I have a multi-threaded Python program. The response of the main thread to the user command:
while 1: try: cmd = raw_input(">> ") if cmd == "exit": break # other commands except KeyboardInterrupt: break # other stuffs
Question : How can I break the while loop from other child threads?
sys.exit() not an option because there is other code outside the while loop.
Possible solutions that I think of:
- Main thread interruption
- Write "exit" on
sys.stdin
Solution 1: I tried thread.interrupt_main() , but that did not work.
Solution 2: Calling sys.stdin.write() will not work, nor the following code:
f = open(sys.stdin.name, "w") f.write("exit") f.close()
Another similar question gives an answer that suggests you to start another process and use subprocess.Popen.communicate() to send commands to it. But is it possible to make communicate() for the current process?
source share