运行后台任务,然后运行GUI

时间:2013-09-25 16:12:42

标签: python multithreading multiprocessing pyside

好的,所以现在我差不多完成了我的小项目,还剩下一些东西,正在运行我的后台任务,然后显示我的GUI。

class myGUIApp:
    def __init()__: 
        ....
    def createwidgets():
        ....

if __name__ == "__main__":
    import myBackgroundTasks
    x = myBackgroundTasks()
    x.startbackground1()  <----- this is background task that doesn't need user interaction
    x.startbackground2() <----- this is background task that doesn't need user interaction
    MainWindow = myGUIApp()
    MainWindow.show() <---- this is Pyside GUI

问题在于,在我的2个后台任务完成之前,GUI不会“显示”,这可能需要相当长的时间,因为他们正在从互联网上执行I / O作业和抓取文件。我该怎么办呢?使用python的多线程(在后台任务中,我也使用多线程)? QThread的?还是多处理模块?或其他人?谢谢你回答。

1 个答案:

答案 0 :(得分:1)

你可以把它放在thread上。由于Qt gui在自己的线程中运行,因此这是有效的用途。使用queue传回x的结果。唯一的技巧是你需要x的地点和时间?如果你需要在gui中使用它,那么最好的办法是使用gui的after方法,如果它有一个,或者它的等价物。关键是你不要占用所有资源,不断检查队列的输出。如果你在你的gui中放入一个while循环,它可能会导致gui冻结。

from threading import Thread
from Queue import Queue

class myGUIApp:
    def __init()__: 
        ....
    def createwidgets():
        ....

if __name__ == "__main__":
    import myBackgroundTasks
    QUEUE = Queue()
    def queue_fun(q):
        x = myBackgroundTasks()
        x.startbackground1()  <----- this is background task that doesn't need user interaction
        x.startbackground2() <----- this is background task that doesn't need user interaction
        q.put(x)
    THREAD = Thread(target=queue_fun, args=QUEUE)
    THREAD.start()
    MainWindow = myGUIApp()
    MainWindow.show() <---- this is Pyside GUI

    # if you can wait until after mainloop terminates to get x, put this here
    while THREAD.is_alive()
        try:
            x = QUEUE.get_nowait()
        except Queue.Empty:
            continue
    # if you need this inside Pyside, then you should put this inside Pyside,
    # but don't use while loop, use Qt after function and call self.wait

    def wait(self):
        try:
            x = QUEUE.get_nowait()
        except Queue.Empty:
            self.after(5, self.wait)