-1

I'm trying to terminate python program if an input isn't provided by user within specific time frame, say - 5 seconds.

The code has been taken and edited from mediocrity's answer

import sys
import time
from threading import Thread

x = None

def check():
    global x
    time.sleep(5)
    if x:
        print("Input has been given!")
        return
    sys.exit()

Thread(target=check).start()
x = input("Input something: ")

But it keeps waiting for the input and doesn't terminate, unless the input is given. How could I change the code so that it executes as inteded?

double-beep
  • 5,031
  • 17
  • 33
  • 41

1 Answers1

0

you should try this code its working on vscode

import sys
import time
from threading import Thread

x = None

def check():
  global x
  time.sleep(5)
  if x:
    print("Input has been given!")
    return
  else:
    print("input has not been given for last 5 sec") 
    sys.exit()
if __name__=='__main__':
  t1=Thread(target=check)
  t1.start()

  x = input("Input something: ")
  t1.join()
Garampapa
  • 11
  • 2