如何在不使用“输入"的情况下检测输入?在python中? [英] How to detect an input without using "input" in python?

查看:43
本文介绍了如何在不使用“输入"的情况下检测输入?在python中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用while循环来累加时间来制作速度相机程序.我希望用户能够输入"Enter"来停止while循环,而不会使while循环暂停并等待用户输入某些内容,因此while循环可以用作时钟.

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

推荐答案

至少有两种方法可以解决此问题.

There are at least two ways to approach this.

第一个是检查您的标准输入"流中是否有一些数据,而不会阻塞直到真正等待一些数据.注释中引用的答案告诉您如何解决此问题.但是,尽管就简单性而言(与替代方案相比)这很有吸引力,但没有办法在Windows和Linux之间透明地进行此操作.

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

如您所见,关于如何从线程到已接收到输入的主循环进行通信,存在一些难题.通知它的全局变量... yucko嗯?

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?

这篇关于如何在不使用“输入"的情况下检测输入?在python中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆