带有标准输出重定向的

带有标准输出重定向的

本文介绍了带有标准输出重定向的 Python 子进程返回一个 int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

然而,我得到的不是数据,而是一个整数,即退出代码,0 或错误代码.当然,python 然后告诉我AttributeError: 'int' object has no attribute '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'".

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

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

推荐答案

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

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

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

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

或:

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

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

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

这篇关于带有标准输出重定向的 Python 子进程返回一个 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:37