2017-06-20 39 views
3

我有一個Python中的程序,它將偵聽輸入信號。但是這可能會等待很長時間,所以我想每隔5秒顯示一條消息,上面寫着「仍在等待」Python超時計數器?

但是我不希望計數器功能中的延遲時間爲1秒當信號被定時時,停止程序聽信號,並且不正確的定時會產生不正確的結果。

我這麼遠到這一點,但整個腳本被延遲1秒,每次$ temp_2增加

#If option number 1 was selected, proceed 
if(int(input_string) == 1): 
    input_string = "" 
    temp_2 = 0 
    print('Currently listening for messages. System still working. Please wait.') 

     while True: 
      if(input_0 == False): 
       input_string = input_string + "0" 
       temp_1 = temp_1 + "0" 

      if(input_1 == False): 
       input_string = input_string + "1" 
       temp_1 = temp_1 + "1" 

      if(len(input_string) == 8): 
       output_string = output_string + chr(int(input_string, 2)) 
       input_string = "" 

       if(len(temp_1) == 40): 
        if(temp_1 == "0011110001100101011011100110010000111110"): 
         print('Received terminator!') 
        else: 
         temp_1 = temp_1[8::] 

       #increase the counter, but don't stop the script from 
       #listening for the input. can it be done? 
       temp_2 = timeout_counter(temp_2) 

       print(temp_2) 

       if(temp_2 == 5): 
        print('still working. not broken.') 
        temp_2 = 0 

以下是我timeout_counter()函數:

def timeout_counter(temp_2): 
    temp_2 = temp_2 + 1 
    time.sleep(1) 
    return (temp_2) 
+0

如果從用戶程序將阻止採取輸入。我認爲你需要一個線程來顯示消息。 – user3764893

回答

1

而不是使用time.sleep,您可以使用time.time(),在給定的迭代中使用timestamp,並使用前一個的timestamp。

你的算法應該看起來像:現在

#If option number 1 was selected, proceed 
if(int(input_string) == 1): 
    input_string = "" 
    temp_2 = time.time() 
    print('Currently listening for messages. System still working. Please wait.') 

     while True: 
      if(input_0 == False): 
       input_string = input_string + "0" 
       temp_1 = temp_1 + "0" 

      if(input_1 == False): 
       input_string = input_string + "1" 
       temp_1 = temp_1 + "1" 

      if(len(input_string) == 8): 
       output_string = output_string + chr(int(input_string, 2)) 
       input_string = "" 

       if(len(temp_1) == 40): 
        if(temp_1 == "0011110001100101011011100110010000111110"): 
         print('Received terminator!') 
        else: 
         temp_1 = temp_1[8::] 

       #increase the counter, but don't stop the script from 
       #listening for the input. can it be done? 
       temp_2 = timeout_counter(temp_2) 

       print(temp_2) 

       if(time.time() - temp_2 >= 5.): 
        print('still working. not broken.') 
        temp_2 = time.time() 

你timeout_counter()函數是無用:)

+0

「我想每5秒顯示一條消息」我想你誤解了這個問題;) –

+0

哦,我明白了。我誤讀了它 – user3764893

+0

如果他想等5分鐘,你會是對的;) –