【发布时间】:2019-06-22 21:56:23
【问题描述】:
所以目前我有一个 for 循环,这会导致 python 程序因程序说“已杀死”而死。它减慢了大约 6000 个项目,该程序在大约 6852 个列表项目中缓慢死亡。我该如何解决这个问题?
我认为这是由于列表太大。
我尝试将列表分成两部分,大约为 6000。可能是由于内存管理或其他原因。帮助将不胜感激。
for id in listofids:
connection = psycopg2.connect(user = "username", password = "password", host = "localhost", port = "5432", database = "darkwebscraper")
cursor = connection.cursor()
cursor.execute("select darkweb.site_id, darkweb.site_title, darkweb.sitetext from darkweb where darkweb.online='true' AND darkweb.site_id = %s", ([id]))
print(len(listoftexts))
try:
row = cursor.fetchone()
except:
print("failed to fetch one")
try:
listoftexts.append(row[2])
cursor.close()
connection.close()
except:
print("failed to print")
【问题讨论】:
-
您确定每次循环都需要关闭并重新打开连接吗?
-
khelwood,我这样做是为了检查它是不是光标对象变得超载,在此之前存在同样的问题。
-
尝试将数据库连接移出循环并在上下文管理器中使用它。
-
我很确定数据库连接不是问题
标签: python-3.x list for-loop psycopg2