捕获python程序的标准输出 [英] Capture standard output of a python program as it happens

查看:239
本文介绍了捕获python程序的标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个C#程序,以捕获python程序中的标准输出.我的问题是所有输出都在程序执行之后而不是实际发生时发出.例如,对于此python程序:

I'm trying to write a C# program that captures the standard output in a python program. My problem is that all of the output comes after the program has executed rather than when it actually happens. As an example, for this python program:

print "Hello"
time.sleep(2)
print "Hello"

我希望得到"Hello",两秒钟的间隔,然后再得到"Hello".实际结果是两秒钟的间隔,然后是"Hello","Hello".

I would expect to get "Hello", a two second gap, and then another "Hello". The actual result is a two second gap and then "Hello", "Hello".

如果我从命令行运行上述python脚本,则会得到所需的行为.如果命令提示符可以做到这一点,那么我应该能够模仿该功能,而不必反复刷新缓冲区.

If I run the above python script from the command line, I get the desired behaviour. If the command prompt can do this, then I should be able to mimic that functionality without having to flush the buffer repeatedly.

我正在使用它从C#运行该过程:

I'm using this to run the process from C#:

_proc = new Process
            {
                StartInfo = new ProcessStartInfo
                                {
                                    FileName = "C:\\Python27\\python.exe",
                                    Arguments = pyScript,
                                    RedirectStandardError = true,
                                    UseShellExecute = false,
                                    RedirectStandardOutput = true,
                                    CreateNoWindow = true
                                }
            };
_proc.OutputDataReceived += ProcOnOutputDataReceived;
_proc.Start(); 
_proc.BeginOutputReadLine();

我可以运行此C#代码(并更改上面的ProcessStartInfo属性以运行C#可执行文件),并且它的行为正确:

I can run this C# code (and changing the ProcessStartInfo properties above to run C# executable) and it behaves correctly:

Console.WriteLine("Hello");
Thread.Sleep(2000);
Console.WriteLine("Hello");

使用此代码,我得到"Hello",两秒钟的间隔,然后得到另一个"Hello".

With this code I get "Hello", a two second gap, and then another "Hello".

知道为什么吗?如何获取python解释器以在发生标准情况时发送标准输出?

Any idea why? How can I get the python interpreter to send the standard output as it happens?

推荐答案

我知道这很旧,但是使用-u(无缓冲)运行python似乎就是你想要的

I know this is old but running python with -u (unbuffered) seems to be what you were after

这篇关于捕获python程序的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆