请参阅下面的代码示例。症状是requests.get(url)
multiprocessing
中的Pool
似乎被matplotlib
figure()
以某种方式阻止。
重现这种意外行为所需的成分是:
multiprocessing
Pool
将功能应用于列表; request.get(url)
流畅地运行之后的简单plt.figure()
。Pool
map
的功能包含requests.get
;使用其他“更简单”的功能,例如身份功能(例如代码示例中的f
)可以流畅地运行。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
答案 0 :(得分:0)
如果您在Windows中运行此功能,则需要将def f()
下的所有代码移至:
if __name__ == "__main__":
块。