在 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,如下所述:How do I write stderr to a file while using "tee" with a pipe?
现在我想使用 subprocess.call(that_command_as_str, shell=True) 从 python 中执行此命令,但 python 使用/bin/sh 而不是/bin/bash 来执行命令,而 vanilla sh 不支持该命令重定向类型。似乎/bin/sh 的用法被硬编码到子进程模块中。有什么想法吗?
最佳答案
将命令包装在 /bin/bash -c "your-command-stuff"
中。
然后/bin/sh 将运行 bash,它将为您解释其余部分。您还可以考虑使用 Python Subprocess 中的其他函数来进行重定向,但上述应该是快速且有效的。
关于python subprocess.call bash 命令,具有进程替换和文件重定向功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6067173/