福州網站建設>網站新聞>電腦網絡

        c#將一個文件路徑作為參數傳遞給py,py對該路徑中文件進行操作

        發布日期:2023-05-29瀏覽次數:433 來源:福州網站建設

        你可以使用C#的Process類來調用Python腳本并將文件路徑作為參數傳遞給它。以下是一個示例代碼:

        using System.Diagnostics;
        
        public void CallPythonScript(string filePath)
        {
            string pythonPath = "C:/Python37/python.exe"; // 設置Python解釋器的路徑
            string scriptPath = "C:/scripts/script.py"; // 設置Python腳本的路徑
        
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = pythonPath;
            start.Arguments = string.Format("{0} {1}", scriptPath, filePath);
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
        
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    Console.Write(result);
                }
            }
        }

        在上面的代碼中,我們使用ProcessStartInfo類來設置要啟動的Python解釋器和腳本的路徑,并將文件路徑作為參數傳遞給腳本。然后,我們使用Process類來啟動Python進程并等待它完成。最后,我們將Python腳本輸出的結果讀取并在控制臺上打印出來。

        在Python腳本中,你可以使用sys.argv來獲取傳遞給腳本的參數,并使用標準Python庫來對文件進行操作。以下是一個示例代碼:

        import sys
        import os
        
        if len(sys.argv) > 1:
            filePath = sys.argv[1]
            if os.path.exists(filePath):
                with open(filePath, 'r') as file:
                    contents = file.read()
                    # 在這里對文件內容進行操作
                    print(contents.upper()) # 將文件內容轉換為大寫并輸出
            else:
                print("文件不存在")
        else:
            print("請提供文件路徑作為參數")

        以上是由福州網站建設的小編為你分享了"c#將一個文件路徑作為參數傳遞給py,py對該路徑中文件進行操作"文章,如果你在這方面有什么問題,隨時聯系我們

        電腦網絡有關的文章
        如果您有什么問題,歡迎咨詢我們客服! 點擊QQ咨詢