我用 python 的 multiprocessing.Pool 模块进行多处理,但得到了 TypeError: list indices must be integers, not str 错误:
这是我的代码:
def getData(qid):
r = requests.get("http://api.xxx.com/api?qid=" + qid)
if r.status == 200:
DBC.save(json.loads(r.text))
def getAnotherData(qid):
r = requests.get("http://api.xxxx.com/anotherapi?qid=" + qid)
if r.status == 200:
DBC.save(json.loads(r.text))
def getAllData(qid):
print qid
getData(str(qid))
getAnotherData(str(qid))
if __name__ == "__main__":
pool = Pool(processes=200)
pool.map(getAllData, range(10000, 700000))
运行代码一段时间后(不是立即),会抛出异常
pool.map(getAllData, range(10000, 700000))
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
TypeError: list indices must be integers, not str
有什么问题吗?是不是Pool模块的bug?
请您参考如下方法:
当工作任务引发异常时,Pool 捕获它,将其发送回父进程,并重新引发异常,但这不会保留原始回溯(因此您只看到在哪里它在父进程中被重新提出,这不是很有帮助)。据推测,DBC.save 中的某些内容期望从 JSON 加载的值是一个 int,而它实际上是一个 str。
如果您想查看真正的回溯,请在顶层import traceback,并将辅助函数的顶层更改为:
def getAllData(qid):
try:
print qid
getData(str(qid))
getAnotherData(str(qid))
except:
traceback.print_exc()
raise
因此您可以在 worker 中看到真正的回溯,而不仅仅是在 parent 中看到绝育的、大部分无用的回溯。
