【问题标题】:How to both capture shell command output AND show it in terminal at realtime?如何同时捕获 shell 命令输出并在终端中实时显示?
【发布时间】:2020-02-06 16:46:47
【问题描述】:

我写了一个函数,它运行外部命令并捕获它们的输出,就像这样

    proc = subprocess.run(command_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if proc.returncode != 0:

不幸的是,我在运行时看不到长命令输出。如何有条件地执行此操作,例如,如果 loglevel 为 debug 或更高?

【问题讨论】:

  • 我不确定你在问什么。你想要一个在终端上打印输出的“调试模式”吗?
  • 是的,像这样。我想控制打印输出与否,但始终捕获它
  • 您是否考虑过使用check_output() 而不是run()
  • 如何使用check_output()打开和关闭打印?
  • 输出 = check_output(...)。您可以根据需要打印或不打印

标签: python python-3.x subprocess stdout


【解决方案1】:

此代码将在收到命令输出后立即打印:

import sys
import subprocess
try:
    proc = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        shell=shell)
except OSError as e:
    print('Error executing command', command, e)
    raise
for stdout_line in iter(proc.stdout.readline, b''):
    sys.stdout.write(stdout_line)
    sys.stdout.flush()
proc.stdout.close()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多