我正在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创建一个非常基本的命令行实用程序,并且试图将其设置为使用户能够在执行Ctrl + C的过程中中断任何正在运行的操作,并通过发送EOF并退出程序来退出程序Ctrl + Z。但是,在最后一天,我一直在解决这个令人沮丧的问题,在取消使用a的运行操作后,再次KeyboardInterrupt按Ctrl + C会发送EOFError而不是a KeyboardInterrupt,这将导致程序退出。KeyboardInterrupt除了在我输入任何命令或空行(在其中发送附加命令KeyboardInterrupt而不是我提供的输入)之前,随后按Ctrl + C会一直发送。这样做之后,再次按Ctrl + C将再次发送EOFError,然后从那里继续。这是演示我的问题的代码的最小示例;
import time
def parse(inp):
time.sleep(1)
print(inp)
if inp == 'e':
return 'exit'
while True:
try:
user_in = input("> ").strip()
except (KeyboardInterrupt, Exception) as e:
print(e.__class__.__name__)
continue
if not user_in:
continue
try:
if parse(user_in) == 'exit':
break
except KeyboardInterrupt:
print("Cancelled")
Run Code Online (Sandbox Code Playgroud)
这是我的代码的一些示例输出;
>
>
>
> KeyboardInterrupt
> KeyboardInterrupt
> KeyboardInterrupt
> KeyboardInterrupt
> KeyboardInterrupt
> KeyboardInterrupt
>
> …Run Code Online (Sandbox Code Playgroud) 我想在 Ctrl+C / SIGINT 或用户输入时优雅地退出程序。如果可能,终端应该提示类似的东西;“按回车键终止”。
由 Python 3.6 执行的代码
def worker(process):
i = 0
while True:
print('Process %d count %d' % (process, i))
i += 1
def main():
available_num_cores = multiprocessing.cpu_count()
use_num_cores = available_num_cores - 1 if available_num_cores > 1 else 1
print('Using %d cores' % use_num_cores)
pool = multiprocessing.Pool(use_num_cores)
for i in range(0, use_num_cores):
pool.apply_async(worker, args=(i,))
pool.close()
pool.join()
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
已接受此问题的答案Catch Ctrl+C / SIGINT and exit multiprocesses gracefully in python。不工作,它失败并出现错误:
Process SpawnPoolWorker-1:
Process 0 …Run Code Online (Sandbox Code Playgroud) python multiprocessing python-3.x selenium-webdriver python-3.6