I'm currently trying to create a python script which has to use the GObject.MainLoop() to communicate with a Bluetooth client. 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.
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. Furthermore I'm not sure how to solve the stated warning.
Hope you can help!