简体   繁体   English

Jupyter Notebook中Shell命令的实时输出

[英]Realtime output from a shell command in Jupyter notebook

I'm telling jupyter to execute a python script: 我告诉jupyter执行python脚本:

!python build_database.py

When executed from the terminal, the python script prints the progress during execution. 从终端执行时,python脚本会在执行过程中打印进度。 However, in the jupyter notebook, I get all output printed as a list of strings, AFTER the execution. 但是,在jupyter笔记本中,执行后,我将所有输出打印为字符串列表。 Is there a way to see the output live? 有没有办法看到实时输出?

It looks like it is not possible out of the box. 似乎无法立即使用。 The output handling of shell commands is buried deep in ipython internals. Shell命令的输出处理深埋在ipython内部。

One of solutions i would recommend is to create custom magic method based on code below. 我建议的解决方案之一是根据以下代码创建自定义魔术方法。

Check this answer 检查这个答案

Based on it i created a simple magic method that you can use: 基于此,我创建了一个可以使用的简单魔术方法:

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

Usage: 用法:

%runrealcmd ping -c10 www.google.com

Above code probably could be written better but for your needs it should be perfectly fine. 上面的代码可能会写得更好,但是对于您的需求,它应该是完美的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM