Python subprocess with stdout redirect returning an int

不问归期 提交于 2019-12-22 06:35:36

问题


I am trying to read out data from a set of print statements in a C++ program that is being run using a subprocess.

C++ code:

printf "height= %.15f \\ntilt = %.15f \(%.15f\)\\ncen_volume= %.15f\\nr_volume= %.15f\\n", height, abs(sin(tilt*pi/180)*ring_OR), abs(tilt), c_vol, r_vol; e; //e acts like a print

Python code:

run = subprocess.call('Name', stdout = subprocess.PIPE, env={'LANG':'C++'})
data, error = run.communicate()

However instead of getting the data, all I am getting is a single int, the exit code, either a 0 or an error code. Of course, python then tells me "AttributeError: 'int' object has no attribute 'communicate'".

How do I actually get the data (the printf)?


回答1:


subprocess.call just runs the command and returns its exit status (In python the exit status can be set by sys.exit(N) -- In other languages the exit status is determined by different means). If you want to actually get a handle on the process, you'll need to use subprocess.Popen. So, for your example:

run = subprocess.Popen('Name', stdout = subprocess.PIPE, env={'LANG':'C++'})
data, error = run.communicate()

The programs exit status is now available through the returncode attribute.

Also, as a matter of style, I would either do:

run = subprocess.Popen('Name', stdout = subprocess.PIPE, stderr = subprocess.PIPE, env={'LANG':'C++'})
data, error = run.communicate()

or:

run = subprocess.Popen('Name', stdout = subprocess.PIPE, env={'LANG':'C++'})
data, _ = run.communicate()

Since you're not giving yourself the ability to capture stderr, you probably shouldn't pretend like you got something meaningful.



来源:https://stackoverflow.com/questions/11434515/python-subprocess-with-stdout-redirect-returning-an-int

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