Maybe consider a threaded approach.
This solutions works on Windows.
For Win AND Linux give the keyboard module a try:
https://pypi.org/project/keyboard/
import os
import threading
import time
import msvcrt
import queue
import sys
WAIT = 5 # seconds
def keypress(out_q):
t = threading.currentThread()
while getattr(t, "do_run", True):
x = msvcrt.kbhit()
if x:
ret = ord(msvcrt.getch())
out_q.put(ret)
q = queue.Queue()
key = threading.Thread(name="wait for keypress", target=keypress, args=(q,))
key.start()
print("waiting", WAIT, "seconds before shutdown - to abort hit <SPACE>.")
start_time = time.time()
now = time.time()
data = ""
counter = 0
sys.stdout.write(str(WAIT) + "... ")
while now - start_time < WAIT and not data == 32: # 32 = space bar
now = time.time()
try:
data = q.get(False)
except queue.Empty:
pass
if now - start_time > counter + 1:
counter += 1
sys.stdout.write(str(WAIT - counter) + "... ")
sys.stdout.flush()
key.do_run = False
key.join()
if data == 32:
print("\n\nok. exiting...")
exit()
print("\n\nUser did NOT abort - code continues here...")
# Do whatever