在C#中高效执行Python脚本
利用C#的Process
类可以轻松执行Python脚本,但网络上关于此方法的讨论很多,却鲜有简洁高效的解决方案。
首先,务必将UseShellExecute
设置为false
,以便直接控制可执行文件及其参数。此外,FileName
应指定Python可执行文件的完整路径。
接下来,构建Arguments
字符串,包含Python脚本及其参数。例如,如果code.py
读取file.txt
文件,则Arguments
应为code.py file.txt
。
以下是改进后的C#代码:
<code class="language-csharp">private void run_cmd(string cmd, string args) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = @"C:\Path\to\python.exe"; // 请修改为正确的Python可执行文件路径 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); } } }</code>
为了连续调用Python脚本,可以考虑在其中使用run_cmd()
方法的while
循环。
以上是如何有效地从C#执行Python脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!