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?
We can use input() function to achieve this. In this case, the program will wait indefinitely for the user input. Once the user provides the input data and presses the enter key, the program will start executing the next statements. sec = input('Let us wait for user input.
When the input() function is called, the program flow stops until the user enters the input via the command line. To actually enter the data, the user needs to press the ENTER key after inputting their string. While hitting the ENTER key usually inserts a newline character ( "\n" ), it does not in this case.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With