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)?
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