如何使用 os.system() 到 运行 `> >(tee -a log)`?

How to use os.system() to run `> >(tee -a log)`?

我在终端中运行下面的命令。

sh -c "echo out; echo err 2>&1" >>(tee -a stdout.log) 2>>(tee -a stdout.log >&2)

输出:

out  
err

在Python中使用os.system会报错

import os
cmd = """
sh -c "echo out; echo err 2>&1" > >(tee -a stdout.log) 2> >(tee -a stdout.log >&2)
"""
os.system(cmd)
sh: -c: line 1: syntax error near unexpected token `>'
sh: -c: line 1: `sh -c "echo out" > >(tee -a stdout.log) 2> >(tee -a stdout.log >&2)'

>(...) 是 bash 特定的语法。使 bash -c 而不是 sh -c.

此外,您应该将整个命令括在引号中,因为 -c 需要一个参数。

cmd = """
bash -c 'echo out > >(tee -a stdout.log) 2> >(tee -a stdout.log >&2)'
"""

要像您的原始示例一样测试对 stdout 和 stderr 的写入,请尝试使用花括号:

cmd = """
bash -c '{ echo out; echo err 2>&1; } > >(tee -a stdout.log) 2> >(tee -a stdout.log >&2)'
"""