简体   繁体   中英

How do I abort reading a user's input in Python 3.x?

I have a thread that monitors user input which looks like this:

def keyboard_monitor(temp): #temp is sys.stdin
global flag_exit

while True:
    keyin = temp.readline().rstrip().lower()
    if keyin == "exit":
        flag_exit = True
        print("Stopping...")

    if flag_exit == True:
        break

If I type exit the flag is properly set and all the other threads terminate. If another one of my threads sets the flag, this thread refuses to finish because it's hanging on the user input. I have to input something to get it to finish. How do I change this code so that the program finishes when the flag is set externally?

Its hard to tell exactly what is going wrong without more of your code, but as an easy solution you could rather exit() which is a python built in. This should reliably terminate the application, also sys.exit()

From wim's comment:

You can use the atexit module to register clean up handlers

import atexit

def cleanup():
   pass
   # TODO cleanup

atexit.register(cleanup)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM