python subprocess.call bash 命令,具有进程替换和文件重定向功能
在 Python 中,我想调用一个在执行时打印到屏幕的脚本,同时还记录 stdout 和 stderr 流。我想要执行以下 bash 代码行:
script.sh > >(tee /tmp/success.log) 2> >(tee /tmp/errors.log >&2)
其中 script.sh 是输出到 stdout 和 stderr 的任何脚本。此行将 stdout 和 stderr 流捕获到日志文件 success.log 和 error.log 中,并将流输出到 stdout,如下所述:如何在使用“tee”和管道时将 stderr 写入文件?
现在我想要执行这是在 python 中使用 subprocess.call(that_command_as_str, shell=True) 执行的,但是 python 使用 /bin/sh 而不是 /bin/bash 来执行命令,并且 vanilla sh 不支持这种类型的重定向。似乎 /bin/sh 的用法被硬编码到子进程模块中。有什么想法吗?
In Python I want to call a script that prints to the screen as it executes while also logging the stdout and stderr streams. I have the following line of bash code that I'd like to execute:
script.sh > >(tee /tmp/success.log) 2> >(tee /tmp/errors.log >&2)
where script.sh is any script that outputs to both stdout and stderr. This line captures the stdout and stderr streams into the log files success.log and errors.log and also outputs the streams to stdout, as explained here: How do I write stderr to a file while using "tee" with a pipe?
Now I want to execute this from within python using subprocess.call(that_command_as_str, shell=True), but python uses /bin/sh to execute the command instead of /bin/bash, and vanilla sh doesn't support that type of redirection. It seems the usage of /bin/sh is hardcoded into the subprocess module. Any Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将您的命令包装在
/bin/bash -c "your-command-stuff"
中。然后 /bin/sh 将运行 bash,它将为您解释其余部分。您还可以考虑使用 Python Subprocess 中的其他函数来执行重定向,但上述应该快速有效。
Wrap your command in
/bin/bash -c "your-command-stuff"
.Then /bin/sh will run bash which will interpret the rest for you. You could also consider using other functions in Python Subprocess to do the redirection, but the above should be quick and effective.