我試圖運行一個進程,當它完成後,讀取stderr和stdout。我發現只有這樣做的方法是使用Python創建一個subprocess.Popen,並將subprocess.PIPE作爲stderr和stdout參數,然後讀取Popen.stderr和Popen.stdout文件描述符。Python子進程.Popen奇怪的行爲
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]:
我能得到的subprocess.call
返回碼,但我不能得到的subprocess.Popen
返回碼。我也試着閱讀標準錯誤,看看是否真的subprocess.Popen運行命令:
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]:
所以我可以讀標準錯誤,這意味着命令我給subprocess.Popen正在運行,但我不能得到返回碼subprocess.Popen
。有任何想法嗎?