簡體   English   中英

用Python做一段時間的程序

[英]Do things for a period of time program in python

我用python編寫了一個程序,如下所示:

import time
y = "a"
x = 0
while x != 10 and y == "a":
    y = input("What is your name? ")
    time.sleep(1)
    x = x + 1
if y != "a":
    print("Hi " + y)
else:
    print("You took too long to answer...")

我知道有一個方法可以解決這個問題: Python中帶有超時的鍵盤輸入 ,但是我想知道為什么這不起作用。 無論我等待多長時間,它都不會超時。 它只是坐在那里等我輸入內容。我做錯了什么? 我在Win 7上使用python 3.3。

python中的輸入被阻止。 含義time.sleep(1)行以及之后的所有行僅在接收到輸入后才執行。

有兩種方法可以實現您想要的:

  • 使用線程
    input()語句封裝在線程中,加入超時,然后終止線程。 但是,不建議這樣做。 請參考以下問題: 有什么方法可以殺死Python中的線程?
  • 使用非阻塞input()
    建議這樣做。 使用信號。

我基於此博客以一種簡單的方式實現了您所需要的:

import signal

y = 'a'
x = 0

class AlarmException(Exception):
    pass

def alarm_handler(signum, frame):
    raise AlarmException

def my_input(prompt="What's your name? ", timeout=3):
    signal.signal(signal.SIGALRM, alarm_handler)
    signal.alarm(timeout)
    try:
        name = input(prompt)
        signal.alarm(0)
        return name
    except AlarmException:
        print('timeout......')
    signal.signal(signal.SIGALRM, signal.SIG_IGN)

    return

while x != 10 and y == 'a':
    y = my_input(timeout=3) or 'a'
    x += 1

if y != 'a':
    print('Hi %s' % (y,))
else:
    print('You took too long to answer.')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM