2017-05-10 66 views
0

在發佈我的問題之前,我已經閱讀了許多文章,因爲它們都沒有答案,或者對於我在Python中的知識來說太複雜了。 我試圖發送帶有多一些POST請求,我注意到,當我的樹莓派並沒有成功連接到網絡,我有一些 ConnectionError: ('Connection Aborted.', gaierror(-2, 'Name or service not known')如何處理multiprocessing中的requests.exception.ConnectionError python

所以我在我的代碼做這個:

url = "https://some_url.org}" 
list.append(multiprocessing.Process(target=requests.post, args=(url,))) 

#doing this several times with several urls, then 

for element in list: 
    element.start() 
for element in list: 
    element.join() 

我知道我必須做from requests.exceptions import ConnectionError,我已經試過在for循環簡單try:except:但它不工作,因爲除了位於子進程。 這裏是回溯:

Process Process-6: 
    self.run() 
    File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run 
Traceback (most recent call last): 
    File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap 
    self._target(*self._args, **self._kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/api.py", line 94, in post 
    return request('post', url, data=data, json=json, **kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request 
    return session.request(method=method, url=url, **kwargs) 
    self.run() 
    File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request 
    File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run 
    self._target(*self._args, **self._kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/api.py", line 94, in post 
    return request('post', url, data=data, json=json, **kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/api.py", line 49, in request 
    return session.request(method=method, url=url, **kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 457, in request 
    resp = self.send(prep, **send_kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/sessions.py", line 569, in send 
    r = adapter.send(request, **kwargs) 
    File "/usr/lib/python2.7/dist-packages/requests/adapters.py", line 407, in send 

在此先感謝您的幫助!

回答

0

問題:如何處理requests.exception.ConnectionError在多處理

使用wrapperrequests.post(url)調用,例如:

import multiprocessing as mp 
import requests 

def req_wrapper(url): 
    try: 
     requests.post(url) 
    except Exception as e: 
     print('Exception catched in req_wrapper:{}'.format(e)) 

if __name__ == '__main__': 
    url = "https://some_url.org" 
    p = mp.Process(target=req_wrapper, args=(url,)) 
    p.start() 
    p.join() 

輸出
例外在req_wrapper釣到:('連接異常中止。',gaierror(-2, '名稱或服務不知道'))

測試與Python:3.4.2 2.7.9和

+0

是的,我已經嘗試過了,它不起作用,似乎我必須通過多處理方法創建的子進程與我的父進程進行通信 – GarennePb

+0

@GarennePb:更新了我的答案 – stovfl