Run a loop while waiting for a user input - python

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

Related

How to waite for the user input while executing the program using 'argparse' in python

I hope to run my program using multiple threads. One of them needs to waite for any input in order to excute corresping functions and stop the program. I want to use argparse to achieve that. However, it works really confusing:
import threading, argparse
stop = False
lock = threading.Lock()
def pt():
seq = 0
while not stop:
time.sleep(1)
seq += 1
print('pt stopping...')
def get_args():
global stop
parser = argparse.ArgumentParser()
parser.add_argument('kill', action='store_true')
start = time.time()
while not stop:
argv = input()
try:
args = parser.parse_args(argv)
except:
continue
if args.kill:
lock.acquire()
try:
stop = True
finally:
lock.release()
print('get_args stopping...')
if __name__ == '__main__':
g = threading.Thread(target=get_args, name='g')
t = threading.Thread(target=pt, name='t')
g.start()
t.start()
g.join()
t.join()
print('all stopped')
It can not recognize input properly. And whenever I push 'enter', it triggers stop signal.
The excuting result details are in the following image:
enter image description here

In python, how do I end the countdown when I have input

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")

How to ask Question by if statement via timeout

is there any way for ask question by if statement and after afew sec if user didnot give any answer , if state use a default answer?
inp = input("change music(1) or close the app(2)")
if inp = '1':
print("Music changed)
elif inp = '2':
print("good by")
in this case if user dont give any answer after 30 sec by default if statement choose number 3
from threading import Timer
out_of_time = False
def time_ran_out():
print ('You didn\'t answer in time') # Default answer
out_of_time = True
seconds = 5 # waiting time in seconds
t = Timer(seconds,time_ran_out)
t.start()
inp = input("change music(1) or close the app(2):\n")
if inp != None and not out_of_time:
if inp == '1':
print("Music changed")
elif inp == '2':
print("good by")
else:
print ("Wrong input")
t.cancel()
Timer Objects
This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a
subclass of Thread and as such also functions as an example of
creating custom threads.
Timers are started, as with threads, by calling their start() method.
The timer can be stopped (before its action has begun) by calling the
cancel() method. The interval the timer will wait before executing its
action may not be exactly the same as the interval specified by the
user.
For example:
def hello():
print("hello, world")
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed
class threading.Timer(interval, function, args=None, kwargs=None)
Create a timer that will run function with arguments args and keyword
arguments kwargs, after interval seconds have passed. If args is None
(the default) then an empty list will be used. If kwargs is None (the
default) then an empty dict will be used.
cancel()
Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting
stage.
Here's an alternative way to do it (python 3), using multiprocessing. Note, to get the stdin to work in the child process, you have to re open it first. I'm also converting the input from string to int to use with the multiprocessing value, so you might want to error check there as well.
import multiprocessing as mp
import time
import sys
import os
TIMEOUT = 10
DEFAULT = 3
def get_input(resp: mp.Value, fn):
sys.stdin = os.fdopen(fn)
v = input('change music(1) or close the app (2)')
try:
resp.value = int(v)
except ValueError:
pass # bad input, maybe print error message, try again in loop.
# could also use another mp.Value to signal main to restart the timer
if __name__ == '__main__':
now = time.time()
end = now + TIMEOUT
inp = 0
resp = mp.Value('i', 0)
fn = sys.stdin.fileno()
p = mp.Process(name='Get Input', target=get_input, args=(resp, fn))
p.start()
while True:
t = end - time.time()
print('Checking for timeout: Time = {:.2f}, Resp = {}'.format(t, resp.value))
if t <= 0:
print('Timeout occurred')
p.terminate()
inp = DEFAULT
break
elif resp.value > 0:
print('Response received:', resp.value)
inp = resp.value
break
else:
time.sleep(1)
print()
if inp == 1:
print('Music Changed')
elif inp == 2:
print('Good Bye')
else:
print('Other value:', inp)

What is best way to repeatedly execute a function in python and stop it based on some condition?

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

Pause and resume a running script in Python 3.42 in Windows

I'm new to Python and have been googling for a couple of days and read all I can find on this forum. Might be that I don't understand it all but I haven't found a solution to my problem yet. Ask for forgiveness already if there's an answer already to my problem, then I haven't understood it.
I want to make a Pause function for my program Tennismatch. The program will when it's being run print the score of a tennis match like this: "15-0, 15-15 etc ongoing till the match ends. It will print the score line by line.
I want the user to be able to pause after x number of balls, games, etc. So I don't know when the user wants to pause and after the user has paused I want the user to be able to resume the tennismatch where it was.
Have seen the time.sleep() but as I have understood it you must know when you want to pause to use this and it also ain't an indefinetie pause like I want. With input() it's the same.
Am going to make a GUI later on when the code is finished. Happy for anything that leads me to solving my problem.
I use Windows and Python 3.42 and run the program in Shell.
A piece of the code (haven't written it all yet, it's more of a general situation when something is being printed line after line for some time and want to be able do pause in the CIL:
#self.__points = [0,0]
def playGame(self):
if self.server == True: #self.server is either True or False when someone calls playGame()
server = self.player_1.get_win_serve() #self.player_1 = an object of a class Player():
else:
server = self.player_2.get_win_serve() #get_win_serve() method returns the probability to win his serv (1-0)
while (0 < self.__points[0] - self.__points[1] >= 2 or 0 < self.__points[1] - self.__points[0] >= 2) and (self.__points[1] >= 4 or self.__points[0] >= 4):
x = random.uniform(0,1)
if x > 0 and x < server:
self.__points[0] += 1
else:
self.__points[1] += 1
# print('The score, by calling a score() function that I haven't written yet')
For dealing with events in main loop you need to make a separated thread which capture input or any other event.
import sys
from sys import stdin
from time import sleep
from threading import Thread
from Queue import Queue, Empty
def do_something():
sleep(1)
print 42
def enqueue_output(queue):
while True:
# reading line from stdin and pushing to shared queue
input = stdin.readline()
print "got input ", input
queue.put(input)
queue = Queue()
t = Thread(target=enqueue_output, args=(queue,))
t.daemon = True
t.start()
pause = False
try:
while True:
try:
command = queue.get_nowait().strip()
print 'got from queue ', command
except Empty:
print "queue is empty"
command = None
if command:
if command == 'p':
pause = True
if command == 'u':
pause = False
if not pause:
print pause
do_something()
except KeyboardInterrupt:
sys.exit(0)
I came up with the following.
while True:
try:
## Keep doing something here
## your regular code
print '.',
except KeyboardInterrupt:
## write or call pause function which could be time.sleep()
print '\nPausing... (Hit ENTER to continue, type quit to exit.)'
try:
response = raw_input()
if response.lower() == 'quit':
break
print 'Quitting...'
except KeyboardInterrupt:
print 'Resuming...'
continue
The Event loop might as well be the code I wrote with.
I don't see any user input so I assume that x emulates it. To pause the game if x < 0.1 and to unpause(/resume) it if x > 0.9, you could:
while your_condition(self.__points):
x = random.random()
if x < 0.1: # pause
self.pause()
elif x > 0.9: # resume
self.resume()
if self.is_paused:
continue # do nothing else only wait for input (`x`)
# assume your_condition() has no side-effects
# here's what the resumed version does:
print("...")
# change self.__points, etc
where pause(), resume(), is_paused() methods could be implemented as:
def __init__(self):
self.is_paused = False
def pause(self):
self.is_paused = True
def resume(self):
self.is_paused = False
as you can see the implementation is very simple.

Categories