2017-05-26 61 views
0

的問題是,我找不到任何 答案與谷歌搜索方面相對只有簡單:如何在python上覆蓋樹莓派3的線程?

  1. 如何終止線程在python
  2. 如何同時使用線程等
  3. 鍵盤輸入迴路結束

所以程序的格式是這樣的:

import everything necessary 

def readingsomething(): 
     DOING SOME WORK in a infinite while loop and sleep for 1 sec 

def readingsomeotherthing(): 
    DOING SOME WORK in a infinite while loop and sleep for 2 sec 

thread1 = thread.thread(target = readingsomething) 

thread2 = thread.thread(target = readingsomeotherthing) 

try:  
    thread1.start() 
    thread2.start() 

    thread1.join() 
    thread2.join() 

except KeyboardInterrupt: 

    save a file and sys.exit() 

所以,當我運行方案E verything是除非我 按CTRL 順利 + Ç它不會終止每一個KeyboardInterrupt

,因爲我失去了收集到的數據,因爲我無法拯救他們。

任何建議和幫助將不勝感激。

+0

嗨,歡迎堆棧溢出。發佈時請務必使用[正確的格式](https://stackoverflow.com/editing-help#code),以便幫助您的人更容易閱讀代碼。 –

+1

善意地縮進你的代碼 - 當你執行它時。問題到底是什麼? –

+0

該代碼編譯沒有錯誤,並執行,但它應該終止只按下Ctrl + C但它不會停止並繼續執行我認爲這是一個問題,因爲睡眠命令在函數 –

回答

0

這是相當不清楚你想要做什麼。 你正在談論循環,但我沒有看到你的代碼。

另外,就像這樣寫,你將首先等待thread1停止,然後等待thread2停止,確保它是你想要的。

把超時內這些「加入」要求,否則它可以防止異常的聽力:

thread1.join() 

成爲

thread1.join(10) 

你可能要考慮一下導致你的代碼的變化。

+0

謝謝你的建議,我會嘗試它。 循環在定義的函數中。 –

0

您可以使用同步隊列Queue作爲管道將值發送給線程。

0

工作的Python 3例子:

from threading import Thread, Event 
import time 

def readingsomething(stop): 
    while not stop.isSet(): 
     print('readingsomething() running') 
     time.sleep(1) 

def readingsomeotherthing(stop): 
    while not stop.isSet(): 
     print('readingsomeotherthing() running') 
     time.sleep(2) 

if __name__ == '__main__': 
    stop = Event() 
    thread1 = Thread(target=readingsomething, args=(stop,)) 
    thread2 = Thread(target=readingsomeotherthing, args=(stop,)) 
    thread1.start() 
    thread2.start() 

    try: 
     thread1.join() 
     thread2.join() 
    except KeyboardInterrupt: 
     print('catched KeyboardInterrupt') 
     stop.set() 
     #save the file 

    print('EXIT __main__') 

與Python測試:3.4.2

+0

謝謝你的建議,我會試試這個。 –

+0

由於我使用python3, 鍵=輸入('按ctrl + c終止')變成 鍵= eval(輸入('按ctl + c終止'),但我一直得到無效的語法錯誤的C,我試圖找到原因 –

+0

@PradeepBV:更新我的答案與工作示例 – stovfl