在Gui应用程序python中启动一个新线程

时间:2013-11-08 15:50:20

标签: python-3.x gtk python-multithreading

我有一个python Gui应用程序,它有一个执行一些更新的线程。 这是它的实施方式。

GObject.threads_init()
Class main:
    #Extra stuff here
    update_thread = Thread(target= update_func, args=(Blah blah,))
    update_thread.setDaemon(True)
    update_thread.start()
    Gtk.main()

这就是update_func喜欢的方式

def update_func():
    try:
        #do updating
        time.sleep(#6hrs)
    except:
        #catch error 
        time.sleep(#5 min)
    finally:
        update_func()

只要程序正在运行并且程序运行了几天,线程就会运行 问题是,有时线程会死并且不会发生更新,我必须重新启动应用程序。

如果当前的线程死了,有没有办法启动新线程,特别是在Gui应用程序中?

1 个答案:

答案 0 :(得分:1)

以下是从我的一个gtk应用程序剪切的线程示例。它可能会有所帮助。

#!/usr/bin/env python3

# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>

# Use of this source code is governed by GPLv3 license that can be found
# in http://www.gnu.org/licenses/gpl-3.0.html


from gi.repository import GObject
from gi.repository import Gtk
import threading

#UPDATE_INTERVAL = 6 * 60 * 60 * 1000   # 6 hours
UPDATE_INTERVAL = 2 * 1000   # 2 secs, for test only

def async_call(func, func_done, *args):
    '''
    Call func in another thread, without blocking gtk main loop.

    `func` does time-consuming job in background, like access website.
    If `func_done` is not None, it will be called after func() ends.
    func_done is called in gtk main thread, and this function is often used
    to update GUI widgets in app.
    `args` are parameters for func()
    '''
    def do_call(*args):
        result = None
        error = None

        try:
            result = func(*args)
        except Exception as e:
            error = e

        if func_done is not None:
            GObject.idle_add(lambda: func_done(result, error))

    thread = threading.Thread(target=do_call, args=args)
    thread.start()

class App(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.set_default_size(480, 320)
        self.set_border_width(5)
        self.set_title('Gtk Threads')
        self.connect('delete-event', self.on_app_exit)

        self.update_timer = GObject.timeout_add(UPDATE_INTERVAL,
                self.check_update)

    def run(self):
        self.show_all()
        Gtk.main()

    def on_app_exit(self, *args):
        Gtk.main_quit()

    def check_update(self):
        def _do_check_update():
            print('do check update: will check for updating info')
            print(threading.current_thread(), '\n')

        print('check update')
        print(threading.current_thread())
        async_call(_do_check_update, None)
        return True


if __name__ == '__main__':
    app = App()
    app.run()