Asking a user for input only for a limited amount of time in python [duplicate]

孤街醉人 提交于 2019-12-08 04:05:19

问题


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

Any thoughts?

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


回答1:


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


来源:https://stackoverflow.com/questions/28423884/asking-a-user-for-input-only-for-a-limited-amount-of-time-in-python

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