我目前正在尝试创建一个python脚本,它必须使用GObject.MainLoop()与蓝牙客户端进行通信。 我把循环放在一个新的线程中,以便不会阻塞剩余的代码。Python DBusGMainLoop内线程和尝试和catch块
一切工作正常,直到我试图用Control + C退出程序。 如果我点击这个命令,第二个try和catch块(“Host:...”)似乎不会被执行。
示例脚本:脚本的
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")
输出:
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
现在我想知道为什么 “打印(” 主持人:一个KeyboardInterrupt “)” 没有得到执行。此外,我不确定如何解决所述的警告。
希望你能帮助!