在未收到用户输入的情况下执行某些操作 [英] Do something while user input not received

查看:51
本文介绍了在未收到用户输入的情况下执行某些操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,当用户未提供输入时,我可以用什么方式循环执行某些操作.我有python客户端,我要求用户输入,但是当用户未提供输入时,我想保持每五秒钟进行一次更新.

In Python, in what way can I do something on loop while user has not given an input. I have python client and I ask for user input, but while user has not given an input I'd like to keep giving updates every five second.

我不能使用

 while (raw_input==""):
      update()

因为如果输入为",则表示用户已经输入了某些内容(按回车键);

since if input is "", it means user already entered something (hit enter);

有办法吗?

更新:

我仍然无法为我工作.我尝试了以下方法,也尝试了与此线程类似的方法:等待用户输入在单独的线程中.而且,我还尝试改为将update()方法传递给应该在后台运行的线程.但是任何使用raw_input()的东西都会使其停留在等待输入的状态:

I still can't get anything to work for me. I tried the method below, also tried something similar to this thread: waiting for user input in separate thread. And I also tried instead passing an update() method to the thread that's supposed to be working in the background. But anything with raw_input() makes it stuck on waiting for input:

 import threading
 import time

def update():
   while True:
      time.sleep(5)
      print "update"+'\n'

mythread = threading.Thread(target=update, args=())
mythread.daemon = True
mythread.start()

while True:
   usrin=raw_input()
   print "you typed: "+usrin

每次用户输入内容时,都会完成更新,然后将usrin退还给用户.如果这是我想要的,我可以轻松地将update()放入最后一个while循环.

Every time user inputs something, update is done and then usrin is given back. If this was what I wanted I could just easily put the update() into the last while loop.

如果我只是使用update方法启动此线程,而在程序中什么也不做(取消最后一个while循环),那么在shell中,它每五秒钟更新一次,我仍然可以使用shell(即键入3 + 5)它给了我8).我希望在程序中发生这样的事情,即当用户处于非活动状态时更新,并且如果他输入了响应并返回到更新.

If I were to just start this thread with update method and do nothing else in the program (scrap the last while loop), then in shell while it updates every five seconds I can still use the shell (i.e type 3+5 and it gives me 8). I want something like that to happen within the program, when user is inactive update, and if he types react and go back to updating.

注意:另外,我目前正在使用python 2.7.8,切换版本会有所帮助吗?

NOTE: Also, I'm currently using python 2.7.8, would switching versions help?

推荐答案

也许这可以帮助您入门:

Maybe this can get you started:

from threading import Thread
from time import sleep

result = None

def update_every_second():
    while result is None:
        sleep(1)
        print "update"

t = Thread(target=update_every_second)
t.start()
result = raw_input('? ')

print "The user typed", result

这篇关于在未收到用户输入的情况下执行某些操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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