【发布时间】:2015-06-17 07:23:09
【问题描述】:
当使用子进程运行 bash 命令时,我可能会遇到命令无效的情况。在这种情况下,bash 将返回错误消息。我们怎样才能捕捉到这个消息?我想将此消息保存到日志文件中。 以下是一个示例,我尝试列出不存在目录中的文件。
try:
subprocess.check_call(["ls", "/home/non"])
df = subprocess.Popen(["ls", "/home/non"], stdout=subprocess.PIPE)
output, err = df.communicate()
# process outputs
except Exception as error:
print error
sys.exit(1)
Bash 会打印“ls: cannot access /home/non: No such file or directory”。我怎样才能得到这个错误信息? except 行捕获的错误明显不同,它说“命令'['ls','/home/non']'返回非零退出状态2”。
【问题讨论】:
-
我认为你需要重定向两个:即
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,然后错误消息将在err。 -
@martineau 感谢您的建议。我刚刚检查过,如果将“stderr=...”添加到 Popen,则会在输出中显示错误消息。如果有的话,我更喜欢通过 excpet 行捕获此消息的方法。有什么想法吗?
-
为此,您需要进程间通信。因为
subprocess.Popen()可以启动任何其他类型的困难进程。关于您唯一的常规选项是returncode和管道。考虑使用subprocess.check_output而不是Popen。
标签: python bash error-handling subprocess