0

我有一个 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 应用程序中?

4

1 回答 1

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()
于 2013-11-09T11:20:15.040 回答