# Python 信号处理中调用 print 安全吗？

Original title: Is it safe to call print in a Python signal handler?

> Hacker News story 49450248 · language: zh · submitted 2026-08-26
> Web version: https://zeli.app/zh/story/49450248
> About this feed: https://zeli.app/llms.txt · Agent guide: https://zeli.app/skill.md

▲ 64 · by [hellerve](<https://news.ycombinator.com/user?id=hellerve>) · 💬 35
[original](<https://iafisher.com/2026/08/sigprint>) · [HN discussion](<https://news.ycombinator.com/item?id=49450248>)

## Summary

很多人以为 Python 的信号处理机制比 C 语言更安全，因为解释器会在状态一致时才调用用户代码。但事实并非如此简单。Python 的信号处理程序具有意外的可重入性：如果一个信号在另一个信号处理程序执行期间到达，它可能会再次被调用。我在极端测试中发现，如果在信号处理程序中调用 print，当快速连续触发信号时，程序会因重入调用而崩溃，抛出 RuntimeError。虽然这种情况在真实应用中极难复现，且崩溃比 C 语言中可能出现的死锁或数据损坏要好得多，但这仍提醒我们：在信号处理程序中应避免执行非平凡操作。

## Key quote

> 即使在极端情况下，在 Python 信号处理程序中调用 print 也可能导致程序崩溃。

## HN discussion (35 comments)

### [nine_k](<https://news.ycombinator.com/item?id=49495509>)

> POSIX 信号从设计之初就是残缺的，唉：https://lwn.net/Articles/414618/
>
> 不管是不是 Python，在信号处理函数里几乎没什么操作是安全的。

### [IgorPartola](<https://news.ycombinator.com/item?id=49494869>)

> 真正让人哭笑不得的是把信号处理和线程混在一起用，尤其是在 Linux 上。这里有一种简单可行的做法，但也有一千种会踩坑的写法。

### [jrumbut](<https://news.ycombinator.com/item?id=49495668>)

> 我觉得作者低估了这个问题的重要性。我很容易就能想象有人写出类似示例的代码，这只需要大量的信号和一个 print 语句。
>
> 如果你的程序会生成信号，它可能会无意中产生信号风暴。如果你在信号处理函数里放了 print 语句，就会得到这个结果。
>
> 这倒也不足为奇，但知道这一点挺好。

### [Uptrenda](<https://news.ycombinator.com/item?id=49495369>)

> 当你把它和事件循环、多个操作系统以及不同的 Python 版本结合起来时，情况会变得甚至更棘手。别误会：我热爱 Python，但程序关闭和清理工作确实很让人头疼。如果有人能写一个（好用的）库来解决这个问题，那肯定会很受欢迎。

### [charcircuit](<https://news.ycombinator.com/item?id=49495627>)

> 我不明白为什么到了 2026 年这还是个问题。信号应该通过新线程来处理，这样就能解决所有围绕它们的复杂性。大家都知道当前的实现方式在能安全执行的操作上极其受限。这种暂停当前正在运行的代码，然后去别处执行额外代码的整个思路，事实证明并不是个好主意。

---

## Cite

- Page: https://zeli.app/zh/story/49450248
- Date: 2026-08-26
- Source: iafisher.com (https://iafisher.com/2026/08/sigprint)
- Hacker News: https://news.ycombinator.com/item?id=49450248

## Other languages

- en: https://zeli.app/story/49450248 · markdown: https://zeli.app/story/49450248.md
- ja: https://zeli.app/ja/story/49450248 · markdown: https://zeli.app/ja/story/49450248.md
- ko: https://zeli.app/ko/story/49450248 · markdown: https://zeli.app/ko/story/49450248.md
- de: https://zeli.app/de/story/49450248 · markdown: https://zeli.app/de/story/49450248.md
- es: https://zeli.app/es/story/49450248 · markdown: https://zeli.app/es/story/49450248.md
- ru: https://zeli.app/ru/story/49450248 · markdown: https://zeli.app/ru/story/49450248.md
