我必须通过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()'? –