PubNub 和 Python 的 multiprocessing.Process 不兼容?

PubNub and Python's multiprocessing.Process not compatible?

我正在尝试使用 Python 的 multiprocessing.Process 包(Python 3.5 on Raspbian 9 - Stretch)在进程内接收来自 PubNub 的消息。

以下作为独立程序或在使用 Python 的线程包的线程中完美运行。但是,它不适用于 multiprocessing.Process.

我是不是遗漏了什么或者 PubNub 的 SubscribeListener 与 Python 的多处理包不兼容?

#!/usr/bin/env python3

from pubnub.pubnub import PubNub, SubscribeListener
from pubnub.pnconfiguration import PNConfiguration

import multiprocessing
import time

def PN_func():
    pnconfig = PNConfiguration()
    pnconfig.subscribe_key = 'sub-mykey'
    pubnub = PubNub(pnconfig)

    print('Pubnub multiprocess subscriber initiated...')

    class Listener(SubscribeListener):
        def message(self, pubnub, data):
            print("From Multiprocess function message: ", data.message)

    pubnub.add_listener(Listener())
    pubnub.subscribe().channels('my_channel').execute()

if __name__ == '__main__':
    mp = multiprocessing.Process(target=PN_func)
    mp.start()
    mp.join()

PubNub 和 Python 多处理

我无法让 SDK 处理多处理工作线程内的同步请求。然而,以下技巧非常有效:

同时使用 Multiprocessing 和 PubNub

简单 example.py 文件包含以下代码:

import multiprocessing
import requests

SUB_KEY  = 'demo'
CHANNELS = ['my_channel']

def main():
    mp = multiprocessing.Process(target=subscriber)
    mp.start()
    mp.join()

def subscriber():
    timetoken = '0' ## pointer to last message received
    while True:
        url = "/".join([
            'https://ps.pubnub.com/subscribe'
        ,   SUB_KEY
        ,   ",".join(CHANNELS)
        ,   '0'
        ,   timetoken
        ])

        print(url)

        response  = requests.get(url)
        data      = response.json()
        messages  = data[0]
        timetoken = data[1]

        print(data)

if __name__ == '__main__': main()

多处理子进程的输出

> python example.py 
https://ps.pubnub.com/subscribe/demo/my_channel/0/0
[[], u'15336927707090912']
https://ps.pubnub.com/subscribe/demo/my_channel/0/15336927707090912
[[{u'text': u'hey'}], u'15336927943808959']
https://ps.pubnub.com/subscribe/demo/my_channel/0/15336927943808959
[[{u'text': u'hey'}], u'15336927945476647']
https://ps.pubnub.com/subscribe/demo/my_channel/0/15336927945476647
[[{u'text': u'hey'}], u'15336927946996529']
https://ps.pubnub.com/subscribe/demo/my_channel/0/15336927946996529
[[{u'text': u'hey'}], u'15336927948441519']
https://ps.pubnub.com/subscribe/demo/my_channel/0/15336927948441519
[[{u'text': u'hey'}], u'15336927950007602']
https://ps.pubnub.com/subscribe/demo/my_channel/0/15336927950007602