【问题标题】:Print realtime output of subprocess in jupyter notebook在 jupyter notebook 中打印子进程的实时输出
【发布时间】:2021-03-03 08:45:15
【问题描述】:

在我的文件“wrapper.py”中,我调用了一个子进程并将其输出实时打印到标准输出。如果我从控制台调用 python 脚本,这工作得很好。但是,当从 jupyter notebook 调用它时,代码会挂在 proc.stdout.readline() 行。所有以前的打印语句都可以正常工作..

proc = subprocess.Popen(["calc", "input.txt"], cwd=__dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while True:
    out = proc.stdout.readline().decode("utf-8")
    err = proc.stderr.readline().decode("utf-8")
    if out == '' and err == '' and proc.poll() is not None:
        break
    if out:
        print("::::%s"%(out), end='')
    if err:
        print("::::%s"%(err), end='', file=sys.stderr)
rc = proc.poll()
print("---> returns %s"%(rc))

有人知道如何解决这个问题吗?

【问题讨论】:

  • 检查this是否有帮助。
  • 是的,它有帮助!

标签: python jupyter-notebook subprocess ipython


【解决方案1】:

我使用这个自定义函数在 Notebooks 中执行命令。

import subprocess

def run_cmd(cmd: str, stderr=subprocess.STDOUT) -> None:
    """Run a command in terminal

    Args:
        cmd (str): command to run in terminal
        stderr (subprocess, optional): Where the error has to go. Defaults to subprocess.STDOUT.

    Raises:
        e: Excetion of the CalledProcessError
    """
    out = None
    try:
        out = subprocess.check_output(
            [cmd],
            shell=True,
            stderr=stderr,
            universal_newlines=True,
        )
    except subprocess.CalledProcessError as e:
        print(f'ERROR {e.returncode}: {cmd}\n\t{e.output}',
              flush=True, file=sys.stderr)
        raise e
    print(out)

用例:

run_cmd("pip install emoji")

【讨论】:

  • 但这会打印实时输出吗(比如命令需要很长时间才能运行)?正如@yorodm 所指出的,我的问题已经在另一篇文章中得到解答
猜你喜欢
  • 2016-12-01
  • 2019-09-21
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
  • 2017-11-25
相关资源
最近更新 更多