<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[django test 无法正常退出的问题]]></title><description><![CDATA[<p dir="auto">在用<code>django</code>的时候如果你在程序里开了其他线程（比如用作后台的长期服务程序）。那么在用<code>django</code>自带的测试程序就会有问题。测试完成之后程序无法自动退出。这是由于开启的线程还在运行的原因。</p>
<p dir="auto">解决方法也比较简单。这是因为<code>django</code>的测试代码中用的是<code>sys.exit()</code>来退出。但是当<code>python</code>程序还有其他线程在执行的时候这个指令是没办法退出的。<br />
把 <code>django/core/management/commands/test.py</code></p>
<pre><code>def handle(self, *test_labels, **options):
        from django.conf import settings
        from django.test.utils import get_runner

        TestRunner = get_runner(settings, options['testrunner'])

        test_runner = TestRunner(**options)
        failures = test_runner.run_tests(test_labels)

        if failures:
            sys.exit(1)
</code></pre>
<p dir="auto">改为</p>
<pre><code>def handle(self, *test_labels, **options):
        from django.conf import settings
        from django.test.utils import get_runner

        TestRunner = get_runner(settings, options['testrunner'])

        test_runner = TestRunner(**options)
        failures = test_runner.run_tests(test_labels)

        if failures:
            os._exit(1)
        os._exit(0)
</code></pre>
<p dir="auto">就是采用<code>os._exit()</code>进行退出。这样其他线程能够收到<code>SIGINT</code>的信号，然后回收资源退出就可以了。</p>
]]></description><link>http://community.bwbot.org/topic/208/django-test-无法正常退出的问题</link><generator>RSS for Node</generator><lastBuildDate>Wed, 22 Jul 2026 02:10:53 GMT</lastBuildDate><atom:link href="http://community.bwbot.org/topic/208.rss" rel="self" type="application/rss+xml"/><pubDate>Wed, 21 Jun 2017 09:04:14 GMT</pubDate><ttl>60</ttl></channel></rss>