【发布时间】:2017-02-17 16:20:56
【问题描述】:
请参阅下面的代码示例。症状是 multiprocessing Pool 中的 requests.get(url) 似乎被 matplotlib figure() 阻止了。
重现这种相当出乎意料的行为所需的成分是:
- 使用
multiprocessingPool将函数应用于列表;plt.figure()之后的普通request.get(url)运行流畅。 -
Poolmap的函数包含requests.get;使用其他“更简单”的功能,例如身份功能(例如代码示例中的f)可以流畅地运行。 - 在启动 Pool 之前,创建一个 matplotlib
figure;没有这个figure,代码运行流畅。
代码示例:
# matplotlib.__version__: 1.4.3
# requests.__version__: 2.9.1
# Python version:
# 2.7.12 |Anaconda 2.3.0 (x86_64)| (default, Jul 2 2016, 17:43:17)
# [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)]
# uname -a:
# Darwin myMBP 16.4.0 Darwin Kernel Version 16.4.0:
# Thu Dec 22 22:53:21 PST 2016;
# root:xnu-3789.41.3~3/RELEASE_X86_64 x86_64 i386 MacBookPro11,3 Darwin
from matplotlib import pyplot as plt
from multiprocessing import Pool
import requests
urls = ['http://stackoverflow.com']
# Runs as expected:
p = Pool(processes=1)
print 1, p.map(requests.get, urls)
# Runs as expected:
def f(x):
return x
fig = plt.figure()
p = Pool(processes=1)
print 2, p.map(f, urls)
# Will not run (the p.map takes forever to run):
fig = plt.figure()
p = Pool(processes=1)
print 3, p.map(requests.get, urls)
# REPLACING the previous block with the following
# will again runs as expected:
fig = plt.figure()
print 4, requests.get(urls[0])
代码示例的输出:
1 [<Response [200]>]
2 ['http://stackoverflow.com']
3
【问题讨论】:
-
这里适用于 Python 2.7.9、matplotlib 1.4.2 和 requests 2.4.3。
-
@J.P.Petersen 我用
conda env试过你的版本;还是不行…… -
1.如果这是一个新项目,建议使用 python 3.6 而不是 python 2.7; 2.运行并发HTTP请求,
threading优先于multiprocessing; 3.在python中使用concurrent.futures.ThreadPoolExecutor(python3内置,或python 2中pip install futures)为easier concurrency。
标签: python matplotlib multiprocessing python-requests python-multiprocessing