我有一个用Python编写的项目,它将发送硬件(Phidgets)命令。因为我将与多个硬件组件接口,所以需要有多个循环并发运行。在
我研究过Pythonmultiprocessing
模块,但结果发现硬件一次只能由一个进程控制,所以我的所有循环都需要在同一个进程中运行。在
到目前为止,我已经能够用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()
命令。在
这是可行的,但是有没有更好/更像Python的方式来做呢?我还想知道这种方法是否会导致不必要的计算开销(我不是一个计算机科学的人)。在
谢谢!在
多进程面向多进程处理。虽然您可以使用
Tk
的事件循环,但是如果您没有基于Tk的GUI,那么这是不必要的,因此如果您只想在同一个进程中执行多个任务,那么可以使用Thread
模块。有了它,你可以创建特定的类来封装一个单独的执行线程,这样你就可以让许多“循环”在后台同时执行。想想这样的事情:您应该检查this article以更熟悉
threading
模块。它的documentation也是一本很好的读物,所以你可以充分发掘它的潜力。在相关问题 更多 >
编程相关推荐