Jupyter 笔记本中 shell 命令的实时输出

Ben*_*nni 7 python jupyter-notebook

我告诉 jupyter 执行一个 python 脚本:

!python build_database.py
Run Code Online (Sandbox Code Playgroud)

从终端执行时,python 脚本会打印执行过程中的进度。但是,在 jupyter notebook 中,我在执行后将所有输出打印为字符串列表。有没有办法实时查看输出?

Kam*_*ski 7

看起来不可能开箱即用。shell 命令的输出处理深埋在 ipython 内部。

我推荐的解决方案之一是根据下面的代码创建自定义魔术方法。

检查这个答案

基于它,我创建了一个简单的魔术方法,您可以使用它:

from subprocess import Popen, PIPE, STDOUT

from IPython.core.magic import register_line_magic


@register_line_magic
def runrealcmd(command):
    process = Popen(command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True)
    for line in iter(process.stdout.readline, b''):
        print(line.rstrip().decode('utf-8'))
    process.stdout.close()
    process.wait()
Run Code Online (Sandbox Code Playgroud)

用法:

%runrealcmd ping -c10 www.google.com
Run Code Online (Sandbox Code Playgroud)

上面的代码可能会写得更好,但对于您的需要,它应该完全没问题。