Python脚本被杀死
环境 烧瓶0.10.1 SqlAlchemy 1.0.10 Python 3.4.3 使用unittest 我创建了两个独立的测试,其目标是通过700k记录查看数据库,并进行一些字符串查找。当一次执行一个测试时,它工作正常,但当整个脚本使用以下命令执行时:Python脚本被杀死,python,python-3.x,flask,flask-sqlalchemy,python-unittest,Python,Python 3.x,Flask,Flask Sqlalchemy,Python Unittest,环境 烧瓶0.10.1 SqlAlchemy 1.0.10 Python 3.4.3 使用unittest 我创建了两个独立的测试,其目标是通过700k记录查看数据库,并进行一些字符串查找。当一次执行一个测试时,它工作正常,但当整个脚本使用以下命令执行时: python name_of_script.py 它在随机的地方以“杀死”的形式存在 两个测试的主代码如下所示: def test_redundant_categories_exist(self): self.assertTrue(
python name_of_script.py
它在随机的地方以“杀死”的形式存在
两个测试的主代码如下所示:
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()")
在两次测试之间,数据是否可以保存在内存中?我不太明白单独执行测试是如何工作的,但是当背靠背运行时,过程以kill结束
有什么想法吗
编辑(我尝试过但无效的内容):
- 从
并在不使用manager.py导入函数
os.system(..)的情况下调用它
并在import gc
和调用get\u redundant\u categories()
remove\u redundant\u mappings()之后运行
gc.collect()
db_session.close()
现在unittest执行时不会被终止。使用
os.system
真的有必要吗?它会产生一个新的进程,可能会引起麻烦。通过python导入remove_redundant_mappings
似乎是一个更好的开始。我确实尝试过从manager导入它,但在执行过程中说它找不到模块管理器。您应该检查系统的日志文件(如果您在linux上,可以使用dmesg
)。这听起来像是内核为了保护系统而杀死了进程。如果您正在将大量信息加载到内存中,可能会在系统日志中引发OOM(内存不足)错误。您可能希望将os.path.join(dirname(\uuu FILE\uuuu),“…”,“…”)
添加到您的“sys.path”中,以便能够导入。这不是最漂亮的一行,但仍然比你的os.system
好。也许看看ps aux | grep python
和top
(或htop
)的内存可以帮助调试。