2014-03-02 38 views
2

在Python中,我運行一種無限循環,其中進程休眠預定義時間 ,然後彈出詢問輸入。這裏就是我試圖用戶定義的中斷

while(1): 
    time.sleep(3600) //wait for one hour 


    pop_up_and_ask_for_input 

雖然我能夠做到上面的僞代碼,我想多了一個附加要求,只要作爲一個用戶,我想中斷並提供輸入自己。程序應該接受輸入,並從停止的地方繼續。請幫我做後期

+0

這對你有什麼用? –

+0

哇,你已經有足夠的代表投票了。既然你是新手,不要忘記接受(通過點擊複選標記)答案,最好的回答你的問題,你會得到+2代表只是爲了。 –

回答

1

首先導入模塊,Python中的最佳實踐:

import time 
import sys 

您需要在其中採集的投入,我會用列表的數據結構:

inputs = [] 

在Python 2,最好是比的raw_input輸入使用,

if sys.version_info[0] == 2: 
    input = raw_input 

而分解出reusab樂代碼,因此您不必將它寫兩次:

def user_input(): 
    user_in = input('\nplease give your input (Ctrl+C to break): ') # pop_up_and_ask_for_input 
    if user_in: 
     inputs.append(user_in) 

要捕獲鍵盤中斷(按Ctrl +Ç),你把循環中,除了塊一試,並執行輸入捕捉功能那裏也是。

while True: 
    try: 
     time.sleep(3600) # wait for one hour 
     user_input() 
    except KeyboardInterrupt: # stop and get input now 
     try: 
      user_input() 
     except KeyboardInterrupt: # graciously leave loop if another interrupt 
      break 

是如何工作的交互式會話:

^C 
please give your input (Ctrl+C to break): foo 
^C 
please give your input (Ctrl+C to break): bar 
^C 
please give your input (Ctrl+C to break): >>> 

>>> print(inputs) 
['foo', 'bar'] 
+0

非常感謝..它的工作 – user2095966

+0

很酷,它應該在Python 2或3中工作。如果您認爲它應該是規範的答案,請務必接受我的答案(單擊旁邊的複選標記)。 –

1

阿龍的回答有,如果用戶響應輸入提示點擊控制-C她被要求再次輸入的問題。該版本在這些條件下立即終止循環,並且如果尚未提示任何提示,則簡單地終止睡眠。

import time 
while True: 
    try: 
     time.sleep(3600) 
    except KeyboardInterrupt: 
     print # print newline to get back to col 1 
    try: 
     in_string = raw_input("Enter hourly input:") 
     # process the input 
    except KeyboardInterrupt: # graciously leave the loop if another interrupt 
     break 
+0

我想你會讓我的答案與另一個混淆。 –