python - Jupyter notebook 中 shell 命令的实时输出
问题描述
我告诉 jupyter 执行一个 python 脚本:
!python build_database.py
从终端执行时,python 脚本会打印执行过程中的进度。但是,在 jupyter notebook 中,我在执行之后将所有输出打印为字符串列表。有没有办法实时查看输出?
解决方案
看起来不可能开箱即用。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()
或者Popen
可以用作上下文管理器。因此,代码将更具可读性和可靠性。查看文档
通过 with 语句支持 Popen 对象作为上下文管理器:退出时,标准文件描述符被关闭,并等待进程。
from subprocess import Popen, PIPE, STDOUT
from IPython.core.magic import register_line_magic
@register_line_magic
def runrealcmd(command):
with Popen(
command, stdout=PIPE, shell=True, stderr=STDOUT, bufsize=1, close_fds=True
) as process:
for line in iter(process.stdout.readline, b""):
print(line.rstrip().decode("utf-8"))
用法:
%runrealcmd ping -c10 www.google.com
上面的代码可能可以写得更好,但根据您的需要,它应该非常好。
推荐阅读
- c# - 是否可以在 MySqlCommand 中使用 MySql 赋值运算符 (:=)?
- java - 在 Spring 应用程序中将数据存储在 Threadlocal 中的替代方法
- javascript - javascript 仅适用于页面重新加载(安装了 rails、turbolinks)
- r - 由于大小,无法将 CSV 文件导入 R
- c# - 如何从 C# 中的内存位置读回一个值?
- django - 在 django 模板中检查用户权限
- c - 我在 CodeVisionAVR 中使用 ATmega164 的吉他调音器代码不能处理超过 4 个样本
- c# - 字典
强类型对象 - angular - 如何从firestore集合实时同步列表(组件+服务)
- javascript - 将数组转换为字典时返回虚假的非法对