使用control-c退出python脚本时的自定义输出 [英] custom output when control-c is used to exit python script

查看:53
本文介绍了使用control-c退出python脚本时的自定义输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望用户使用Control-c关闭脚本,但是当按下control-c时,它会显示错误和关闭原因(这很有意义).有没有一种方法可以将自己的自定义输出显示到屏幕上,而不是显示什么?不确定如何处理该特定错误.

I would like the user to use control-c to close a script, but when control-c is pressed it shows the error and reason for close (which make sense). Is there a way to have my own custom output to the screen rather than what is shown? Not sure how to handle that specific error.

推荐答案

您可以使用 try..except 捕获KeyboardInterrupt:

You could use try..except to catch KeyboardInterrupt:

import time

def main():
    time.sleep(10)

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print('bye')

这篇关于使用control-c退出python脚本时的自定义输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆