Aborting the main thread raw_input () from the child thread

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?

+4
source share
1 answer

You can use something like select to check if there is an input to sys.stdin . This causes the loop to not wait on raw_input , but instead to poll, and you can have a loop condition to check whether to exit the loop or not.

+1
source

All Articles