在Python中将文本输出到多个终端

问题描述 投票:0回答:3

(我使用Python和ArchLinux)

我正在用 Python 编写一个简单的人工智能作为学校项目。因为这是一个学校项目,并且我想清楚地演示它在做什么,所以我的目的是有一个不同的终端窗口来显示每个子进程的打印输出 - 一个终端显示句子如何被解析,一个显示 pyDatalog 正在做什么,一个用于实际的输入输出聊天等,可能在两台显示器上。

据我所知,这并不多,有几种可行的方法可以解决这个问题,即对每个子进程进行线程处理并从那里计算出显示,或者编写/使用允许我制作和配置自己的窗口的库。

我的问题是,这些是最好的方法,还是有一种简单的方法可以同时输出到多个终端。另外,如果制作我自己的窗口(如果我说“制作我自己的窗口”时我的术语是错误的,我很抱歉。我的意思是在Python中构建我自己的输出区域)是最好的选择,我正在寻找哪个库我应该用它。

python shell terminal
3个回答
4
投票

所以你可以朝多个方向发展。您可以创建一个 Tkinter(或您选择的 GUI 库)输出文本框并写入其中。此选项可以让您最大程度地控制如何显示数据。

另一种选择是通过命名管道访问多个终端。这涉及到用管道生成一个 xterm 并将输出泵送到它以写入屏幕上。请参阅此问题和示例:

使用Python的子进程在新的Xterm窗口中显示输出


4
投票

我喜欢@ebarr的答案,但一种快速而肮脏的方法是写入多个文件。然后,您可以打开多个终端并尾随文件。


0
投票

我遇到了同样的问题,所以我制作了一个使用 tkinter 和线程的简短程序: https://github.com/tylerebowers/multiTerminal-Python

from time import sleep
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
import threading
class terminal(threading.Thread):
    def __init__(self, title="Terminal", height=20, width=100, font=("Courier New", "12")):
        self.title = title
        self.height = height
        self.width = width
        self.font = font
        self.root = None
        self.st = None
        threading.Thread.__init__(self)
        self.daemon = True  # terminate when the main thread terminates
        self.start()
        sleep(0.5)  # wait for window to open

    def callback(self):
        self.root.destroy()
        self.root = None
        self.st = None

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)
        self.root.title(self.title)
        self.st = ScrolledText(self.root, height=self.height, width=self.width, font=self.font)
        self.st.pack()
        self.root.mainloop()

    def print(self, toPrint):
        if self.root is None or self.st is None:
            return None  # window has been closed; raise error?
        else:
            self.st.configure(state="normal")
            self.st.see("end")  # show last line printed (could also put this under "insert" but there would be a gap)
            self.st.insert("end", toPrint)
            self.st.configure(state="disabled")
#make new terminals
t1 = terminal()
t2 = terminal(title="Customized Terminal", height=30, width=80, font=("Arial", "16"))
#use the new terminals
for i in range(11):
    print(f"Main terminal: {i}")
    t1.print(f"Terminal 1: {i}\n")
    t2.print(f"Terminal 2: {i}\n")
    sleep(0.1)

t1.print("This is Terminal 1\n")
t2.print("This is Terminal 2\n")
print("This is the main terminal")
print("Exiting in 10 seconds")
sleep(10)
quit()
© www.soinside.com 2019 - 2024. All rights reserved.