4

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:

  1. Interrupt the main thread
  2. 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?

Community
  • 1
  • 1
eliang
  • 503
  • 3
  • 12

1 Answers1

1

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

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621