简体   繁体   English

在 C# 上运行 python 脚本并持续获取输出

[英]Running python script on C# and getting output continuously

I'm trying to run a python script from C# and I want to get the output line by line and not at the end.我正在尝试从 C# 运行一个 python 脚本,我想逐行而不是最后获得输出。 I feel like I'm missing something important, but don't know what.我觉得我错过了一些重要的东西,但不知道是什么。 This is what I have so far:这是我到目前为止:

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);
}

And the python code:和python代码:

import time

for i in range(5):
    print("Hello World " + str(i))
    time.sleep(1)

change your python code to the following:将您的python代码更改为以下内容:

import time
import sys
for i in range(5):
    print("Hello World " + str(i))
    sys.stdout.flush()
    time.sleep(1)

or just edit your c# code and use -u switch:或者只是编辑您的 c# 代码并使用 -u 开关:

var cmd = "-u C:/Users/user/Documents/script.py";

When standard output it was being redirected, the event in C# wasn't being raised when a line was written on console because there were no calls to stdout.flush;当标准输出被重定向时,在控制台上写入一行时不会引发 C# 中的事件,因为没有调用 stdout.flush;

Putting a stdout.flush() statement after each print statement made the events fire as they should and C# now captures the output as it comes.在每个打印语句之后放置一个 stdout.flush() 语句会使事件按原样触发,C# 现在可以捕获输出。

Or you could just use -u switch.或者你可以只使用 -u 开关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM