You can do that as easy as that
from threading import Thread
listener_thread = Thread(target=self.listen)
listener_thread.start()
When your program terminates and there are some non-daemon threads running, it will wait till they all finish.
You can flag you thread as daemon, but you need to be careful with them - see this article for more details. Basically, they might be still running and using the data that is in the consistent state because of the cleanup that is happening in other threads or already happened.
Creating a daemon thread:
from threading import Thread
listener_thread = Thread(target=self.listen)
listener_thread.daemon = True
# or listener_thread.setDaemon(True) for old versions of python
listener_thread.start()
The best option would be to leave your listener thread non-daemon (default) and think of a way to notify a listener thread somehow when your program is about to exit. Thus your listener thread can be finished gracefully.
updated
Don't use run
method of thread's object - it simply calls the function you have specified in the thread you are currently calling it from. Calling start
method of Thread
object fires your activity in a separate thread.