![](/img/trans.png)
[英]Getting the output of a shell command in Jupyter Notebook
[英]Realtime output from a shell command in Jupyter notebook
我告訴jupyter執行python腳本:
!python build_database.py
從終端執行時,python腳本會在執行過程中打印進度。 但是,在jupyter筆記本中,執行后,我將所有輸出打印為字符串列表。 有沒有辦法看到實時輸出?
似乎無法立即使用。 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()
用法:
%runrealcmd ping -c10 www.google.com
上面的代碼可能會寫得更好,但是對於您的需求,它應該是完美的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.