在有限的时间内用Python要求用户输入 [英] Asking a user for input only for a limited amount of time in python

查看:548
本文介绍了在有限的时间内用Python要求用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的程序需要暂停并要求用户输入,如果没有输入,请继续执行该程序.我认为它看起来像这样:

The program I am working on needs to pause and ask the user for input and if there is none, move on with the program. I think it would look something like this:

import time 

...[code to run before break]...

if input in time.sleep(5):
    [break out of normal code]
else:
    [return to normal code] 

 [code to run after break]...

有什么想法吗?

当我询问但我正在运行Windows(8.1)时,没有想到这一点.

Didn't think about this when I asked but I am running Windows (8.1).

推荐答案

是一种简单快捷的hack,但有效.以下内容将等待用户输入5秒钟或直到收到输入为止,以先到者为准.

Bit of a quick-and-dirty hack, but effective. The following waits for user input for 5 seconds or until input is received, whichever happens first.

from datetime import datetime, timedelta
import os
import signal
import threading
import time

waiting = False

def wait_and_kill(timeout):
    elapsed = timedelta(0)
    while elapsed.total_seconds() < timeout and waiting:
        start = datetime.now()
        time.sleep(0.1)
        elapsed += datetime.now() - start
    if waiting:
        os.kill(os.getpid(), signal.SIGINT)

try:
    t = threading.Thread(target=wait_and_kill, args=(5,))
    waiting = True
    t.start()
    raw = raw_input('> ')
    waiting = False
except KeyboardInterrupt:
    pass

这篇关于在有限的时间内用Python要求用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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