2

ハードウェア (Phidg​​ets) コマンドを送信する Python で書いているプロジェクトがあります。複数のハードウェア コンポーネントとインターフェイスするため、複数のループを同時に実行する必要があります。

Pythonmultiprocessingモジュールを調査しましたが、ハードウェアは一度に 1 つのプロセスでしか制御できないことが判明したため、すべてのループを同じプロセスで実行する必要があります。

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な方法はありますか? また、この方法が不要な計算オーバーヘッドを引き起こすのではないかと考えています (私はコンピューター サイエンスの専門家ではありません)。

ありがとう!

4

1 に答える 1

1

multiprocessing モジュールは、複数の個別のプロセスを持つことを目的としています。のイベント ループを使用できます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)

この記事をチェックして、threadingモジュールに慣れる必要があります。そのドキュメントも読みやすいので、その可能性を最大限に探ることができます。

于 2013-08-07T20:13:10.460 に答える