Python subprocess.Popen strange behavior
我正在尝试运行一个进程,当它完成后,请阅读stderr和stdout。 我发现只有这样才能用Python创建一个subprocess.Popen,subprocess.PIPE作为stderr和stdout args,然后读取Popen.stderr和Popen.stdout文件描述符。
1 2 3 4 5 6 7 8 | In [133]: subprocess.call(['python', '-c',"import sys; sys.exit(1)"]) Out[133]: 1 In [134]: p = subprocess.Popen(['python', '-c',"import sys; sys.exit(1)"]) In [135]: p.returncode In [136]: |
我可以获得
1 2 3 4 5 6 7 8 9 10 11 12 | In [143]: p = subprocess.Popen(['python', '-c',"import sys; sys.stderr.write('ook'); sys.exit(1)"], stderr=subprocess.PIPE) In [144]: p.stderr.read() Out[144]: 'ook' In [145]: p.returncode In [146]: p.kill() In [147]: p.returncode In [148]: |
所以我可以读取stderr,这意味着我给subprocess.Popen的命令正在运行,但我无法获得
您必须
1 2 3 4 | >>> p.wait() 1 >>> p.returncode 1 |
或者使用
1 2 3 4 5 6 | >>> stdout, stderr = p.communicate() >>> stdout >>> stderr 'ook' >>> p.returncode 1 |
试试这个:
1 2 3 4 | In [39]: p = subprocess.Popen(['python', '-c',"import sys; sys.exit(1)"]) In [40]: p.poll() Out[40]: 1 |
1 2 3 4 | if (subprocess.call(command, shell=True) != 0): # wait and return returncode attribute # non-zero returncode indicates failure pass |