【发布时间】:2021-06-01 08:53:20
【问题描述】:
我已经定义了函数get_content 来从https://www.investopedia.com/ 抓取数据。我试过get_content('https://www.investopedia.com/terms/1/0x-protocol.asp'),它奏效了。但是,该过程似乎在我的 Windows 笔记本电脑上无限运行。我检查了它在 Google Colab 和 Linux 笔记本电脑上运行良好。
您能否详细说明为什么我的函数在这种并行设置中不起作用?
import requests
from bs4 import BeautifulSoup
from multiprocessing import dummy, freeze_support, Pool
import os
core = os.cpu_count() # Number of logical processors for parallel computing
headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
session = requests.Session()
links = ['https://www.investopedia.com/terms/1/0x-protocol.asp', 'https://www.investopedia.com/terms/1/1-10net30.asp']
############ Get content of a word
def get_content(l):
r = session.get(l, headers = headers)
soup = BeautifulSoup(r.content, 'html.parser')
entry_name = soup.select_one('#article-heading_3-0').contents[0]
print(entry_name)
############ Parallel computing
if __name__== "__main__":
freeze_support()
P_d = dummy.Pool(processes = core)
P = Pool(processes = core)
#content_list = P_d.map(get_content, links)
content_list = P.map(get_content, links)
Update1:我在 JupyterLab 中从 Anaconda 发行版中运行此代码。从下面的截图可以看出,状态一直是busy。
Update2:代码的执行可以在Spyder中完成,但它仍然没有返回任何输出。
Update3:代码在 Colab 中运行良好:
【问题讨论】:
-
在将所有共享数据移动到
if __name__ == "__main__":(我在 Windows 上运行)后对我来说效果很好。 -
顺便说一句,MP 在这方面可能有点矫枉过正。由于您只是触发请求并且大部分工作都是 IO 绑定的,因此多线程似乎更适合,因为线程可以只是照看请求。 MP 更适合 CPU 密集型工作。见this answer
-
@ggorlen 你能详细说明“移动所有共享数据......”是什么意思吗?
-
请参阅this answer--我认为如果您使用的是 linux/mac 并且它应该开箱即用,这不是问题。不过,我确实将
session对象传递给了每个工作函数,但我不确定这是否重要。 -
@ggorlen 我尝试将并行代码放入
if __name__ == "__main__":,但没有成功。 Here 是我的修改。是的,我在 Windows 10 上运行。您能否发布您的代码作为答案?
标签: python python-3.x parallel-processing multiprocessing jupyter-lab