如何使用 posix 消息队列在节点和 python 之间进行 IPC?

How to IPC between node and python using posix message queue?

我正在尝试在节点 js 和 python3 应用程序之间编写 IPC 的“hello world”。目前,当新消息到达 Python 应用程序时,我遇到了解析错误。代码是:

Python:

from ipcqueue import posixmq
from time import sleep

q1 = posixmq.Queue('/fila1')

while True:

    while q1.qsize() > 0:
        print('p1: Recebi na minha fila: ' + str(q1.get()))

    sleep(0.5)

节点:

const PosixMQ = require('posix-mq')

var mq = new PosixMQ();
mq.open({
    name: '/fila1',
    create: true,
    mode: '0777',
    maxmsgs: 10,
    msgsize: 11
});
mq.push("hello world")
mq.close();

当第二个应用程序发送消息时,python 应用程序失败并显示:

File "../test-fila1.py", line 9, in

print('p1: Recebi na minha fila: ' + str(q1.get()))   File "/usr/lib/python3.7/site-packages/ipcqueue/posixmq.py", line 174, in

get

return self._serializer.loads(data)   File "/usr/lib/python3.7/site-packages/ipcqueue/serializers.py", line 14,

in loads

return pickle.loads(data) KeyError: 101

[2]- Exit 1 python3 ../test-fila1.py [3]+ Done node index.js

编辑
因此,我决定将问题从“KeyError: 101 when loading ipc message between node and python apps”更改为“How to IPC between node and python using posix message queue?”因为我刚刚注意到我发布的示例代码每次 运行 都会产生不同的错误。现在发生的错误是(但是,没有更改代码):

Traceback (most recent call last): File "snippets/test-fila1.py",
line 9, in
print('p1: Recebi na minha fila: ' + str(q1.get())) File "/usr/lib/python3.7/site-packages/ipcqueue/posixmq.py", line 174, in
get
return self._serializer.loads(data) File "/usr/lib/python3.7/site-packages/ipcqueue/serializers.py", line 14,
in loads
return pickle.loads(data)
_pickle.UnpicklingError: unpickling stack underflow

如果您查看 Queue

__init__
class Queue(object):
    """
    POSIX message queue.
    """

    def __init__(self, name, maxsize=10, maxmsgsize=1024, serializer=PickleSerializer):

如您所见,默认的 serializerPickleSerializer,这意味着当您从 nodejs 发送原始数据时,它假定进入队列的数据已被腌制。修复很简单,使用 RawSerializer

from ipcqueue import posixmq
from time import sleep
from ipcqueue.serializers import RawSerializer
q1 = posixmq.Queue('/fila1', serializer=RawSerializer)

while True:

    while q1.qsize() > 0:
        print('p1: Recebi na minha fila: ' + str(q1.get()))

    sleep(0.5)