我正在尝试使用Python的multiprocessing.Process包(Raspbian9-Stretch上的Python3.5on Raspbian9- 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()发布于 2018-08-08 09:50:32
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/15336927950007602https://stackoverflow.com/questions/51687355
复制相似问题