繁体   English   中英

Python脚本被杀死

[英]Python script getting Killed

环境烧瓶0.10.1 SqlAlchemy 1.0.10 Python 3.4.3

使用单元测试

我创建了两个单独的测试,其目标是通过70万条记录查找数据库并进行一些字符串查找。 一次执行一次测试时,它可以正常工作,但是当使用以下命令执行整个脚本时:

python name_of_script.py

它在随机位置以“ KILLED”退出。

这两个测试的主要代码如下:

def test_redundant_categories_exist(self):
    self.assertTrue(self.get_redundant_categories() > 0, 'There are 0 redundant categories to remove. Cannot test removing them if there are none to remove.')

def get_redundant_categories(self):
        total = 0
        with get_db_session_scope(db.session) as db_session:
            records = db_session.query(Category)
            for row in records:
                if len(row.c) > 1:
                    c = row.c
                    #TODO: threads, each thread handles a bulk of rows
                    redundant_categories = [cat_x.id
                                            for cat_x in c
                                            for cat_y in c
                                            if cat_x != cat_y and re.search(r'(^|/)' + cat_x.path + r'($|/)', cat_y.path)
                                            ]
                    total += len(redundant_categories)
            records = None
            db_session.close()
        return total

另一个测试调用位于manager.py文件中的函数,该函数执行类似的操作,但是在数据库中添加了批量删除功能。

    def test_remove_redundant_mappings(self):
        import os
        os.system( "python ../../manager.py remove_redundant_mappings" )
        self.assertEqual(self.get_redundant_categories(), 0, "There are redundant categories left after running manager.py remove_redundant_mappings()")

测试之间是否可以将数据保存在内存中? 我不太了解如何单独执行测试,但是当背靠背运行时,该过程以Killed结尾。

有任何想法吗?

编辑(我尝试无济于事的东西):

  • manager.py导入函数,然后不使用os.system(..)调用
  • import gc和运行gc.collect()get_redundant_categories()并调用后remove_redundant_mappings()

在上下搜索时,我偶然遇到了这个StackOverflow问题/答案中的以下评论

我认为正在发生的事情是人们正在实例化会话,而不是关闭会话。 然后在不关闭会话的情况下对对象进行垃圾回收。 当会话对象超出范围时,为什么sqlalchemy会话不会自行关闭,并且将永远不在我身边。 @ melchoir55

因此,我将以下代码添加到正在测试的方法中:

db_session.close()

现在,单元测试将执行而不会被杀死。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM