2013-08-07 25 views
2

我有一個項目,我正在用Python編寫將發送硬件(Phidg​​ets)命令。因爲我將連接多個硬件組件,所以我需要同時運行多個循環。在同一進程中的多個Python循環

我已經研究了Python multiprocessing模塊,但事實證明,硬件一次只能由一個進程控制,所以我所有的循環都需要在同一個進程中運行。

截至目前,我已經能夠用Tk()循環完成我的任務,但沒有實際使用任何GUI工具。例如:

from Tk import tk 

class hardwareCommand: 
    def __init__(self): 
     # Define Tk object 
     self.root = tk() 

     # open the hardware, set up self. variables, call the other functions 
     self.hardwareLoop() 
     self.UDPListenLoop() 
     self.eventListenLoop() 

     # start the Tk loop 
     self.root.mainloop() 


    def hardwareLoop(self): 
     # Timed processing with the hardware 
     setHardwareState(self.state) 
     self.root.after(100,self.hardwareLoop) 


    def UDPListenLoop(self): 
     # Listen for commands from UDP, call appropriate functions 
     self.state = updateState(self.state) 
     self.root.after(2000,self.UDPListenLoop) 


    def eventListenLoop(self,event): 
     if event == importantEvent: 
      self.state = updateState(self.event.state) 
     self.root.after(2000,self.eventListenLoop) 

hardwareCommand() 

所以基本上,用於定義Tk()循環的唯一原因是,這樣我可以那些需要同時循環函數中調用root.after()命令。

這有效,但有沒有更好/更pythonic的做法呢?我也想知道這種方法是否會導致不必要的計算開銷(我不是計算機科學家)。

謝謝!

+0

循環守護進程線程 – eri

+0

也許考慮看看[gevent](http://www.gevent.org/) – voithos

+1

你看過python線程(而不是多進程?)像鎖和線程這樣的東西允許你管理多個線程並協調他們訪問特定的硬件部分等。 – chander

回答

1

多處理模塊面向具有多個單獨的進程。雖然您可以使用Tk的事件循環,但如果您沒有基於Tk的GUI,那麼這是不必要的,因此如果您只想在同一進程中執行多個任務,則可以使用Thread模塊。有了它,您可以創建封裝獨立執行線程的特定類,因此可以在後臺同時執行多個「循環」。想想這樣的事情:

from threading import Thread 

class hardwareTasks(Thread): 

    def hardwareSpecificFunction(self): 
     """ 
     Example hardware specific task 
     """ 
     #do something useful 
     return 

    def run(self): 
     """ 
     Loop running hardware tasks 
     """ 
     while True: 
      #do something 
      hardwareSpecificTask() 


class eventListen(Thread): 

    def eventHandlingSpecificFunction(self): 
     """ 
     Example event handling specific task 
     """ 
     #do something useful 
     return 

    def run(self): 
     """ 
     Loop treating events 
     """ 
     while True: 
      #do something 
      eventHandlingSpecificFunction() 


if __name__ == '__main__': 

    # Instantiate specific classes 
    hw_tasks = hardwareTasks() 
    event_tasks = eventListen() 

    # This will start each specific loop in the background (the 'run' method) 
    hw_tasks.start() 
    event_tasks.start() 

    while True: 
     #do something (main loop) 

您應該檢查this article獲得更多熟悉threading模塊。其documentation也是一個很好的閱讀,所以你可以探索其全部潛力。

+0

優秀的描述,謝謝! – user1636547