gpt4 book ai didi

Python 2.7 ctrl+c 不确定行为

转载 作者:行者123 更新时间:2023-12-01 05:34:10 26 4
gpt4 key购买 nike

我希望在我的脚本中进行正确的 CTRL+C 处理,我一直在阅读一些示例,但无法实现确定性行为。例如,给定以下脚本:

  1 import signal
2 import time
3
4 def sigint_handler(signum, frame):
5 raise Exception('captured ctrl+c')
6
7 signal.signal(signal.SIGINT, sigint_handler)
8
9 c = True
10 while c:
11 try:
12 pass
13 except KeyboardInterrupt as e:
14 print 'captured keyboardexception'
15 print str(e)
16 except Exception as e:
17 print 'captured exception'
18 print str(e)
19 c = False

我可以获得这两个不同的输出

$ python ctrlc.py
^Ccaptured exception
captured ctrl+c

$ python ctrlc.py
^CTraceback (most recent call last):
File "ctrlc.py", line 12, in <module>
pass
File "ctrlc.py", line 5, in sigint_handler
raise Exception('captured ctrl+c')
Exception: captured ctrl+c

我尝试了不同的配置,也使用了双重异常处理并且没有信号处理,但您总是可以通过点击 CTRL+C

获得不同的行为

最佳答案

经典的竞赛条件。当你的循环展开时,它看起来像这样:

while True:
....
try:
pass <-----
....

while True: <-----
....
try:
pass

在箭头之间的时间里,您实际上并不处于 try/except 子句中。所以你应该期待两种不同的行为。

试试这个:

try:
while True:
pass
except....

关于Python 2.7 ctrl+c 不确定行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519195/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com