下記のコード例を参照してください。症状は、multiprocessing
Pool
の中のrequests.get(url)
が何らかの形でmatplotlib
figure()
によってブロックされているように見えます。このかなり予期しない動作を再現するために必要なマルチプロセッシングプールのRequests.getがMatplotlibの図でブロックされていますか?
成分は:
- がリストに関数を適用する
multiprocessing
Pool
を使用します。plt.figure()
の後の平文はrequest.get(url)
です。流暢に実行されます。 Pool
map
の機能には、requests.get
が含まれています。同一性関数などの他の「より単純な」関数(コードサンプルのf
など)を使用すると、うまく実行されます。- プールを開始する前に、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、および要求2.4.3で動作しました。 –
@ J.P.Petersen私はあなたのバージョンを 'conda env'で試しました。それでもまだ動作しません... – FJDU
1.これが新しいプロジェクトの場合は、Python 3.6がPython 2.7よりも推奨されます。 2.同時のHTTPリクエストを実行するために、 'マルチプロセッシング 'よりも' threading'が優先されます。 3. Pythonで[concurrent.futures.ThreadPoolExecutor'(python3に組み込まれているか、python 2に 'pip install futures'を使用してください)を使用します(http://pythonhosted.org/futures/#threadpoolexecutor-example)。 – Udi