中断Python单元tes时关闭资源

2024-05-14 01:26:42 发布

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

我使用的是标准库unittest模块(因此我用python -m unittest运行我的测试)。在

我定义了setUpModule在后台启动一个子进程(使用subprocess.Popen)和{}关闭其输入和输出流,然后在其进程ID上调用os.killpg

如果我让一个测试运行它的进程,这一切都可以正常工作,但是如果我使用Ctrl-C提前停止它,我会收到一堆警告,并且我的终端会慢到爬行状态:

keyboardInterrupt
sys:1: ResourceWarning: unclosed file <_io.FileIO name=6 mode='rb'>
/.../lib/python3.4/importlib/_bootstrap.py:2150: ImportWarning: sys.meta_path is empty
sys:1: ResourceWarning: unclosed file <_io.FileIO name=7 mode='wb'>
sys:1: ResourceWarning: unclosed file <_io.BufferedWriter name='/dev/null'>

有没有什么方法可以拦截KeyboardInterrupt以便正确清理?有没有更好的方法来启动和停止测试模块的外部程序?在


Tags: 模块方法nameio标准定义进程mode
2条回答

根据测试的组织方式,您还可以捕获KeyboardInterrupt并调用except块中的tearDown方法:

import unittest

class MyTestCase(unittest.TestCase):

  def test_one(self):
      for i in range(1<<20):
         if i % 271 == 0:
            print i

  @classmethod
  def tearDownClass(cls):
      print("\nteardown")

if __name__ == '__main__':
     try:
        unittest.main()
     except KeyboardInterrupt:
        MyTestCase.tearDownClass()

不管怎样,我试着按照https://stackoverflow.com/a/4205386/1475412中的说明找到了一个解决方案。在

我为SIGINT注册了一个处理程序,它杀死了子进程,然后调用了sys.exit()。我以为我可以在处理程序中重新引发KeyboardInterrupt,但那没用。在

相关问题 更多 >