我正在尝试使用Python的multiprocessing.Process包(Raspbian 9上的Python 3.5-Stretch)在一个进程内从PubNub接收消息。
以下代码可以完美地作为独立程序运行,也可以在使用Python线程包的线程内完美运行。但是,它不适用于multiprocessing.Process。
我是否缺少某些东西,还是PubNub的SubscribeListener与Python的多处理程序包不兼容?
XDocument doc = XDocument.Load("dati.txt");
doc.Descendants().Elements("name") //all "name" elements
.Where(d => d.Value == selectednode) //where node value is user input
.Where(d => d.Parent.Name == "setting") //and also its parent element name is "setting"
.Select(d => d.Parent) //Select name's parent
.Remove(); //Remove it
//optionally save the xml back to the file or whatever you intend to do with it.
答案 0 :(得分:1)
我无法让SDK处理多处理工作程序中的同步请求。但是,以下技巧非常有效:
简单的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