I have multi-threaded Python program. The main thread responses to user's command:
while 1:
try:
cmd = raw_input(">> ")
if cmd == "exit":
break
# other commands
except KeyboardInterrupt:
break
# other stuffs
Question: How do I break the while loop from other child threads?
sys.exit()
is not an option, because there are other code outside the while loop.
Possible solutions I think of:
- Interrupt the main thread
- Write an "exit" to
sys.stdin
Solution 1: I tried thread.interrupt_main()
, but it didn't work.
Solution 2: Calling sys.stdin.write()
won't work, neither the following code:
f = open(sys.stdin.name, "w")
f.write("exit")
f.close()
Another similar question provides an answer which suggests you to spawn another process and use subprocess.Popen.communicate()
to send commands to it. But isn't it possible to do a communicate()
on the current process itself?