python什么时候用input_在python中仅在有限的时间内要求用户输入

1586010002-jmsa.png

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值