如何从Python调用`time`并且只返回stderr

问题描述 投票:0回答:1

如果命令本身输出 stderr,如何才能捕获

/usr/bin/time
的输出?

import subprocess
print(subprocess.run('/usr/bin/time -p foo', capture_output=True, shell=True).stderr.decode())

打印

foo_stderr
real 0.02
user 0.01
sys 0.00

我知道(而不是寻找答案)以下选项:

  • 将输出写入文件(例如 GNU
    time --output file
  • 处理捕获的输出以过滤掉相关数据
python time subprocess command stderr
1个回答
0
投票

在自己的 shell 中执行

foo
,并重定向其 stderr。

print(subprocess.run(['/usr/bin/time', '-p', 'bash', '-c', 'foo 2>/dev/null'], capture_output=True).stderr.decode())
© www.soinside.com 2019 - 2024. All rights reserved.