Python CTRL+C to exit interpreter?

南笙酒味 提交于 2019-12-21 05:12:09

问题


Python 2.73

Why is it on my laptop when I hit CTRL+C, I can exit the interpreter and on my desktop hitting CTRL+C will make the interpreter shoot back at me a KeyboardInterrupt message. How can I get rid of this KeyboardInterrupt and go back to exiting with CTRL+C!

On my desktop it's required to input CTRL+Z and hitting enter to exit.

I am using PowerShell on both computer. Same 64bit, one is Win7 one is Win8


回答1:


You could change the signal handler for CTRL-C to something that exits the interpreter:

import signal
import sys
signal.signal(signal.SIGINT, lambda number, frame: sys.exit())

You could probably put that code in a file to be run automatically when an interactive session starts, then set the environment variable PYTHONSTARTUP to the name of that file:

http://docs.python.org/3/using/cmdline.html?highlight=startup#envvar-PYTHONSTARTUP




回答2:


A slightly shorter version of the previous answer:

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

SIG_DFL means default signal handling, so Python does not catch it to raise a KeyboardInterrupt exception.



来源:https://stackoverflow.com/questions/18707523/python-ctrlc-to-exit-interpreter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!