Python 平行化刮刀,什么也不会发生
我试着将刮刀平行化。不幸的是,当我执行这段代码时,它的运行时间异常长。直到我停下来。也不会生成输出。这里有什么我错过的吗?我使用操作系统的问题是什么 首先定义函数,然后加载数据池,然后将其输入多进程 总而言之,我想这样做:Python 平行化刮刀,什么也不会发生,python,web-scraping,multiprocessing,python-multiprocessing,Python,Web Scraping,Multiprocessing,Python Multiprocessing,我试着将刮刀平行化。不幸的是,当我执行这段代码时,它的运行时间异常长。直到我停下来。也不会生成输出。这里有什么我错过的吗?我使用操作系统的问题是什么 首先定义函数,然后加载数据池,然后将其输入多进程 总而言之,我想这样做: def cube(x): return x**3 pool = mp.Pool(processes=2) results = pool.map(cube, range(1,7)) print(results) 但是这个小计算现在运行了超过5分钟,所以我认为代码本身没
def cube(x):
return x**3
pool = mp.Pool(processes=2)
results = pool.map(cube, range(1,7))
print(results)
但是这个小计算现在运行了超过5分钟,所以我认为代码本身没有错误。而是我对多重处理的理解
from multiprocessing import Pool
import os
import json
import datetime
from dateutil.relativedelta import relativedelta
import re
os.chdir(r'C:\Users\final_tweets_de')
p = Pool(5)
import time
def get_id(data_tweets):
for i in range(len(data_tweets)):
account = data_tweets[i]['user_screen_name']
created = datetime.datetime.strptime(data_tweets[i]['date'], '%Y-%m-%d').date()
until = created + relativedelta(days=10)
id = data_tweets[i]['id']
filename = re.search(r'(.*).json',file).group(1) + '_' + 'tweet_id_' +str(id)+ '_' + 'user_id_' + str(data_tweets[i]['user_id'])
os.system('snscrape twitter-search "(to:'+account+') since:'+created.strftime("%Y-%m-%d")+' until:'+until.strftime("%Y-%m-%d")+' filter:replies" >C:\\Users\\test_'+filename)
directory =r'C:\Users\final_tweets_de'
path= r'C:\Users\final_tweets_de'
for file in os.listdir(directory):
fh = open(os.path.join(path, file),'r')
print(file)
with open(file, 'r', encoding='utf-8') as json_file:
data_tweets = json.load(json_file)
data_tweets = data_tweets[0:5]
start = time.time()
print("start")
p.map(get_id, data_tweets)
p.terminate()
p.join()
end = time.time()
print(end - start)
更新
代码没有运行的原因首先是@Booboo解决的问题。另一个问题是,在使用windows时,脚本必须通过cmd启动,以防多处理
就像这里:
现在我输入了密钥错误0。如果我运行代码
import multiprocessing as mp
import os
import json
import datetime
from dateutil.relativedelta import relativedelta
import re
os.chdir(r'C:\Users\Paul\Documents\Uni\Masterarbeit\Datengewinnung\final_tweets_de')
import time
def get_id(data_tweets):
for i in range(len(data_tweets)):
print(i)
account = data_tweets[i]['user_screen_name']
created = datetime.datetime.strptime(data_tweets[i]['date'], '%Y-%m-%d').date()
until = created + relativedelta(days=10)
id = data_tweets[i]['id']
filename = re.search(r'(.*).json',file).group(1) + '_' + 'tweet_id_' +str(id)+ '_' + 'user_id_' + str(data_tweets[i]['user_id'])
try:
os.system('snscrape twitter-search "(to:'+account+') since:'+created.strftime("%Y-%m-%d")+' until:'+until.strftime("%Y-%m-%d")+' filter:replies" >C:\\Users\\Paul\\Documents\\Uni\\Masterarbeit\\Datengewinnung\\Tweets_antworten\\Antworten\\test_'+filename)
except:
continue
directory =r'C:\Users\Paul\Documents\Uni\Masterarbeit\Datengewinnung\final_tweets_de'
path= r'C:\Users\Paul\Documents\Uni\Masterarbeit\Datengewinnung\final_tweets_de'
for file in os.listdir(directory):
fh = open(os.path.join(path, file),'r')
print(file)
with open(file, 'r', encoding='utf-8') as json_file:
data_tweets = json.load(json_file)
data_tweets = data_tweets[0:2]
start = time.time()
print("start")
if __name__ == '__main__':
pool = mp.Pool(processes=2)
pool.map(get_id, data_tweets)
end = time.time()
print(end - start)
del(data_tweets)
输出:
(NLP 2) C:\Users\Paul\Documents\Uni\Masterarbeit\Datengewinnung\Tweets_antworten>python scrape_id_antworten_parallel.py
corona.json
start
corona.json
corona.json
start
0.0009980201721191406
coronavirus.json
start
0.0
coronavirus.json
start
0.0
covid.json
start
0.0
SARS_CoV.json
start
0.0
0
0
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py", line 121, in worker
result = (True, func(*args, **kwds))
File "C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py", line 44, in mapstar
return list(map(*args))
File "C:\Users\Paul\Documents\Uni\Masterarbeit\Datengewinnung\Tweets_antworten\scrape_id_antworten_parallel.py", line 25, in get_id
account = data_tweets[i]['user_screen_name']
KeyError: 0
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "scrape_id_antworten_parallel.py", line 60, in <module>
pool.map(get_id, data_tweets)
File "C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py", line 268, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py", line 657, in get
raise self._value
KeyError: 0
(NLP 2)C:\Users\Paul\Documents\Uni\Masterarbeit\datengewinung\Tweets\u antworten>python scrape\u id\u antworten\u parallel.py
corona.json
开始
corona.json
corona.json
开始
0.0009980201721191406
coronavirus.json
开始
0
coronavirus.json
开始
0
covid.json
开始
0
SARS_CoV.json
开始
0
0
0
multiprocessing.pool.RemoteTraceback:
"""
回溯(最近一次呼叫最后一次):
文件“C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py”,第121行,在worker中
结果=(True,func(*args,**kwds))
文件“C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py”,第44行,在mapstar中
返回列表(映射(*args))
文件“C:\Users\Paul\Documents\Uni\Masterarbeit\datengewinung\Tweets\u antworten\scrape\u id\u antworten\u parallel.py”,第25行,在get\u id中
帐户=数据\u推文[i]['user\u screen\u name']
关键错误:0
"""
上述异常是以下异常的直接原因:
回溯(最近一次呼叫最后一次):
文件“scrape_id_antworten_parallel.py”,第60行,in
map(获取id、数据和推文)
文件“C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py”,第268行,在映射中
返回self.\u map\u async(func、iterable、mapstar、chunksize).get()
get中第657行的文件“C:\Users\Paul\Anaconda3\envs\NLP 2\lib\multiprocessing\pool.py”
提升自我价值
关键错误:0
我可以从path=r'C:\Users\final\u tweets\u de'
中看到您的平台是Windows。在Windows下执行多处理时,创建子进程的代码必须完全在块中执行,如下所示:
import multiprocessing as mp
def cube(x):
return x**3
if __name__ == '__main__':
pool = mp.Pool(processes=2)
results = pool.map(cube, range(1,7))
print(results)
否则,您将进入一个递归循环,其中子进程将尝试无限地创建一个新的池和新的子进程。修复此问题并重新测试。最简单的方法是将代码包装到函数中(例如,将其称为main
),然后添加:
if __name__ == '__main_':
main()
另外,在您的实际示例中,为什么只使用2个流程或5个流程。通过不为
池
构造函数指定参数,您将创建一个等于计算机上实际可用处理器数量的池大小。这是一个不错的默认设置。谢谢,我认为这是解决方案的第一部分,另一部分是在cmd上运行脚本。我已更新了问题,因为我当前遇到一个关键错误0。