【发布时间】:2012-08-14 11:46:54
【问题描述】:
我正在使用subprocess 模块和check_output() 在我的 Python 脚本中创建一个虚拟 shell,它适用于返回零退出状态的命令,但是对于那些不返回异常的命令打印在普通 shell 的输出中会显示的错误。
例如,我希望有这样的事情:
>>> shell('cat non-existing-file')
cat: non-existing-file: No such file or directory
但是,这种情况发生了:
>>> shell('cat non-existing-file')
CalledProcessError: Command 'cat non-existing-file' returned non-zero exit status 1 (file "/usr/lib/python2.7/subprocess.py", line 544, in check_output)
即使我可以使用try 和except 删除Python 异常消息,我仍然希望cat: non-existing-file: No such file or directory 向用户显示。
我该怎么做呢?
shell():
def shell(command):
output = subprocess.check_output(command, shell=True)
finished = output.split('\n')
for line in finished:
print line
return
【问题讨论】:
标签: python shell subprocess