Popen.communicate() returns (None, None) 即使脚本打印结果

Popen.communicate() returns (None, None) even if script print results

我对 Popen.communicate() 有疑问。

我有 return 字符串的脚本。

然后我编写了第二个脚本,它采用该变量。

v = "./myscript arg1 arg2"
com = subprocess.Popen(v, shell=True).communicate()
print com

com returns (None, None)。关键是我可以先在脚本中打印结果, shell 也打印结果。我不能只将该打印分配给变量。

当然是第一个脚本return的值,不是打印出来的。

来自docs

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

因此,创建 Popen 对象:

subprocess.Popen("./myscript arg1 arg2", shell=True,
                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)