Communicating with a running python daemon

前端 未结 8 1640
一个人的身影
一个人的身影 2020-12-07 07:45

I wrote a small Python application that runs as a daemon. It utilizes threading and queues.

I\'m looking for general approaches to altering this application so that

8条回答
  •  自闭症患者
    2020-12-07 08:42

    You can do this using multiprocessing managers (https://docs.python.org/3/library/multiprocessing.html#managers):

    Managers provide a way to create data which can be shared between different processes, including sharing over a network between processes running on different machines. A manager object controls a server process which manages shared objects. Other processes can access the shared objects by using proxies.

    Example server:

    from multiprocessing.managers import BaseManager
    
    class RemoteOperations:
        def add(self, a, b):
            print('adding in server process!')
            return a + b
    
        def multiply(self, a, b):
            print('multiplying in server process!')
            return a * b
    
    class RemoteManager(BaseManager):
        pass
    
    RemoteManager.register('RemoteOperations', RemoteOperations)
    
    manager = RemoteManager(address=('', 12345), authkey=b'secret')
    manager.get_server().serve_forever()
    

    Example client:

    from multiprocessing.managers import BaseManager
    
    class RemoteManager(BaseManager):
        pass
    
    RemoteManager.register('RemoteOperations')
    manager = RemoteManager(address=('localhost', 12345), authkey=b'secret')
    manager.connect()
    
    remoteops = manager.RemoteOperations()
    print(remoteops.add(2, 3))
    print(remoteops.multiply(2, 3))
    

提交回复
热议问题