如果我在linux终端上运行python程序并按ctrl + c手动中止它,我怎样才能让我的程序在发生此事件时执行某些操作.
就像是:
if sys.exit():
print "you chose to end the program"
Run Code Online (Sandbox Code Playgroud)
您可以编写信号处理功能
import signal,sys
def signal_handling(signum,frame):
print "you chose to end the program"
sys.exit()
signal.signal(signal.SIGINT,signal_handling)
while True:
pass
Run Code Online (Sandbox Code Playgroud)
按Ctrl + c发送一个SIGINT中断,输出:
你选择结束该计划
好吧,你可以使用KeyBoardInterrupttry-except块:
try:
# some code here
except KeyboardInterrupt:
print "You exited
Run Code Online (Sandbox Code Playgroud)
在命令行中尝试以下操作:
import time
try:
while True:
time.sleep(1)
print "Hello"
except KeyboardInterrupt:
print "No more Hellos"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
796 次 |
| 最近记录: |