Python CTRL+C to exit interpreter?

懵懂的女人 提交于 2019-12-03 17:04:59
Stephan Wenger

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

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.

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