相关疑难解决方法(0)

为什么我不能在python中处理KeyboardInterrupt?

我正在Windows上编写python 2.6.6代码,如下所示:

try:
    dostuff()
except KeyboardInterrupt:
    print "Interrupted!"
except:
    print "Some other exception?"
finally:
    print "cleaning up...."
    print "done."
Run Code Online (Sandbox Code Playgroud)

dostuff()是一个永远循环的函数,一次从输入流读取一行并对其进行操作.我希望能够在我按下ctrl-c时停止并清理它.

发生的事情是,下面的代码except KeyboardInterrupt:根本没有运行.打印的唯一内容是"清理......",然后打印出如下所示的回溯:

Traceback (most recent call last):
  File "filename.py", line 119, in <module>
    print 'cleaning up...'
KeyboardInterrupt
Run Code Online (Sandbox Code Playgroud)

因此,异常处理代码没有运行,并且traceback声称在finally子句期间发生了KeyboardInterrupt ,这没有意义,因为命中ctrl-c是导致该部分首先运行的原因!甚至通用except:子句也没有运行.

编辑:基于注释,我try:用sys.stdin.read()替换了块的内容.问题仍然与描述完全一致,finally:块的第一行运行,然后打印相同的回溯.

编辑#2: 如果我在阅读后添加了很多东西,那么处理程序就可以了.所以,这失败了:

try:
    sys.stdin.read()
except KeyboardInterrupt:
    ...
Run Code Online (Sandbox Code Playgroud)

但这有效:

try:
    sys.stdin.read()
    print "Done reading."
except KeyboardInterrupt:
    ...
Run Code Online (Sandbox Code Playgroud)

这是打印的内容:

Done reading. Interrupted!
cleaning up...
done.
Run Code Online (Sandbox Code Playgroud)

因此,出于某种原因,"完成阅读".即使前一行发生异常,也会打印行.这不是一个真正的问题 - 显然我必须能够在"try"块内的任何地方处理异常.但是,打印不能正常工作 - 它不会像之前那样打印换行符!"Interruped"印在同一条线上......前面有一个空格,出于某种原因......?无论如何,在那之后代码完成它应该做的事情. …

python windows keyboardinterrupt

38
推荐指数
2
解决办法
3万
查看次数

停止无限循环重复调用 os.system

谢谢大家看到我的帖子。

首先,以下是我的代码:

import os

print("You can create your own message for alarm.")
user_message = input(">> ")

print("\n<< Sample alarm sound >>")

for time in range(0, 3):
    os.system('say ' + user_message) # this code makes sound.

print("\nOkay, The alarm has been set.")

"""
##### My problem is here #####
##### THIS IS NOT STOPPED #####

while True:
    try:
        os.system('say ' + user_message)
    except KeyboardInterrupt:
        print("Alarm stopped")
        exit(0)
"""
Run Code Online (Sandbox Code Playgroud)

我的问题是Ctrl + C 不起作用!

我尝试改变try块的位置,并制作信号(SIGINT)捕捉功能。

但那些也不起作用。

我看过/sf/answers/583464871//sf/answers/2304614931/ …

python loops os.system try-catch python-3.x

5
推荐指数
1
解决办法
2002
查看次数