我有一个用Python编写的项目,它将发送硬件(Phidgets)命令。因为我将与多个硬件组件连接,所以我需要同时运行多个循环。
我研究过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 :(得分: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也很好读,所以你可以发掘它的全部潜力。