从C#执行Python脚本时莫名停滞的问题排查请求
问题分析与解决方案
你的问题核心在于两个关键点:工作目录不匹配导致Python找不到目标文件,以及未捕获标准错误输出无法看到报错详情,这才让你误以为是“莫名停滞”。
可能的原因
- 工作目录不一致:C#启动Python进程时,默认工作目录是你C#程序的运行目录,而非Python脚本所在的
ltrDirectory。当脚本执行open("features.json")时,会在C#程序的目录下查找文件,自然找不到,进而抛出异常(但你看不到),导致进程卡住。 - 未重定向标准错误输出:你的代码只重定向了
StandardOutput,但Python的错误信息会输出到StandardError流,所以你完全看不到报错内容,无法定位问题根源。 - 路径分隔符隐患:你拼接参数时用了
/,虽然Python在Windows下也能识别,但建议用Windows原生的\\或者Path.Combine方法拼接路径,避免潜在的路径解析问题。
修正后的C#代码
ProcessStartInfo start = new ProcessStartInfo(); start.FileName = @"C:\Python27\python.exe"; // 用Path.Combine处理路径,避免分隔符问题 string scriptPath = Path.Combine(ltrDirectory, "train_and_upload_demo_model.py"); string configPath = Path.Combine(ltrDirectory, "config.json"); start.Arguments = $"{scriptPath} -c {configPath}"; start.UseShellExecute = false; // 同时重定向标准输出和错误输出 start.RedirectStandardOutput = true; start.RedirectStandardError = true; // 设置工作目录为脚本所在目录,确保相对路径生效 start.WorkingDirectory = ltrDirectory; using (Process process = Process.Start(start)) { // 先读取错误输出再读标准输出,避免死锁 string error = process.StandardError.ReadToEnd(); string result = process.StandardOutput.ReadToEnd(); process.WaitForExit(); System.Diagnostics.Debug.WriteLine("脚本输出结果:"); System.Diagnostics.Debug.WriteLine(result); if (!string.IsNullOrEmpty(error)) { System.Diagnostics.Debug.WriteLine("脚本错误信息:"); System.Diagnostics.Debug.WriteLine(error); } }
额外调试建议
- 建议在Python脚本里给文件操作加上异常捕获,打印详细错误,方便排查:
import sys try: featuresBody = open("features.json") except Exception as e: print(f"打开features.json失败: {str(e)}", file=sys.stderr) raise - 确认
features.json确实存在于ltrDirectory目录下,检查文件名拼写、大小写(Windows文件名不区分大小写,但最好保持一致)。
内容的提问来源于stack exchange,提问作者Reddy
相关产品推荐
相关产品推荐

