带有stdout重定向的Python子进程返回一个int



我正试图从使用子进程运行的C++程序中的一组打印语句中读取数据。

C++代码:

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代码:

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

然而,我得到的不是数据,而是一个int,一个退出代码,一个0或一个错误代码。当然,python然后告诉我"AttributeError:'int'对象没有属性'communication'"。

我如何实际获得数据(printf)?

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

既然你没有给自己捕获stderr的能力,你可能不应该假装你得到了一些有意义的东西。

最新更新