同一进程中的多个python循环

2024-10-01 07:38:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用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的方式来做呢?我还想知道这种方法是否会导致不必要的计算开销(我不是一个计算机科学的人)。在

谢谢!在


Tags: thefrom命令selfevent硬件进程def
1条回答
网友
1楼 · 发布于 2024-10-01 07:38:24

多进程面向多进程处理。虽然您可以使用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也是一本很好的读物,所以你可以充分发掘它的潜力。在

相关问题 更多 >