同一进程中的多个python循环
我有一个用Python编写的项目,它将发送硬件(Phidgets)命令。因为我将与多个硬件组件进行接口,所以我需要同时运行多个循环 我研究了Python同一进程中的多个python循环,python,loops,multiprocessing,tk,Python,Loops,Multiprocessing,Tk,我有一个用Python编写的项目,它将发送硬件(Phidgets)命令。因为我将与多个硬件组件进行接口,所以我需要同时运行多个循环 我研究了Python多处理模块,但结果表明,硬件一次只能由一个进程控制,因此我的所有循环都需要在同一个进程中运行 到目前为止,我已经能够通过Tk()循环完成我的任务,但实际上没有使用任何GUI工具。例如: from Tk import tk class hardwareCommand: def __init__(self): # Defin
多处理模块,但结果表明,硬件一次只能由一个进程控制,因此我的所有循环都需要在同一个进程中运行
到目前为止,我已经能够通过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()
命令
这是可行的,但是有没有更好/更像蟒蛇的方法呢?我还想知道这种方法是否会导致不必要的计算开销(我不是计算机科学的人)
谢谢 多处理模块旨在拥有多个独立的进程。尽管您可以使用Tk
的事件循环,但如果您没有基于Tk的GUI,那么这是不必要的,因此,如果您只想在同一进程中执行多个任务,那么可以使用线程
模块。使用它,您可以创建封装单独执行线程的特定类,因此您可以在后台同时执行多个“循环”。想想这样的事情:
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)
您应该检查以更熟悉线程化
模块。它是一个很好的阅读,所以你可以探索它的全部潜力。< /p>循环在守护进程线程中,也许考虑看一下你是否已经看过Python线程(不是多进程)?像锁和线程之类的东西允许你管理多个线程并协调它们对特定硬件的访问等等。