How to detect an input without using “input” in python?

做~自己de王妃 提交于 2021-01-28 22:57:24

问题


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


回答1:


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?




回答2:


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



来源:https://stackoverflow.com/questions/26798767/how-to-detect-an-input-without-using-input-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!