python:将元组转换为生成器和释放内存

时间:2017-12-07 16:30:54

标签: python tuples generator

我有一个python脚本从数据库中获取大量数据(数百万),但它占用大量内存并使整个服务器速度变慢

#open connection with database
#execute query in database
data = tuple(cursor.fetchall())
def dataGenerator(self, data):
    for i in data:
        yield i
del data

我试图从元组创建一个生成器并删除数据以释放内存但它不会工作 我也尝试使用光标,但我需要关闭与数据库的连接 有办法吗?

1 个答案:

答案 0 :(得分:-1)

根据您的要求,我认为此解决方案最适合您。首先从DB获取数据:

import psycopg2
con = connect(user='root', host = 'localhost', database='pricing_db_new')
cur = con.cursor()
cur.execute('SELECT * from accounts')

现在我有了光标,我们可以将它写入临时文件:

import json
from tempfile import NamedTemporaryFile
tmp = NamedTemporaryFile()
_ = [tmp.write(json.dumps(c) + '\n') for c in cur.fetchall()]

此临时文件只要打开就会存在,并在关闭它时会被删除。

In [38]: tmp.name
Out[38]: '/tmp/tmpEQsoKt'

现在,您可以逐行读取文件并生成结果。

In [77]: tmp.seek(0) # seek to beginning to read again

In [78]: def read_file(file_obj):
    ...:     for row in file_obj.readlines(): # read line by line
    ...:         yield json.loads(row.strip())
    ...:

In [79]: gen = read_file(tmp)

In [80]: gen.next()
Out[80]:
[40507,
 None,
 3,
 107,
 None
]