I am writing a code where I need to request user input (requested input is used later), but I wanted to always catch the KeyboardInterrupt
exception so the script could show a message and request user input (in my case, the Enter key) to stop running the script, so I followed the code suggested by another StackOverflow post.
However, when I try to ask for user input to stop running the script, Python returns the error RuntimeError: can't re-enter readline
, so I need to use another approach (wait 5 seconds, then exit) to get a similar functionality, and I'm not sure about what I'm doing wrong (I have searched similar posts related to this error, but I haven't found any applicable to me).
An example code to verify this problem is the following (commented code is the alternative approach I have used).
requestKey = "Press Enter key to exit...\n"
exitTimeout = "\n\nstop received! exit in 5 seconds...\n"
import sys, signal, threading, time
# https://stackoverflow.com/questions/4205317/capture-keyboardinterrupt-in-python-without-try-except
def exitKey(signal, frame):
#print(exitTimeout)
#time.sleep(5)
input(requestKey)
sys.exit()
signal.signal(signal.SIGINT, exitKey)
watchExit = threading.Event()
while True:
userInput = input("\nenter something: ")
print("user input: " + userInput)
EDIT: an example of the error returned when running the code is the below.
enter something: ^CTraceback (most recent call last):
File "/Users/user/Documents/signalError.py", line 17, in <module>
userInput = input("\nenter something: ")
File "/Users/user/Documents/signalError.py", line 10, in exitKey
input(requestKey)
RuntimeError: can't re-enter readline