【问题标题】:Running python script on C# and getting output continuously在 C# 上运行 python 脚本并连续获取输出
【发布时间】:2018-11-19 17:32:10
【问题描述】:

我正在尝试从 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)

【问题讨论】:

  • 我们是否假设您获得了输出,但您一次获得了所有输出?问题中没有说明这一点。
  • 我得到了输出,但在 5 秒结束时。
  • 默认情况下print 不会刷新输出。有几种方法可以做到这一点,具体取决于您的 python 版本。见:stackoverflow.com/questions/230751/…

标签: c#


【解决方案1】:

将您的 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";

当标准输出被重定向时,在控制台上写入一行时不会引发 C# 中的事件,因为没有调用 stdout.flush;

在每个 print 语句之后放置一个 stdout.flush() 语句可以使事件按应有的方式触发,并且 C# 现在会在输出时捕获它。

或者你可以只使用 -u 开关。

【讨论】:

  • 这非常有效。显然我不知道冲洗机制。
  • 请注意,如果您不想修改 python 代码,还有其他方法可以完成此操作。在您的问题下查看我的链接。命令行参数-u 将使用无缓冲流。
  • -u 工作完美
猜你喜欢
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 2019-07-29
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 2017-05-15
相关资源
最近更新 更多