在 Python 线程中处理信号

发布于 2024-10-10 12:29:55 字数 239 浏览 2 评论 0 原文

我有一个用 Python 编写的线程应用程序,每当通过 Ctrl+C 或有时使用 Kill 接收到中断时,应用程序就会挂起。堆栈跟踪是从一个线程显示的,但应用程序仍保留在前台,我通常必须使用 Ctrl+Z 将其置于后台,然后试图杀死它。

在线程应用程序内部处理信号和键盘中断的正确方法是什么?

I have a threaded application written in Python, and whenever an interrupt is received via Ctrl+C or sometimes with kill, the application will hang. A stack trace is presented from one thread, but the application remains in the foreground, and I usually have to background it with Ctrl+Z then attempt to kill it.

What is the proper way of handling signals and keyboard interrupts inside of a threaded application?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

还如梦归 2024-10-17 12:29:55

如果在启动每个线程之前设置newthread.daemon = True,则当主线程退出时,线程将自动被终止。这并不完全是您要问的,但从您所描述的情况来看,这听起来可能值得了解。

If you set newthread.daemon = True before starting each thread, the threads will automatically be killed when the main thread exits. That's not precisely what you were asking, but from what you've described, it sounds like it could be worth knowing.

眼泪也成诗 2024-10-17 12:29:55

我解决这个问题的方法是制作一个可以保存线程列表的模块。该模块还有一个方法可以杀死该列表中的每个线程。我注册了此方法,以便在收到 SIGINT 信号时调用。最后,我为 Thread 创建了一个包装类,它将自动将创建的实例添加到线程列表中。

The way I worked around this issue was to make a module that could kept a list of threads. The module also had a method that killed every thread in that list. I registered this method to be called when the SIGINT signal was received. Lastly, I created a wrapper class for Thread that would automatically add the created instance to the list of threads.

绅刃 2024-10-17 12:29:55

CPython 线程:中断 涵盖了 Python 线程中信号发生的情况,以及针对您的问题的各种解决方案。这是一本很好的读物。

CPython Threading: Interrupting covers what happens to signals in Python threads, and various solutions to your problem. It is a good read.

嗼ふ静 2024-10-17 12:29:55

使用 signal 模块 并在此处继续阅读 Python 中的信号处理程序和日志记录了解可能存在的陷阱。

为了捕获用户的 Ctrl+C 操作,您必须配置 SIGINT 的 >signal 处理程序。

在信号处理程序中通知(消息队列或 RLock 同步属性访问)您的线程要关闭,或者您打算做什么。

Use the signal module and continue reading here Signal handlers and logging in Python about possible pitfalls.

In order to catch Ctrl+C actions from the user you have to profice a signal handler for SIGINT.

Within the signal handler notify (message queues or RLock synchronized attribute access) your threads to shutdown, or what ever you intent to do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文