从C#调用Python脚本并重定向标准输出,无返回结果求助
C#调用Python进程无输出的问题排查与修复
核心问题点
- 输出读取顺序错误:原C#代码先调用
process.WaitForExit()再读取输出,当Python输出缓冲区满时会导致进程阻塞,既无法退出也读不到内容。 - 未捕获错误输出:Python脚本可能存在语法或参数错误,但原代码未读取
StandardError,无法定位问题根源。 - Python脚本参数定义错误:
argparse里的type='str'写法有误,带引号会导致参数解析失败,脚本直接报错退出。 - 路径/参数未加引号:如果Python脚本路径或传入的参数包含空格,未用引号包裹会导致命令行解析错误,Python无法正确识别脚本或参数。
修正后的代码
C#代码
using System; using System.Diagnostics; using System.IO; namespace ExecuteProcess { public class Class1 { static void Main(string[] args) { string pythonExe = @"absolute_path_to_python.exe"; // 路径带空格时用双引号包裹,C#里用@""""表示单个双引号 string scriptPath = @"""absolute_path_to_script_to_be_called_in_solution"""; string scriptArgs = "Hello World"; ProcessStartInfo start = new ProcessStartInfo(); start.FileName = pythonExe; start.Arguments = $"{scriptPath} {scriptArgs}"; start.UseShellExecute = false; start.CreateNoWindow = true; start.RedirectStandardOutput = true; start.RedirectStandardError = true; // 设置UTF8编码避免中文乱码 start.StandardOutputEncoding = System.Text.Encoding.UTF8; start.StandardErrorEncoding = System.Text.Encoding.UTF8; using (Process process = Process.Start(start)) { // 先读取输出和错误,再等待进程退出,避免阻塞 string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); // 控制台输出便于测试 Console.WriteLine("Python输出:"); Console.WriteLine(output); if (!string.IsNullOrEmpty(error)) { Console.WriteLine("Python错误信息:"); Console.WriteLine(error); } // 调试窗口输出 Debug.WriteLine("Python输出:"); Debug.WriteLine(output); Debug.WriteLine("Python错误信息:"); Debug.WriteLine(error); } } } }
Python代码
print("In python script") import argparse parser = argparse.ArgumentParser() # 修正type的写法,去掉多余引号 parser.add_argument("params", type=str, store=True) args = parser.parse_args() def func(params): print(args.params) return args.params func(args.params)
额外注意事项
- 务必使用绝对路径指向Python.exe和脚本文件,路径含空格时必须用双引号包裹。
- 测试时可以先直接在命令行运行Python脚本,确认脚本本身能正常输出内容后,再用C#调用。
- 如果需要传递多个参数,可在Python脚本中用
parser.add_argument("params", type=str, nargs='+')来接收。
内容的提问来源于stack exchange,提问作者eli7
相关产品推荐
相关产品推荐

