【问题标题】:Requests.get in multiprocessing pool blocked by a Matplotlib figure?多处理池中的 Requests.get 被 Matplotlib 图阻止?
【发布时间】:2017-02-17 16:20:56
【问题描述】:

请参阅下面的代码示例。症状是 multiprocessing Pool 中的 requests.get(url) 似乎被 matplotlib figure() 阻止了。

重现这种相当出乎意料的行为所需的成分是:

  1. 使用multiprocessingPool 将函数应用于列表; plt.figure() 之后的普通 request.get(url) 运行流畅。
  2. Poolmap 的函数包含requests.get;使用其他“更简单”的功能,例如身份功能(例如代码示例中的f)可以流畅地运行。
  3. 在启动 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


【解决方案1】:

如果您在 Windows 中运行此程序,则需要将 def f() 下面的所有代码移动到:

if __name__ == "__main__":

阻止。

【讨论】:

  • 我使用的是 macOS 10.12.3
  • 我在 macOS 10.12.3、python 3.5.1 上遇到了同样的问题。它在 Ubuntu 16.04 上运行良好
  • 您可能需要在 matplotlib 的错误跟踪器上打开一个错误
猜你喜欢
  • 2012-11-18
  • 1970-01-01
  • 2021-03-25
  • 2015-05-11
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 2014-01-15
相关资源
最近更新 更多