2011-05-20 42 views
2

在Python中,我想调用一个脚本,它在执行时打印到屏幕上,同时还记录stdout和stderr流。我的bash的下面一行代码,我想执行:python subprocess.call bash命令与进程替换和文件重定向

script.sh > >(tee /tmp/success.log) 2> >(tee /tmp/errors.log >&2) 

其中script.sh是输出到标准输出和标准错误的任何脚本。这一行捕获stdout和stderr流到日志文件success.log和errors.log中,并且还输出流到stdout,如下所述:How do I write stderr to a file while using "tee" with a pipe?

现在我想在python中使用subprocess.call( that_command_as_str,shell = True),但是python使用/ bin/sh来执行命令而不是/ bin/bash,而且vanilla sh不支持这种类型的重定向。看起来/ bin/sh的用法被硬编码到子进程模块中。有任何想法吗?

回答

3

把你的命令换成/bin/bash -c "your-command-stuff"

然后/ bin/sh会运行bash,它会为您解释其余的。您也可以考虑在Python子流程中使用其他函数来执行重定向,但上述内容应该快速有效。

+1

谢谢,调用/ bin/bash直接很有效。我真的不认为有一种方法可以仅使用子流程模块轻松实现此功能。 – Cogan 2011-05-20 13:31:44