【发布时间】:2018-05-23 08:34:59
【问题描述】:
我正在尝试与 multiprocessing.Process 和请求并行运行多个 API 请求。我将要解析的 urls 放入 JoinableQueue 实例并将内容放回 Queue 实例。我注意到将 response.content 放入队列会以某种方式阻止进程终止。
这是一个只有 1 个进程的简化示例(Python 3.5):
import multiprocessing as mp
import queue
import requests
import time
class ChildProcess(mp.Process):
def __init__(self, q, qout):
super().__init__()
self.qin = qin
self.qout = qout
self.daemon = True
def run(self):
while True:
try:
url = self.qin.get(block=False)
r = requests.get(url, verify=False)
self.qout.put(r.content)
self.qin.task_done()
except queue.Empty:
break
except requests.exceptions.RequestException as e:
print(self.name, e)
self.qin.task_done()
print("Infinite loop terminates")
if __name__ == '__main__':
qin = mp.JoinableQueue()
qout = mp.Queue()
for _ in range(5):
qin.put('http://en.wikipedia.org')
w = ChildProcess(qin, qout)
w.start()
qin.join()
time.sleep(1)
print(w.name, w.is_alive())
运行代码后我得到:
无限循环终止
ChildProcess-1 真
请帮助理解为什么运行函数退出后进程没有终止。
更新:添加打印语句以显示循环终止
【问题讨论】:
-
我遇到了完全相同的问题。我的 Process-inheriting 对象的“run”函数的最后一行执行了,但进程没有死。仍然没有找到答案(我的问题:stackoverflow.com/questions/57780333/…)
标签: python python-3.x python-requests python-multiprocessing