从 Python 脚本子进程获取输出 [英] Getting output from a Python script subprocess
问题描述
这可能是一个愚蠢的问题,但我有一个 Python 脚本来启动一个子进程(也是一个 Python 脚本),我需要该子进程返回三个整数.如何从启动子进程的 Python 脚本中获取这些返回值?我是否必须将整数输出到标准输出,然后使用 check_output() 函数?
This may be a stupid question but I have a Python script that starts a subprocess (also a Python script) and I need that subprocess to return three integers. How do I get those return values from the Python script that starts the subprocess? Do I have to output the integers to stdout and then use the check_output() function?
推荐答案
答案是是...我想要 +15 的声望!!:-D
The answer is Yes... I want my +15 reputation!! :-D
不,真的......一旦你开始处理子进程,你真正需要与它们通信的唯一方法就是通过文件(这就是stdout
、stderr
最后就是这样)
No, seriously... Once you start dealing with subprocesses, the only way you really have to communicate with them is through files (which is what stdout
, stderr
and such are, in the end)
所以你要做的就是获取输出并检查发生了什么(可能还有生成的进程'exit_code
,如果一切顺利,它将为零)请记住stdout
的内容(您将使用 check_output
函数获得)是一个字符串.因此,为了获得这三个项目,您必须以某种方式拆分该字符串...
So what you're gonna have to do is grab the output and check what happened (and maybe the spawned process' exit_code
, which will be zero if everything goes well) Bear in mind that the contents of stdout
(which is what you'll get with the check_output
function) is an string. So in order to get the three items, you'll have to split that string somehow...
例如:
import subprocess
output = subprocess.check_output(["echo", "1", "2", "3"])
print "Output: %s" % output
int1, int2, int3 = output.split(' ')
print "%s, %s, %s" % (int1, int2, int3)
这篇关于从 Python 脚本子进程获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!