2017-01-26 69 views
0

我有一個程序,它需要在後臺連續運行,但能夠接收到要更改的指令。我有這個線程運行,將數據發送到一個Arduino和接收數據傳回:從外部控制python線程

class receiveTemp (threading.Thread): 
    def __init__(self, out): 
     threading.Thread.__init__(self) 
     self.out = out 

    def run(self): 
     self.alive = True 
     try: 
      while self.alive: 
       rec = send("command") 
       self.out.write(rec) 
     except BaseException as Error: 
      print(Error) 
      pass 

現在我需要改變我與外部程序發送命令。
我嘗試過使用Pyro4,但我似乎無法獲得服務器上運行的線程,然後使用客戶端進行控制。

任何想法?

+0

您正在尋找流行語「Interprocess Communications」。研究它是如何在C中完成的,因爲這是python的大部分內容所基於的。在其他選項中,您可以使用套接字,管道,共享內存或可能(如果您想發送的內容有限的話)執行此操作,即信號處理程序。 –

+0

使用Pyro4獲得「在服務器上運行」的問題是什麼?一旦啓動Pyro4守護進程的請求回調,它就會運行一個服務器進程來處理工作線程中的請求。 –

回答

1

Scott Mermelstein的建議很好,我希望你會研究進程間通信。但作爲一個簡單的例子,讓你開始,我會建議修改你這樣的代碼:

import threading 
import queue 
import sys 
import time 

class receiveTemp (threading.Thread): 
    def __init__(self, out, stop, q): 
     threading.Thread.__init__(self) 
     self.out = out 
     self.q = q 
     self.stop = stop 

    def run(self): 
     while not self.stop.is_set(): 
      try: 
       cmd = self.q.get(timeout=1) 
      except queue.Empty: 
       continue 
      try: 
       rec = send(cmd) 
       self.out.write(rec) 
      except BaseException as Error: 
       print(Error) 
       pass 

stop = threading.Event() 
q = queue.Queue() 

rt = receiveTemp(sys.stdout, stop, q) 
rt.start() 

# Everything below here is an example of how this could be used. 
# Replace with your own code. 
time.sleep(1) 
# Send commands using put. 
q.put('command0') 
q.put('command1') 
q.put('command2') 
time.sleep(3) 
q.put('command3') 
time.sleep(2) 
q.put('command4') 
time.sleep(1) 
# Tell the thread to stop by asserting the event. 
stop.set() 
rt.join() 
print('Done') 

該代碼使用threading.Event作爲信號的線程應該停止。然後它使用queue.Queue作爲將命令從外部發送到線程的一種方式。您將需要使用q.put(command)從線程外部向隊列添加命令。

我沒有用Arduino測試,我創建了我自己的send版本,用於剛剛返回命令的測試。