我有一個項目,我正在用Python編寫將發送硬件(Phidgets)命令。因爲我將連接多個硬件組件,所以我需要同時運行多個循環。在同一進程中的多個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的做法呢?我也想知道這種方法是否會導致不必要的計算開銷(我不是計算機科學家)。
謝謝!
循環守護進程線程 – eri
也許考慮看看[gevent](http://www.gevent.org/) – voithos
你看過python線程(而不是多進程?)像鎖和線程這樣的東西允許你管理多個線程並協調他們訪問特定的硬件部分等。 – chander