擅长:python、mysql、java
<p>这里发生了几件事</p>
<p>从<a href="https://docs.python.org/3/library/signal.html#signals-and-threads" rel="nofollow noreferrer">https://docs.python.org/3/library/signal.html#signals-and-threads</a>:</p>
<blockquote>
<p><strong>Python signal handlers are always executed in the main Python thread of the main interpreter, even if the signal was received in another thread.</strong></p>
</blockquote>
<p>主线程创建一个非守护进程线程,并使用无限循环运行test_func()。然后主线程退出。非守护进程线程继续打印消息,然后休眠3秒钟,以此类推</p>
<p>由于中断处理程序位于主线程上,因此非守护进程线程将保持运行,按Ctrl+C不会停止执行</p>
<p>但是,在Windows上,当<em>Ctrl+C</em>不起作用时,通常可以按<em>Ctrl+Pause</em>或<em>Ctrl+ScrLk</em>来终止Python进程</p>
<p>如果代码运行test_func(),并在主键盘上执行sleep调用,则按Ctrl+C将引发键盘中断异常</p>
<pre><code>def main():
test_func()
# thread0 = threading.Thread(target=test_func)
# thread0.daemon = True
# thread0.start()
</code></pre>