Python subprocess on Windows 7 64bit - no output when stdout=PIPE

ⅰ亾dé卋堺 提交于 2019-12-14 03:45:39

问题


Apologies for another question about Python subprocesses, but I couldn't find an answer to this one.

I am having trouble with some Python code which calls a subprocess on Windows 7 64-bit. When the subprocess's stdout is sent to a pipe, no output is produced. The subprocess appears to run and terminate without problems, it just doesn't produce any output.

EDIT: The same code works correctly on WinXP 32bit, so I updated the question title.

# (listing 1)
from subprocess import *
#cmdline= (a valid command line)
proc = Popen(cmdline,shell=True,stdout=PIPE,stderr=PIPE)
out, err = proc.communicate()
print( out )
print( err )

This gives output

out:

err:

However, when the subprocess's output is not piped, it produces output as expected:

# (listing 2)
proc = Popen(cmdline,shell=True)
proc.communicate()

This gives the expected output to console.

I'm confident the executable is actually writing its output to stdout. I have the C source code, and I added the line:

fprintf(stdout, "HELLO");

Again, "HELLO" is seen when running listing 2, but not listing 1.

I also tried making a new C++ executable and calling that from cmdline:

#include <iostream>

int main()
{
    std::cout << "HELLO" << std::endl;
}

The same thing still happens - "HELLO" is seen when running listing 2, but not listing 1.

If I set cmdline to 'dir', the expected thing happens for both listing 1 and listing 2 - directory contents are printed to the console.

Other things I tried: Python 3.3 and Python 2.7 (same results); bufsize=0 (same results); checking proc.returncode (it's 0, as expected); removing stderr=PIPE (in which case listing 1 gives "err: None" as expected).

EDIT - I also tried out = proc.stdout instead of the communicate() method with the same results. Python documentation and other questions suggest the communicate() method is the right one to use.


回答1:


It's not a Python problem at all. My firewall settings had "sandboxed" the executables, and this caused their output to be discarded without any kind of warning or error.

It would have made more sense to prevent them from executing. I think I need to use different firewall software.



来源:https://stackoverflow.com/questions/12759431/python-subprocess-on-windows-7-64bit-no-output-when-stdout-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!