Reputation: 117
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?
Upvotes: 7
Views: 15850
Reputation: 73
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')
Upvotes: 2
Reputation: 17322
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.
Upvotes: 11
Reputation: 530
I suggest you to look for select
it allow you to check if a file descriptor is ready
for read/write/expect operation
Upvotes: 0