从C#调用带输入的Python脚本无响应问题求助
问题分析
你的代码卡在exeProcess.StandardOutput.ReadToEnd()的核心原因是:
- Python脚本使用了
input()函数,需要读取用户输入,但你的C#代码只重定向了标准输出(StandardOutput)和标准错误(StandardError),没有重定向标准输入(StandardInput),导致Python进程一直处于等待输入的状态,无法输出任何内容,进而让ReadToEnd()一直阻塞等待。 - 当
CreateNoWindow = true时,Python的控制台输入界面被完全禁用,自然看不到输入提示;设为false时窗口闪一下,是因为Python进程在等待输入,但没有可交互的输入渠道,最终陷入无响应状态。
解决方案
根据你的需求,提供两种可行方案:
方案1:保留Python脚本的交互输入(C#处理输入传递)
修改C#代码,重定向StandardInput,同时避免同步读取输出导致的死锁:
string path = @"C:\Program Files\Python311\python.exe"; string input = @"C:\app\new_7.py"; ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = path; startInfo.Arguments = $"\"{input}\""; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.RedirectStandardInput = true; // 新增:重定向标准输入 using (Process exeProcess = Process.Start(startInfo)) { // 给Python脚本传递输入(示例直接传入"A1",也可通过C#输入框获取用户输入) exeProcess.StandardInput.WriteLine("A1"); exeProcess.StandardInput.Close(); // 关闭输入流,告知Python输入结束 // 异步读取输出和错误,避免死锁 string output = await exeProcess.StandardOutput.ReadToEndAsync(); string error = await exeProcess.StandardError.ReadToEndAsync(); exeProcess.WaitForExit(); if (exeProcess.ExitCode == 0) MessageBox.Show("External program is executed successfully."); else MessageBox.Show($"External program execution failed. Error: {error}"); output = output?.TrimEnd('\r', '\n') ?? string.Empty; MessageBox.Show(output); }
方案2:通过命令行参数传递任务名(取消Python的input交互)
修改Python脚本,直接从命令行参数读取任务名,避免等待用户输入:
import sys # 从命令行参数获取任务名,索引0是脚本名,索引1为传入的参数 if len(sys.argv) >= 2: TaskName = sys.argv[1] else: TaskName = "DefaultTask" # 可设置默认值或抛出异常 print(TaskName)
然后修改C#代码的参数部分,直接传递任务名:
startInfo.Arguments = $"\"{input}\" A1"; // "A1"即为要传递的任务名
这种方案无需处理输入重定向,不会出现阻塞问题,适合不需要交互的场景。
关键注意点
- 同时重定向标准输入、输出、错误时,不要先调用同步的ReadToEnd()再处理输入,这会导致死锁:进程等待输入,代码等待进程输出,双方互相阻塞。推荐使用异步读取或单独线程分别处理输入输出。
- 如果必须保留控制台交互,不要设置
CreateNoWindow = true,可设置startInfo.WindowStyle = ProcessWindowStyle.Normal让控制台窗口正常显示,供用户输入。
内容的提问来源于stack exchange,提问作者Pankaj_Sen
相关产品推荐
相关产品推荐

