Python fetchall 吃掉了我所有的交换内存

Pythons fetchall eats all my swap memory

我正在对 table 执行查询,在该查询中我得到一个包含几亿行的列,这是因为我想将它们绘制成直方图。问题是,在 cur.fetchall() 完成之前程序以退出代码 -9 退出之前,这几乎耗尽了我所有的内存(7.8 gb)和我所有的交换内存(8gb)。

如何防止这种情况发生?我应该先对我的列进行排序,然后对它的块进行多次查询 - 或者是否有更好的方法来获取我的查询中的数据? cur.execute 本身几乎不需要时间。

#!/usr/bin/python

import sqlite3 as lite
import numpy as np
import sys
import os
import matplotlib.pyplot as plt


def getQuantity(databasepath):
    con = lite.connect(databasepath)
    binwidth = 1
    start = time.time()
    with con:
        cur = con.cursor()
        cur.execute('SELECT latitude FROM MessageType1')
        con.commit()
        latitudes = cur.fetchall() #Breakdown here
        latitudes = [x[0] for x in latitudes]
        plt.hist(latitudes, bins=range(int(min(latitudes)), int(max(latitudes)) + binwidth, binwidth))
        plt.title("Bucket size: " + str(binwidth))
        plt.ylabel("Number of message")
        plt.savefig('latlongstats'+'t'+str(time.strftime("%H:%M:%S")), format='png')

if __name__ == "__main__":

    getQuantity('database/database.db')

我发现如果我替换以下内容:

    latitudes = cur.fetchall()
    print "fetched"
    latitudes = [x[0] for x in latitudes]

与:

    while True:
        tmp = cur.fetchone()
        if tmp != None:
            latitudes.append(tmp[0])
        else:
            break

我得到了相同的结果,尽管它需要很长时间,而且几乎耗尽了我的 ram(但不是我的交换)。