我必須通過python腳本運行「提交」命令並根據其退出或返回狀態打印消息。如何使用python中的子進程獲取退出狀態?
代碼如下:
import subprocess
msg = 'summary about commit'
commitCommand = 'hg commit -m "{}"'.format(msg)
p = subprocess.Popen(commitCommand, stdout=subprocess.PIPE)
output = p.communicate()[0]
if p.returncode:
print 'commit failed'
sys.exit()
else:
print 'Commit done'
這是給我以下錯誤:
Traceback (most recent call last):
File "script.py", line 66, in <module>
p = subprocess.Popen(commitCommand, stdout=subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
如何糾正這個錯誤?
'進口shlex; ...; subprocess.Popen(shlex.split(commitCommand),...)'。 [相關問題](http://stackoverflow.com/q/21029154/510937),['Popen']的文檔(http://docs.python.org/2/library/subprocess.html#subprocess.Popen) (你應該閱讀)。 – Bakuriu
@Bakuriu:爲什麼在OP構建字符串時使用'shlex.split()'? –