在jupyter笔记本中打印子流程的实时输出



在我的文件'wrapper.py'中,我调用一个子进程并实时将其输出打印到stdout。如果我从控制台调用python脚本,这就很好了。然而,当从jupyter笔记本调用它时,代码挂在proc.stdout.redline((行。以前的所有print语句都可以正常工作。。

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))

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

我使用这个自定义函数来执行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}nt{e.output}',
flush=True, file=sys.stderr)
raise e
print(out)

用例:

run_cmd("pip install emoji")

最新更新