问题描述
我在终端中运行以下命令。
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)'
"""