Multiprocessing in python - UnboundLocalError: local variable 'data' referenced before assignment

Multiprocessing in python - UnboundLocalError: local variable 'data' referenced before assignment

我正在尝试访问 API 以 return 一组产品。由于执行速度很慢,我希望可以使用多处理来使其更快。 API 在使用简单的 for 循环访问时完美运行。

这是我的代码:

from multiprocessing import Pool
from urllib2 import Request, urlopen, URLError
import json

def f(a):
    request = Request('API'+ str(a)) 
    try:
        response = urlopen(request)
        data = response.read()
    except URLError, e:
        print 'URL ERROR:', e
    s=json.loads(data)
    #count += len(s['Results'])
    #print count
    products=[]
    for i in range(len(s['Results'])):
        if (s['Results'][i]['IsSyndicated']==False):        
            try:
                products.append(int(s['Results'][i]['ProductId']))
            except ValueError as e:
                products.append(s['Results'][i]['ProductId'])
    return products

list=[0,100,200]

if __name__ == '__main__':
    p = Pool(4)
    result=p.map(f, list)
    print result

错误信息如下:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\z080302\Desktop\WinPython-32bit-2.7.6.3\python-2.7.6\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 540, in runfile
    execfile(filename, namespace)
  File "C:/Users/z080302/Desktop/Python_Projects/mp_test.py", line 36, in <module>
    result=p.map(f, list)
  File "C:\Users\z080302\Desktop\WinPython-32bit-2.7.6.3\python-2.7.6\lib\multiprocessing\pool.py", line 250, in map
    return self.map_async(func, iterable, chunksize).get()
  File "C:\Users\z080302\Desktop\WinPython-32bit-2.7.6.3\python-2.7.6\lib\multiprocessing\pool.py", line 554, in get
    raise self._value
UnboundLocalError: local variable 'data' referenced before assignment

我在想即使使用多处理函数仍然会按顺序执行。那为什么我得到 UnboundLocalError?

在此代码中:

try:
    response = urlopen(request)
    data = response.read()
except URLError, e:
    print 'URL ERROR:', e

如果 urlopen 抛出 URLError 异常,以下行 (data = response.read() 永远不会执行。所以当你来到:

s=json.loads(data)

变量data 从未被赋值。您可能希望在出现 URLError 时中止处理,因为这表明您将没有任何 JSON 数据。

接受的答案是关于实际问题的,但我想我会为其他因 multiprocessings ApplyResult.get 和 [=12= 提出的神秘错误而来到这里的人添加我的经验].如果您收到 TypeErrorValueError 或基本上与您的情况无关的任何其他错误 multiprocessing 那么这是因为该错误不是由多处理引起的,而是由您的代码引起的您正在尝试管理的进程中 运行(或者线程,如果您碰巧使用的是我曾经使用的 multiprocessing.pool.ThreadPool)。