Python进程在执行期间突然终止

2024-10-01 15:29:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,现在面临的似乎是内存泄漏错误。 我已经编写了一个简单的脚本,试图从postgres数据库中获取多个列,然后继续对这些列执行简单的减法,并将结果存储在一个临时变量中,该变量正在写入一个文件中。我需要对数据库中的多对列执行此操作,并使用列表列表来存储不同的列名。在

我循环遍历这个列表的各个元素,直到列表用完为止。当我得到前几个列对的有效结果(valid是指输出文件包含预期值)时,程序突然在执行之间的某个地方被“杀死”。代码如下:

varList = [ ['table1', 'col1', 'col2'],
        ['table1', 'col3', 'col4'],
        ['table2', 'col1', 'col2'],
        # ..
        # and many more such lines
        # ..
        ['table2', 'col3', 'col4']]

try:

    conn = psycopg2.connect(database='somename', user='someuser', password='somepasswd')

    c = conn.cursor()

    for listVar in varList:
        c.execute("SELECT %s FROM %s" %(listVar[1], listVar[0]))

        rowsList1 = c.fetchall();

        c.execute("SELECT %s FROM %s" %(listVar[2], listVar[0]))

        rowsList2 = c.fetchall();

        outfile = file('%s__%s' %(listVar[1], listVar[2]), 'w')

        for i in range(0, len(rowsList1)):
            if rowsList1[i][0] == None or rowsList2[i][0] == None:
                timeDiff = -1

            else:
                timestamp1 = time.mktime(rowsList1[i][0].timetuple())
                timestamp2 = time.mktime(rowsList2[i][0].timetuple())
                timeDiff = timestamp2 - timestamp1

            outfile.write(str(timeDiff) + '\n')

        outfile.close();

    del rowsList1, rowsList2

#numpy.savetxt('output.dat', column_stack(rows))

except psycopg2.DatabaseError, e:
    print 'Error %s' % e
    sys.exit(1)

finally:
    if conn:
        conn.close()

我最初的猜测是有某种形式的内存泄漏,为了解决这个问题,我在两个大数组上添加了一个del语句,希望能够正确地收集内存。这一次,我得到了稍微好一点的输出(我的意思是为db列对创建了更多的输出文件)。 然而,在第10列或第11列之后,我的程序又被“杀死”。有人能告诉我这里有什么问题吗。有没有更好的方法来完成这个任务? 感谢任何帮助。在

PS:我知道这是一个相当低效的实现,因为我循环了很多次,但我需要一些快速和肮脏的东西来证明概念。在


Tags: 文件内存程序数据库列表connoutfilecol2
1条回答
网友
1楼 · 发布于 2024-10-01 15:29:37

我认为这里的问题是你选择了所有的东西,然后在应用程序代码中过滤它,而你应该用sql查询来选择你想要的东西。如果您像这样在sql查询中选择所需的内容:

对于varlist中的listvar: 从listvar[0]中选择listvar[1],listvar[2]不为null,listvar[2]不为空

# then...

timeDiff = {}
for row in rows:
    timestamp1 = time.mktime(row[0].timetuple())
    timestamp2 = time.mktime(row[0].timetuple())
    timeDiff[identifier] = timestamp2 - timestamp1 #still need to assoc timediff with row... maybe you need to query a unique identifyer also?

#and possibly a separate... (this may not be necessary depending on your application code.  do you really need -1's for irrelevant data or can you just return the important data?)

select listvar[1], listvar[2] from listvar[0] where listvar[1] is null or listvar[2] is null

for row in rows:
    timeDiff[identifier] = -1 # or None

相关问题 更多 >

    热门问题