具有多处理功能的python中IPC的经典解决方案

问题描述 投票:0回答:1

我在需要IPC的同一台计算机上有两个独立的进程。到目前为止,我有这个可行的解决方案:

server.py

#!/usr/bin/python3
from multiprocessing.managers import BaseManager
from multiprocessing import Process, Queue

def do_whatever():
    print('function do whatever, triggered by xyz')
    # do something

def start_queue_server(q):
    class QueueManager(BaseManager): pass

    QueueManager.register('get_queue', callable=lambda:q)
    m = QueueManager(address=('', 55555), authkey=b'tuktuktuk')
    s = m.get_server()
    s.serve_forever()

def main():
    queue = Queue()
    proc = Process(target=start_queue_server, args=(queue,))  
    proc.start()

    while True:
        command = queue.get()
        print('command from queue:', command)

        if command == 'xyz':
            do_whatever()

        # many more if, elif, else statements

if __name__ == "__main__":
    main()

client.py

#!/usr/bin/python3

from multiprocessing.managers import BaseManager

def communicator(command):
    class QueueManager(BaseManager): pass
    QueueManager.register('get_queue')

    m = QueueManager(address=('', 55555), authkey=b'tuktuktuk')
    m.connect()
    queue = m.get_queue()
    queue.put(command)

def main():
    command = ('xyz')
    communicator(command)

if __name__ == "__main__":
    main()
  • 与解析队列传递的命令然后调用目标函数相比,有没有一种更优雅的方法来调用“ do_whatever”?
  • 我可以以某种方式传递对“ do_whatever”的引用并直接从客户端调用它吗?
  • 如何从服务器得到答案,例如对还是错,传达给客户?我尝试传递共享变量而不是队列对象,但是失败。我是否需要使用第二个套接字打开另一个连接以通过答案?

我阅读了python文档,但找不到不相关进程的更多选项。欢迎输入!干杯

python sockets multiprocessing ipc
1个回答
0
投票

“使用REST API”是客户端与服务器之间通信的推荐方法,也是最受欢迎的方法。

REST提供用于数据交换的简单和标准的JSON格式。它还允许与身份验证和授权机制集成。它也是高度可扩展的。它还允许以不同语言编写的程序之间的轻松通信。

更多信息:https://realpython.com/api-integration-in-python/

© www.soinside.com 2019 - 2024. All rights reserved.