Max Dickson
Max Dickson

Reputation: 31

How to detect an input without using "input" in python?

I am trying to do a speed camera program by using a while loop to add up time. I want the user to be able to input "Enter" to stop the while loop with out the while loop pausing and waiting for the user input something, so the while loop works as a clock.

    import time
    timeTaken=float(0)
    while True:
        i = input   #this is where the user either choses to input "Enter"
                    #or to let the loop continue
        if not i:
        break
        time.sleep(0.01)
        timeTaken=timeTaken+0.01
    print(timeTaken)

I need a line of code which can detect whether the user has inputted something without using "input".

Upvotes: 2

Views: 9458

Answers (2)

GreenAsJade
GreenAsJade

Reputation: 14685

There are at least two ways to approach this.

The first is to check whether your "standard input" stream has some data, without blocking to actually wait till there is some. The answers referenced in comments tell you how to approach this. However, while this is attractive in terms of simplicity (compared to the alternatives), there is no way to transparently do this portably between Windows and Linux.

The second way is to use a thread to block and wait for the user input:

import threading 
import time

no_input = True

def add_up_time():
    print "adding up time..."
    timeTaken=float(0)
    while no_input:
        time.sleep(0.01)
        timeTaken=timeTaken+0.01
    print(timeTaken)


# designed to be called as a thread
def signal_user_input():
    global no_input
    i = raw_input("hit enter to stop things")   # I have python 2.7, not 3.x
    no_input = False
    # thread exits here


# we're just going to wait for user input while adding up time once...
threading.Thread(target = signal_user_input).start()

add_up_time()

print("done.... we could set no_input back to True and loop back to the previous comment...")

As you can see, there's a bit of a dilemma about how to communicate from the thread to the main loop that the input has been received. Global variable to signal it... yucko eh?

Upvotes: 3

qstebom
qstebom

Reputation: 739

You should use a thread, if you are supposed to listen to input and have at the same time something else being processed.

Upvotes: -1

Related Questions