当我尝试通过python3.4中的asyncio和concurrent.futures模块处理带有20个线程的100k url时,我收到此错误。它出现在2-5分钟的脚本工作之后。
concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
Task exception was never retrieved
future: <Task finished coro=<main() done, defined at async.py:173> exception=BrokenProcessPool('A process in the process pool was terminated abruptly while the future was running or pending.',)>
我试图优化我的代码,但仍然会收到此错误,之前已有过描述。
代码:
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
from grab import Grab
import random
import psycopg2
# Open connection to the database
connection = psycopg2.connect(database="<....>",
user="<....>",
password="<....>",
host="127.0.0.1",
port="5432")
# Create a new cursor for it
c = connection.cursor()
# Select settings from database
c.execute("SELECT * FROM <....> WHERE id=1;")
data = c.fetchall()
# Get time starting script
start_time = time.time()
def operation(link):
# init grab framework
g = Grab()
# try to find some elements on the page
try:
# open link
g.go(link)
# some link processing
<....>
except:
pass
@asyncio.coroutine
def main(item):
yield from loop.run_in_executor(p, operation, item)
# Create async loop, declare number of threads
loop = asyncio.get_event_loop()
p = ProcessPoolExecutor(data[0][13]) # =20
# Init tasks list - empty
tasks = []
# Select all urls which need to process
c.execute ("SELECT url FROM <....> ORDER BY id;")
# Forming tasks
for item in c.fetchall():
tasks.append(main(item[0]))
# Close main connection to the database
connection.close()
# Run async tasks
loop.run_until_complete(asyncio.wait(tasks))
# Close loop
loop.close()
# Get script finish time
print("--- %s seconds ---" % (time.time() - start_time))
答案 0 :(得分:0)
在loop.close()
之后添加{{1}}等待完成所有已执行的任务。