I made this program to have a timed input:
import time
from threading import Thread
def get_answer():
answer = input ("ANSWER THE QUESTION!!!")
def runtime():
time.sleep(1)
timer = timer-1
print (timer)
if timer == 0:
thread1.cancel()
print ("hi")
timer = 5
# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)
# start the threads
thread1.start()
thread2.start()
# wait for the threads to complete
thread1.join()
thread2.join()
When I run it though, I get this error:
Exception in thread Thread-2 (runtime):
Traceback (most recent call last):
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner
self.run()
File "C:\Users\user1\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run
self._target(*self._args, **self._kwargs)
File "c:\Users\user1\Desktop\import time.py", line 9, in runtime
timer = timer-1
UnboundLocalError: local variable 'timer' referenced before assignment
How can I fix this? I set the variable timer
before the thread runs, so why isn't it assigned already?
CodePudding user response:
I can not add a comment, I think you should use global var.
import time
from threading import Thread
global timer
timer = 5
# rest of your code
def runtime():
global timer
time.sleep(1)
timer = timer-1
print (timer)
if timer == 0:
thread1.cancel()
print ("hi")
#rest of your code
CodePudding user response:
Thanks @Marya
Made the variable global, and put the subtracting part in a while
loop.
import time
from threading import Thread
global timer
timer = 5
def get_answer():
answer = input ("ANSWER THE QUESTION!!!")
def runtime():
global timer
while True:
time.sleep(1)
timer = timer-1
print (timer)
if timer == 0:
thread1.kill()
thread1.join|()
print ("hi")
break
# create two new threads
thread1 = Thread(target=get_answer)
thread2 = Thread(target=runtime)
# start the threads
thread1.start()
thread2.start()
# wait for the threads to complete
thread1.join()
thread2.join()
CodePudding user response:
Here's how you can handle input with a timer:
import signal
TIMEOUT = 5
def get_answer(timeout):
def handler(*args):
raise Exception('Timeout')
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
return input ("ANSWER THE QUESTION!!! ")
except Exception:
pass
finally:
signal.alarm(0)
print(get_answer(TIMEOUT))
So, no threads here. If no input within TIMEOUT seconds the get_answer() function will return None. Otherwise it will return the user input.