PubNub和Python的多处理过程不兼容?

2024-09-27 23:20:59 发布

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

我正在尝试使用Python的多处理过程包(Raspbian9上的Python3.5-Stretch)。你知道吗

以下内容可以作为独立程序或在使用Python的线程包的线程中完美地工作。但是,它不适用于多处理过程. 你知道吗

是我遗漏了什么,还是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()

Tags: fromimportmessagedefmpsubscribe线程multiprocessing
1条回答
网友
1楼 · 发布于 2024-09-27 23:20:59

PubNub和Python多处理

我无法让SDK在多处理工作进程中处理同步请求。不过,以下技巧非常有效:

同时使用多处理和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

相关问题 更多 >

    热门问题