刷新Jupyter笔记本中的输出文本

时间:2018-06-11 11:31:52

标签: python ipython jupyter-notebook

我需要创建一种可以定期刷新的监视器。那么如何才能正确刷新单元格的输出?当我使用下面的代码刷新文本时,输出窗格在被清除时会折叠,从而产生恼人的屏幕跳转。

from IPython import display
import time
while True:
    o = !netstat
    display.clear_output()
    display.publish_display_data({"text/plain":o.n})
    time.sleep(1)

1 个答案:

答案 0 :(得分:0)

如何使用tk窗口?我在Windows上使用Python 3.6对此进行了测试:

import threading
from subprocess import Popen, PIPE
from time import sleep
import tkinter as tk
from tkinter import *


PROCESS = ['netstat','1']
class Console(tk.Frame):
    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        # undo=False prevents increasing memory use
        self.text = tk.Text(self, undo=False)
        self.text.pack(expand=True, fill="both")
        # run process in a thread to avoid blocking gui
        t = threading.Thread(target=self.execute)
        t.start()


    def display_text(self, p):
        display = ''
        lines_iterator = iter(p.stdout.readline, b"")
        for line in lines_iterator:
            if 'Active' in line:
                self.text.delete('1.0', END)
                self.text.insert(INSERT, display)
                display = ''
            display = display + line 


    def display_text2(self, p):
        while p.poll() is None:
            line = p.stdout.readline()
            if line != '':
                if 'Active' in line:
                    self.text.delete('1.0', END)
                self.text.insert(END, line)
                p.stdout.flush()


    def execute(self):
            p = Popen(PROCESS,  universal_newlines=True,
                   stdout=PIPE, stderr=PIPE)
            print('process created with pid: {}'.format(p.pid))
            self.display_text(p)


if __name__ == "__main__":
    root = tk.Tk()
    root.title("netstat 1")
    Console(root).pack(expand=True, fill="both")
    root.mainloop()