你好我有一些命令,平均运行30分钟,当我点击GTK3创建的按钮时,python开始执行命令,但我的所有应用程序都冻结了。我点击按钮的python代码是:
def on_next2_clicked(self,button):
cmd = "My Command"
proc = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
while True:
line = proc.stdout.read(2)
if not line:
break
self.fper = float(line)/100.0
self.ui.progressbar1.set_fraction(self.fper)
print "Done"
我还必须在我的窗口中将命令输出设置为进度条。任何人都可以帮助解决我的问题吗?我也尝试过在python中使用Threading,但它也没用了......
答案 0 :(得分:3)
在循环中运行主循环迭代:
def on_next2_clicked(self,button):
cmd = "My Command"
proc = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
while True:
line = proc.stdout.read(2)
if not line:
break
self.fper = float(line)/100.0
self.ui.progressbar1.set_fraction(self.fper)
while Gtk.events_pending():
Gtk.main_iteration() # runs the GTK main loop as needed
print "Done"
答案 1 :(得分:1)
您正忙着等待,不要让UI主事件循环运行。将循环放在一个单独的线程中,这样主线程就可以继续自己的事件循环。
修改:添加示例代码
import threading
def on_next2_clicked(self,button):
def my_thread(obj):
cmd = "My Command"
proc = subprocess.Popen(cmd,shell=True, stdout=subprocess.PIPE)
while True:
line = proc.stdout.read(2)
if not line:
break
obj.fper = float(line)/100.0
obj.ui.progressbar1.set_fraction(obj.fper)
print "Done"
threading.Thread(target=my_thread, args=(self,)).start()
对您的函数的上述修改将启动一个与您的主线程并行运行的新线程。当新线程忙于等待时,它将让主事件循环继续。