我正在尝试从C#运行python脚本,我想逐行而不是最后获取输出。我觉得自己缺少了一些重要的东西,但是不知道是什么。这是我到目前为止的内容:
static void Main(string[] args)
{
var cmd = "C:/Users/user/Documents/script.py";
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "C:/Users/user/AppData/Local/Programs/Python/Python36/python.exe",
Arguments = cmd,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
},
EnableRaisingEvents = true
};
process.ErrorDataReceived += Process_OutputDataReceived;
process.OutputDataReceived += Process_OutputDataReceived;
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
process.WaitForExit();
Console.Read();
}
static void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
还有python代码:
import time
for i in range(5):
print("Hello World " + str(i))
time.sleep(1)
答案 0 :(得分:3)
将您的python代码更改为以下内容:
import time
import sys
for i in range(5):
print("Hello World " + str(i))
sys.stdout.flush()
time.sleep(1)
或仅编辑您的C#代码并使用-u开关:
var cmd = "-u C:/Users/user/Documents/script.py";
当标准输出被重定向时,由于没有调用stdout.flush,因此在控制台上编写一行代码时并没有引发C#中的事件;
在每个print语句之后放置stdout.flush()语句会使事件按预期方式触发,而C#现在会捕获输出。
或者您可以只使用-u开关。