Good evening,
I want keyboard input with visible timer (time to respond)
My code
import time
import sys
def initial_startup(t):
print('Do you want to continue?')
global input
input = input("Answer yes or no only:" " ").lower()
while t:
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t -= 1
if input == "yes" or input == "yup":
print("\n\nThanks script is now starting\n\n")
else:
pass
if input == "no" or input == "nope":
print("\nOk as you wish, I'm stopping...\n")
sys.exit(1)
if timer == "00:01":
print("Timeout! try again")
sys.exit(1)
t = 4
initial_startup(int(t))
I'm trying to get keyboard input with timeout and also want to show time below answer yes or no:
Prints timer after input ..
Want this output.
Output:
Do you want to continue?
Answer yes or no:
You have {timer} time left...
If input then continue else sys.exit which is already in code.
Thank you so much for helping to improve this newbie!
CodePudding user response:
To do this you need to move with cursor in the terminal depending on the operating system you are using, it is very tiring and it is not very solid to use the terminal in that way (a static stdout would be easier and safer), what I would do it is an output of this kind obviously you have to use a multithread programming to be able to use the file descriptor simultaneously
import time
import sys
import threading
import time
import sys
def get_input(t):
global stop_threads
while True:
input_cmd = input().lower()
if input_cmd == "yes" or input_cmd == "yup":
print("\n\nThanks script is now starting\n\n")
break
elif input_cmd == "no" or input_cmd == "nope":
print("\nOk as you wish, I'm stopping...\n")
break
stop_threads = True
def initial_startup(t):
print('Do you want to continue?')
t1 = threading.Thread(target=get_input, args=(t,), daemon=True)
t1.start()
while t:
global stop_timeout
global stop_threads
mins, secs = divmod(t, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
prompt = "You have %s time left... Answer yes or no only: " % timer
print(prompt)
sys.stdout.write("\x1b[1A") # cursor up one line
sys.stdout.write("\x1b[2K") # delete the last line
if stop_threads:
sys.exit(1)
time.sleep(1)
t -= 1
if timer == "00:01":
sys.stdout.write("\x1b[2K") # delete the last line
print("Timeout! try again")
sys.exit(1)
stop_threads = False
stop_timeout = False
t = 4
initial_startup(int(t))
Output
Do you want to continue?
You have 00:02 time left... Answer yes or no only:
Ok as you wish, I'm stopping...
Do you want to continue?
You have 00:02 time left... Answer yes or no only:
Timeout! try again
Do you want to continue?
You have 00:05 time left... Answer yes or no only:
Thanks script is now starting