python subprocess.call bash 命令,具有进程替换和文件重定向功能

标签 python 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,如下所述: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/

相关文章:

python - 通过多级键解析 JSON 值

python - selenium 没有在 FirefoxProfile 中设置 downloaddir

linux - 禁用挂起脚本

bash - 如何将特定分隔符之间的文本捕获到 shell 变量中?

python - 如何在pyqt中创建一个定时器

python - 如何使用 lxml objectify 获取 xmlns 属性?

python - 将类中的方法存储在新文件中

linux - 重定向程序输出

bash - 多行双引号字符串会触发其通过管道传输到的后续单引号命令的历史扩展

linux - 更高效的 shell 文本操作