简体   繁体   English

Python DBusGMainLoop在线程内部并尝试捕获块

[英]Python DBusGMainLoop inside thread and try and catch block

I'm currently trying to create a python script which has to use the GObject.MainLoop() to communicate with a Bluetooth client. 我目前正在尝试创建一个Python脚本,该脚本必须使用GObject.MainLoop()与蓝牙客户端进行通信。 I put the loop in a new thread in order to not block the remaining code. 我将循环放入新线程中,以便不阻塞其余代码。

Everything works fine until I've tried to quit the program with Control + C. If I hit this command the second try and catch block ("Host:...") does not seem to get executed. 在尝试使用Control + C退出程序之前,一切正常。如果我按此命令,第二个try and catch块(“ Host:...”)似乎没有执行。

Example script: 示例脚本:

import time
import threading

from dbus.mainloop.glib import DBusGMainLoop

try:
    from gi.repository import GObject
except ImportError:
    import gobject as GObject

DBusGMainLoop(set_as_default=True)

def myThread(a):
    try:
        GObject.threads_init()
        mainloop = GObject.MainLoop()
        mainloop.run()

    except KeyboardInterrupt:
        mainloop.quit()
        print("Thread: KeyboardInterrupt")
    return

try:
    myT = threading.Thread(target=myThread, args=(1,))
    myT.start()

    while 1:
        print("Host: Print every 1 sec")
        time.sleep(1)
except KeyboardInterrupt:
    print("Host: KeyboardInterrupt")

Output of the script: 脚本的输出:

Host: Print every 1 sec
Host: Print every 1 sec
^CHost: Print every 1 sec
Thread: KeyboardInterrupt
/usr/lib/python2.7/dist-packages/gi/types.py:113: Warning: Source ID 1 was not found when attempting to remove it
  return info.invoke(*args, **kwargs)
Host: Print every 1 sec
Host: Print every 1 sec
Host: Print every 1 sec
Host: Print every 1 sec

Process finished with exit code -1

Now I'm wondering why "print("Host: KeyboardInterrupt")" does not get executed. 现在,我想知道为什么“ print(“ Host:KeyboardInterrupt”)“没有得到执行。 Furthermore I'm not sure how to solve the stated warning. 此外,我不确定如何解决上述警告。

Hope you can help! 希望能对您有所帮助!

In fact I was able to solve the problem by myself. 实际上,我能够自己解决问题。

You just have to put the MainLoop() in the main thread and start the other action which currently executes "print("Host: Print every 1 sec")" in a new thread (myT). 您只需要在主线程中放入MainLoop()并启动当前在新线程(myT)中执行“ print(“主机:每1秒打印一次”)“的其他操作。 So you have to change threads from the code above. 因此,您必须从上面的代码更改线程。 Then if a KeyboardInterrupt happens, you have to manually exit the second thread (myT). 然后,如果发生KeyboardInterrupt,则必须手动退出第二个线程(myT)。

The reason why only "print("Thread: KeyboardInterrupt")" is called is, that if you use a MainLoop the process calling it will be seen as the "new main tread". 之所以只调用“ print(“ Thread:KeyboardInterrupt”)“,是因为,如果您使用MainLoop,则调用该过程的进程将被视为“新的主踏板”。

However, I'm still not sure how to get rid of the error: 但是,我仍然不确定如何消除该错误:

(process:2429): GLib-CRITICAL **: Source ID 1 was not found when attempting to remove it

According to the post " GLib-CRITICAL **: Source ID XXX was not found when attempting to remove it " the warning is not a problem, so I'll just ignore it. 根据帖子“ GLib-CRITICAL **:尝试删除它时未找到源ID XXX ”,该警告不是问题,因此我将忽略它。 Hope this helps anyone who'll stumble on this post! 希望这对任何会迷失这篇文章的人有所帮助!

Example: 例:

import time
import threading

from dbus.mainloop.glib import DBusGMainLoop

try:
    from gi.repository import GObject
except ImportError:
    import gobject as GObject

DBusGMainLoop(set_as_default=True)

def myThread(run_event):
    while run_event.is_set():
        print("Thread: Print every 1 sec")
        time.sleep(1)
    print("Thread: Exit")
    return

try:
    run_event = threading.Event()
    run_event.set()

    myT = threading.Thread(target=myThread, args=(run_event,))
    myT.start()

    GObject.threads_init()
    mainloop = GObject.MainLoop()
    mainloop.run()

except (KeyboardInterrupt, SystemExit):
    mainloop.quit()
    run_event.clear()
    myT.join()
    print("Host: KeyboardInterrupt")

Output: 输出:

Thread: Print every 1 sec
Thread: Print every 1 sec
^CThread: Exit
Host: KeyboardInterrupt

(process:2429): GLib-CRITICAL **: Source ID 1 was not found when attempting to remove it

See also: Closing all threads with a keyboard interrupt 另请参阅: 通过键盘中断关闭所有线程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM