Based on idea from https://note.nkmk.me/en/python-while-usage/, and from elsewhere.
Program will stop if CTRL-C is pressed withing 5 seconds, otherwise will continue.
Works on Python 3, does not need any external (pip install ...) libraries.
Should work on Linux and Windows.
If you wish for program to check user input more often, comment print function before time.sleep(), and change time.sleep(1) to time.sleep(0.1). You would probably use top print function, too.
import time
def fn_wait_for_user_input(seconds_to_wait,message):
#print('waiting for',seconds_to_wait, 'seconds ...' )
print (message, seconds_to_wait)
start_time = time.time()
try:
while (time.time() - start_time ) < seconds_to_wait:
'''
parenthesis, from inside out:
time.time() which is current time - start time, if it is more than 10 seconds, time's up :)
int ; so we don't count 10 -1,02=8; instead we will count 10-1 = 9, meaning 9 seconds remaining, not 8
seconds to wait - everything else ; so we get reverse count from 10 to 1, not from 1 to 10
'''
print("%d" % ( seconds_to_wait - int( (time.time() - start_time ) ) ) )
time.sleep(1)
print('No keypress detected.')
return 1 #no interrupt after x seconds
except KeyboardInterrupt:
print('Keypress detected - exiting.')
return 0 #interrupted
if fn_wait_for_user_input(5, "program will continue if you don't press CTRL-C within seconds:" ) == 1:
print('continuing ....')
else:
print('not continuing.')
note:
use this to print all in one line:
print("%d" % ( seconds_to_wait - int( (time.time() - start_time ) ) ), end=' ', flush=True ) #needs flush inside loop...buffered
use this to continue inside a function:
if fn_wait_for_user_input(5, "program will continue if you don't press CTRL-C within seconds:" ) == 1:
#print('continuing ....')
pass
else:
#print('not continuing.')
#exit function
return