0

I want to run a function for just x seconds if in that x seconds user enters any key then program should be terminated, else it should continue further.

# Python Program - Shutdown Computer

import os
import time

check = int(input("enter the seconds"))

for i in range ( 10,0):
 print(i)
#  time.sleep(1)

 while i<check :
  c=input("enter any key to stop")
  if c
  exit();

os.system("shutdown /s /t 1")
halfer
  • 19,824
  • 17
  • 99
  • 186
sammy7
  • 1
  • you should probably use threads for that. Have a look on [`threading`](https://docs.python.org/3/library/threading.html) module – Tomerikoo Aug 15 '19 at 12:16
  • 2
    Possible duplicate of [Timeout on a function call](https://stackoverflow.com/questions/492519/timeout-on-a-function-call) – Olvin Roght Aug 15 '19 at 12:24

1 Answers1

0

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
Fab
  • 213
  • 3
  • 15