Python 特金特说:";“没有回应”;运行长子流程时
我的TkinterGUI(Python2.7)启动了一个可以运行一段时间的子进程,我使用管道将打印语句发送到文本小部件。它可以在没有任何打印语句的情况下运行很长时间,GUI窗口显示“无响应”,而我在该窗口中什么也做不了Python 特金特说:";“没有回应”;运行长子流程时,python,python-2.7,tkinter,subprocess,Python,Python 2.7,Tkinter,Subprocess,我的TkinterGUI(Python2.7)启动了一个可以运行一段时间的子进程,我使用管道将打印语句发送到文本小部件。它可以在没有任何打印语句的情况下运行很长时间,GUI窗口显示“无响应”,而我在该窗口中什么也做不了 #lauch main proc = subprocess.Popen(["python", testPath, filePath] + script_list, stdout=subprocess.PIPE,
#lauch main
proc = subprocess.Popen(["python", testPath, filePath] + script_list,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
#send the scripts output to the GUI text box
for line in iter(proc.stdout.readline,''):
text.insert(END, line)
#update in "real time"
text.see(END)
root.update()
text.update_idletasks()
尝试在子流程中添加
print
和flush
语句,但没有任何帮助。下面的示例是否为您提供了读取子流程输出的方法
import threading
from tkinter import *
import subprocess
import time
class SubprocessThread(threading.Thread):
def __init__(self, widget):
threading.Thread.__init__(self)
self.widget = widget
self.stopEvent = threading.Event()
print("Task Initialised")
def run(self):
print("Task Running")
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
proc = subprocess.Popen(["ping", "-n", "8", "8.8.8.8"],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0, startupinfo=startupinfo)
for line in iter(proc.stdout.readline,''):
if self.stopEvent.is_set():
break
self.widget.insert('end',line.decode())
time.sleep(0.1)
self.widget.insert('end',"\n\nComplete")
def startTask():
task.start()
def stopTask():
task.stopEvent.set()
gui = Tk()
text = Text(gui,width=80)
text.pack()
button1 = Button(gui, text='Start Process', fg='white', bg='gray', height=2, width=9, command=startTask)
button1.pack()
button2 = Button(gui, text='Stop Process', fg='white', bg='gray', height=2, width=9, command=stopTask)
button2.pack()
# start the GUI
task = SubprocessThread(text)
gui.mainloop()
这将创建一个单独的线程,该线程将“侦听”被调用进程中的新标准输出。在这个例子中,我只调用ping
请注意,使用子流程调用另一个python脚本通常是不好的做法。为什么不直接调用脚本中的函数。这是否回答了您的问题?读了这篇文章,但没有看到它对我有什么帮助。谢谢尝试使用
线程
需要进一步了解这一点。这是subprocess.Popen的替代方案吗?您不能在tkinter应用程序中执行阻止mainloop()
运行的操作,因此很可能proc.stdout.readline
正在阻止它。