5

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

4

1 回答 1

4

subprocess.call只是运行命令并返回其退出状态(在 python 中,退出状态可以通过sys.exit(N)-- 在其他语言中,退出状态由不同的方式确定)。如果你想真正掌握这个过程,你需要使用subprocess.Popen. 因此,对于您的示例:

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

程序退出状态现在可通过该returncode属性获得。

另外,作为风格问题,我会这样做:

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

或者:

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

既然你没有给自己捕获标准错误的能力,你可能不应该假装你有一些有意义的东西。

于 2012-07-11T14:12:58.660 回答