Skip to main content
 首页 » 编程设计

python之同一进程中的多个python循环

2025年05月04日10落叶无声

我有一个用 Python 编写的项目,它将发送硬件 (Phidg​​ets) 命令。因为我将与多个硬件组件交互,所以我需要同时运行多个循环。

我研究了 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 的方法呢?我也想知道这种方法是否会导致不必要的计算开销(我不是计算机科学专业的人)。

谢谢!

请您参考如下方法:

多处理模块适用于拥有多个独立的进程。尽管您可以使用 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) 

你应该检查this article以更熟悉 threading 模块。它的documentation也是一本好书,因此您可以探索它的全部潜力。