Jupyter 笔记本中 Python 子进程的实时标准输出输出 [英] Live stdout output from Python subprocess in Jupyter notebook

查看:66
本文介绍了Jupyter 笔记本中 Python 子进程的实时标准输出输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用子进程从 Python (3.5.2) 脚本运行命令行程序,我在 Jupyter 笔记本中运行该脚本.子进程需要很长时间才能运行,因此我希望将其标准输出实时打印到 Jupyter 笔记本的屏幕上.

I'm using subprocess to run a command line program from a Python (3.5.2) script, which I am running in a Jupyter notebook. The subprocess takes a long time to run and so I would like its stdout to be printed live to the screen in the Jupyter notebook.

在从终端运行的普通 Python 脚本中,我可以毫无问题地做到这一点.我这样做:

I can do this no problem in a normal Python script run from the terminal. I do this using:

def run_command(cmd):
from subprocess import Popen, PIPE
import shlex

with Popen(shlex.split(cmd), stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='')
    exit_code = p.poll()
return exit_code

但是,当我在 Jupyter 笔记本中运行脚本时,它不会将标准输出实时打印到屏幕上.相反,它会在子进程完成运行后打印所有内容.

However, when I run the script in a Jupyter notebook, it does not print the stdout live to the screen. Instead, it prints everything after the subprocess has finished running.

有人对如何解决这个问题有任何想法吗?

Does anyone have any ideas on how to remedy this?

非常感谢,约翰尼

推荐答案

ipython notebook 有它自己的 支持运行 shell 命令.如果您不需要使用子流程进行捕获,则可以执行

The ipython notebook has it's own support for running shell commands. If you don't need to capture with subprocess stuff you can just do

cmd = 'ls -l'
!{cmd}

使用 ! 执行的命令的输出自动通过笔记本传送.

Output from commands executed with ! is automatically piped through the notebook.

这篇关于Jupyter 笔记本中 Python 子进程的实时标准输出输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆