Description: now, I have done input and countdown, both of which are carried out at the same time, but I want to achieve like this:
When I don't input anything during the countdown, it will execute another function after the countdown
When I input something before the end of the countdown, the countdown will pause, and then another function will be executed
My code is as follows:
import time
from threading import Thread
def waitinput():
wait_input_str = input("Please enter your account:\n")
print(wait_input_str)
thd = Thread(target=waitinput)
thd.daemon = True
thd.start()
for i in reversed(range(1, 11)):
print("\rcountdown:{}second".format(i), end="")
time.sleep(1)
# ###########################################
You can use isAlive() method to check if your thread has terminated.
In your case:
import time
from threading import Thread
def waitinput():
wait_input_str = input("Please enter your account:\n")
print(wait_input_str)
thd = Thread(target=waitinput)
thd.daemon = True
thd.start()
for i in reversed(range(1, 11)):
if not thd.isAlive():
# Execute 2
print("\nCountdown has stopped")
break
print("\rcountdown:{}second".format(i), end="")
time.sleep(1)
if thd.isAlive():
# Execute 1
print("\nCountdown has ended")
Related
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?
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()
while 1:
wat=water()
if wat==10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first=input("Drank?Y/N")
if first.lower()=="y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
Is there any way to wait for a couple of minutes and if no input is provided, then take the value "n" as input for the first variable?
Guess by default it will wait indefinitely. I tried using a timer function, but it cannot record any input.
What I am trying to do is to track my activities, so if I drink water I say y--> this records my activity and writes it to a file.
All help will be greatly appreciated
Here is how you can use a combination of pyautogui.typewrite, threading.Thread and time.sleep:
from pyautogui import typewrite
from threading import Thread
from time import sleep
a = ''
def t():
sleep(5)
if not a: # If by 5 seconds a still equals to '', as in, the user haven't overwritten the original yet
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
a = input()
b = input() # Test it on b, nothing will happen
Here is the code implemented into your code:
from pyautogui import typewrite
from threading import Thread
from time import sleep
while 1:
wat = water()
if wat == 10:
print("water condition")
mixer.music.load("water.mp3")
mixer.music.play()
first = 'waiting...'
def t():
sleep(5)
if first == 'waiting...':
typewrite('n')
typewrite(['enter'])
T = Thread(target=t)
T.start()
first = input("Drank?Y/N")
if first.lower() == "y":
with open("HealthLog.txt","a") as water1:
Content=f"Drank water at [{getdate()}] \n"
water1.write(Content)
else:
pass
I want to run a loop in my script while the user has not input anything. But when they have input something I want the loop to break.
The issue I am currently having is that when using the input() function, the script will stop and wait for an input, but I want to run another part of the script while waiting for the user input.
I have tried using try: with a raw_input():
while True:
try:
print('SCAN BARCODE')
userInput= raw_input()
#doing something with input
except:
#run this while there is no input
With this, I find that whatever is in the except: will always run, but it will not run try: even when there is a user input. If I change raw_input() to input() the script just waits at input() and doesn't run anything in the except:.
How do I achieve what I am after?
you can use python threads:
from threading import Thread
import time
thread_running = True
def my_forever_while():
global thread_running
start_time = time.time()
# run this while there is no input
while thread_running:
time.sleep(0.1)
if time.time() - start_time >= 5:
start_time = time.time()
print('Another 5 seconds has passed')
def take_input():
user_input = input('Type user input: ')
# doing something with the input
print('The user input is: ', user_input)
if __name__ == '__main__':
t1 = Thread(target=my_forever_while)
t2 = Thread(target=take_input)
t1.start()
t2.start()
t2.join() # interpreter will wait until your process get completed or terminated
thread_running = False
print('The end')
In my example you have 2 threads, the first thread is up and executes code until you have some input from the user, thread 2 is waiting for some input from the user. After you got the user input thread 1 and 2 will stop.
It simple bro u use flag boolean values
Flag = True
while Flag:
try:
Print('scan bar code')
User_inp = input()
if User_inp != '':
Flag = False
Except:
Print('except part')
I suggest you to look for select
it allow you to check if a file descriptor is ready for read/write/expect operation
Hey I am trying to have a loop be pausable from user input like having a input box in the terminal that if you type pause it will pause the loop and then if you type start it will start again.
while True:
#Do something
pause = input('Pause or play:')
if pause == 'Pause':
#Paused
Something like this but having the #Do something continually happening without waiting for the input to be sent.
Ok I get it now, here is a solution with Threads:
from threading import Thread
import time
paused = "play"
def loop():
global paused
while not (paused == "pause"):
print("do some")
time.sleep(3)
def interrupt():
global paused
paused = input('pause or play:')
if __name__ == "__main__":
thread2 = Thread(target = interrupt, args = [])
thread = Thread(target = loop, args = [])
thread.start()
thread2.start()
You can't directly, as input blocks everything until it returns.
The _thread module, though, can help you with that:
import _thread
def input_thread(checker):
while True:
text = input()
if text == 'Pause':
checker.append(True)
break
else:
print('Unknown input: "{}"'.format(text))
def do_stuff():
checker = []
_thread.start_new_thread(input_thread, (checker,))
counter = 0
while not checker:
counter += 1
return counter
print(do_stuff())
I want to execute a function repeatedly every 5 seconds and at the same time take input from the user and based on the input stop the execution?
Ex:
def printit():
t=threading.Timer(3.0,printit)
t.start()
n=str(input())
if(n=='rajesh'):
t.cancel()
else:
#I want to continue the execution here
This Should Help
import time
#use a While loop
While True:
#request said user input
x= input("Please Press 1 to continue Or 2 to Exit")
#then an if statement
if x==1:
#call your function
printit()
time.sleep(5)
else:break
This should Do the trick
If you really want to use threading, then this should work:
import threading
import time
def worker():
while True:
user_input = input("Enter text:")
if user_input == 'rajesh':
break
else:
time.sleep(5)
thread = threading.Thread(target=worker, daemon=True)
thread.start()
thread.join()
This Should Help
#request said user input
x= input("Please Press 1 to continue Or 2 to Exit")
#use a While loop
While True:
#then an if statement
if x==1:
#call your function
printit()
else:break
This should Do the trick