從 C# 無縫執行 Python 腳本
本文探討了從 C# 執行 Python 腳本的核心問題。提供的代碼旨在運行一個簡單的 Python 腳本,該腳本讀取指定文件的內容。但是,最初的方法遇到了挑戰,導致瞭如何使用原生方法實現此目標的問題。
問題分析
初始實現中遇到的主要問題源於將 UseShellExecute 設置為 false。這禁用了系統 shell 的使用,需要顯式指定 Python 可執行文件的完整路徑並正確格式化命令參數。
改進方法
為了糾正這個問題,修改後的代碼提供了一個改進的實現:
private void run_cmd(string cmd, string args) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = "my/full/path/to/python.exe"; start.Arguments = string.Format("{0} {1}", cmd, args); start.UseShellExecute = false; start.RedirectStandardOutput = true; using(Process process = Process.Start(start)) { using(StreamReader reader = process.StandardOutput) { string result = reader.ReadToEnd(); Console.Write(result); } } }
關鍵考慮因素
以上是如何使用本機方法從C#執行Python腳本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!