我正在尝试为我前一段时间创建的GUI添加一些功能,特别是我需要的功能是一个文本小部件,我发送的终端命令显示它们的输出。重定向器类目前看起来像这样:
class StdRed(object):
def __init__(self, textwid):
self.text_space = textwid
def write(self, text):
self.text_space.config(state=NORMAL)
self.text_space.insert(END,text)
self.text_space.see(END)
self.text_space.update_idletasks()
self.text_space.config(state=DISABLED)
def flush(self):
pass
确实有效。我用os.system(...)命令替换了打开终端命令
a = subprocess.Popen(命令,stdout = PIPE,stderr = STDOUT,shell = True)
我读了stdout通过:b = a.stdout.read()
没有一个问题(不幸的是我需要shell = True,否则我需要调用的一些程序失败了)。之后我尝试在tkinter文本小部件上有一个实时输出,所以我改变了b - >
while True:
b = a.stdout.readline().rstrip()
if not b:
break
print b
但似乎输出仅在被调用的进程结束时出现,即像一个简单的C软件
for(int i = 0; i <100000; i ++){cout << i <<'\ n';}
将打印非常缓慢(我慢慢地评论,因为一个简单的“ls”命令将逐行逐行打印)for循环结束时的所有数字。除此之外,我注意到在通过子进程调用的程序运行时,GUI被冻结。关于如何解决这些问题的任何想法?
编辑:
我创建了一个使用多处理类和Popen运行命令的简单终端:
from Tkinter import *
from multiprocessing import Process, Pipe, Queue
import sys
from subprocess import PIPE, Popen, STDOUT
root = Tk()
root.title("Test Terminal")
root.resizable(False, False)
class StdRed(object):
def __init__(self, textwid):
self.text_space = textwid
def write(self, text):
self.text_space.config(state=NORMAL)
self.text_space.insert(END,text)
self.text_space.see(END)
self.text_space.update_idletasks()
self.text_space.config(state=DISABLED)
def flush(self):
pass
terminal = Frame(root, bd=2, relief=GROOVE)
terminal.grid(row=0, sticky='NSEW')
TERM = Label(terminal, text='TERMINAL', font='Helvetica 16 bold')
TERM.grid(row=0, pady=10, sticky='NSEW')
termwid = Text(terminal, height=10)
termwid.grid(row=1, sticky='NSEW')
termwid.configure(state=DISABLED, font="Helvetica 12")
sys.stdout = StdRed(termwid)
enter = StringVar()
enter.set("")
termen = Entry(terminal, textvariable=enter)
queue = Queue(maxsize=1)
a = None
def termexe(execute):
a = Popen(execute, shell=True, stdout=PIPE, stderr=STDOUT)
while True:
line = a.stdout.readline().rstrip()
if not line:
break
else:
queue.put(line)
queue.put('')
def labterm(thi):
if queue.empty():
if thi != None:
if thi.is_alive():
root.after(0,lambda:labterm(thi))
else:
pass
else:
pass
else:
q = queue.get()
print q
root.after(0,lambda:labterm(thi))
def comter(event=None, exe=None, seq=None):
global enter
if seq == 1:
if exe != None:
th = Process(target=termexe, args=(exe,))
th.daemon = True
th.start()
labterm(th)
th.join()
else:
pass
else:
if exe != None:
th = Process(target=termexe, args=(exe,))
th.daemon = True
th.start()
labterm(th)
else:
th = Process(target=termexe, args=(enter.get(),))
th.daemon = True
th.start()
enter.set('')
labterm(th)
def resetterm():
global termwid
termwid.config(state=NORMAL)
termwid.delete(1.0, END)
termwid.config(state=DISABLED)
termen.bind('<Return>', comter)
resterm = Button(terminal, text="Clear", command=resetterm)
terbut = Button(terminal, text="Command", command=comter)
termen.grid(row=2, sticky='NSEW')
terbut.grid(row=3, sticky='NSEW')
resterm.grid(row=4, sticky='NSEW')
root.mainloop()
问题是收购仍然不是实时的。从软件中的条目运行程序:
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while(1)
{
cout << i << '\n';
i++;
int a = 0;
while(a < 10E6)
{
a++;
}
}
}
文本小部件内部暂时没有任何内容,一段时间后,输出突然出现。关于如何解决这个问题的任何想法?
这里的解决方案是使用线程,否则脚本会等到作业完成后再次使GUI响应。使用线程,您的程序将同时运行作业和GUI,代码示例:
import threading
def function():
pass
t = threading.Thread(target=function)
t.daemon = True # close pipe if GUI process exits
t.start()
我使用了这个std重定向器:
class StdRedirector():
"""Class that redirects the stdout and stderr to the GUI console"""
def __init__(self, text_widget):
self.text_space = text_widget
def write(self, string):
"""Updates the console widget with the stdout and stderr output"""
self.text_space.config(state=NORMAL)
self.text_space.insert("end", string)
self.text_space.see("end")
self.text_space.config(state=DISABLED)
我尝试使用@Pau B建议的线程(最后切换到多处理),我确实解决了卡住GUI的问题。现在的问题是运行该程序
for(int i = 0; i <100000; i ++){cout << i <<'\ n';}
不返回实时输出,但似乎它被缓冲,然后在文本小部件中出现一段时间后。我正在使用的代码如下所示:
class StdRed(object):
def __init__(self, textwid):
self.text_space = textwid
def write(self, text):
self.text_space.config(state=NORMAL)
self.text_space.insert(END,text)
self.text_space.see(END)
self.text_space.update_idletasks()
self.text_space.config(state=DISABLED)
def termexe(execute):
a = Popen(execute, shell=True, stdout=PIPE, stderr=STDOUT)
while True:
line = a.stdout.readline().rstrip()
if not line:
break
else:
queue.put(line)
queue.put('')
def labterm():
global th
if queue.empty():
if th != None:
if th.is_alive():
root.after(0,labterm)
else:
pass
else:
pass
else:
q = queue.get()
print q
root.after(1,labterm)
def comter(event=None):
global enter
global th
if th != None:
if not th.is_alive():
th = Process(target=termexe, args=(enter.get(),))
th.start()
else:
pass
else:
th = Process(target=termexe, args=(enter.get(),))
th.start()
enter.set('')
labterm()
其中comter()由一个按钮调用或绑定到文本条目内的'Return'。
也许这可以帮助别人,我解决了用endl替换'\ n'的问题。似乎在while循环中cout被缓冲并且stdout flush仅在一段时间后被调用,而对于endl函数在每个循环后被调用