需要将更新事件传递给同一个python脚本的多个正在运行的实例

2024-03-29 04:48:44 发布

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

我需要将更新事件传递给我的python脚本的所有运行实例,并且我希望代码尽可能简单。我没有在运行进程之间进行通信的经验。到目前为止,我一直在读/写配置文件,每个实例都将读取和/或更新这些文件。你知道吗

下面是我编写的一些伪代码(有点像一个简单的模板)来概括如何解决这个问题。请试着帮我填空。记住,我没有使用套接字、线程等的经验。。。你知道吗

import process # imaginary module

class AppA():
    def __init__(self):
        # Every instance that opens will need to attach
        # itself to the "Instance Manager". If no manager
        # exists, then we need to spawn it. Only one manager
        # will ever exist no matter how many instances are
        # running.
        try:
            hm = process.get_handle(AppA_InstanceManager)
        except NoSuchProgError:
            hm.spawn_instance(AppA_InstanceManager)
        finally:
            hm.register(self)
        self.instance_manager = hm

    def state_update(self):
        # This method won't exist in the real code, however,
        # it emulates internal state changes for the sake of
        # explaination.
        #
        # When any internal state changes happen, we will then
        # propagate the changes outward by calling the
        # appropriate method of "self.instance_manager".
        self.instance_manager.propagate_state()

    def cb_state_update(self):
        # Called from the "Instance Manager" only!
        #
        # This may be as simple as reading a known
        # config file. Or could simply pass data
        # to this method.


class AppA_InstanceManager():
    def __init__(self):
        self.instances = []

    def register_instance(self, instance):
        self.instances.append(instance)

    def unregister_instance(self, instance):
        # nieve example for now.
        self.instances.remove(instance)

    def propagate_state(self):
        for instance in self.instances:
            instance.cb_state_update(data)

if __name__ == '__main__':
    app = AppA()

有什么建议吗?你知道吗


Tags: thetoinstancesinstanceselfdefmanagerupdate
1条回答
网友
1楼 · 发布于 2024-03-29 04:48:44

这种设计有几种选择。你知道吗

您可以使用消息队列,它是为这类东西而设计的,例如AMQP或一些ZeroMQ之类的东西。你知道吗

或者您可以使用Redis或其他(内存中的)数据库来进行同步。你知道吗

如果你不想使用这样的东西,你可以使用多处理模块同步的东西。你知道吗

或者使用特定于平台的IPC系统,例如通过mmap、sysv套接字等共享内存

如果你想按照你解释的方式做事,你可以看看Twisteds透视代理。你知道吗

相关问题 更多 >