2013-12-14 42 views
1

一段時間的節目我做了一個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...") 

我知道有這個問題,完成同樣的事情的一種方式:Keyboard input with timeout in Python,但我想知道爲什麼這不起作用。無論等待多久,它都不會超時;它只是坐在那裏等着我輸入一些東西。我做錯了什麼?我在Win 7上使用python 3.3。

+2

這是因爲輸入塊,該程序的其餘部分不執行,直到它完成。 –

+0

程序在'y = input(「你叫什麼名字?」)塊''''''直到用戶按下輸入。你的程序沒有什麼可以中斷'輸入'並導致它提前終止。看看你連接的答案,找出可能的解決方案。 – Tim

+1

本傑明是對的。你到底想做什麼? – aIKid

回答

1

輸入在python中阻塞。含義time.sleep(1)行和接收輸入後才執行的所有行。

+0

我該如何解決它? @Ruslan Osipov – user2218101

+0

@ user2218101使用您提供的答案中描述的解決方案:http://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python。 –

+0

我知道那個代碼有效,但對我來說,這是一個練習,而不是一個功能。你知道我能解決嗎? – user2218101

1

這裏有兩種方法可以實現你想要什麼:

  • 使用線程
    封裝input()語句在一個線程中,加入了超時,然後殺死線程。但是,不建議。請參考這個問題:Is there any way to kill a Thread in Python?
  • 使用非阻塞input()
    這個建議。使用信號。

我你實現基於this blog一個簡單的方法需要的東西:

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.') 
相關問題