23 lines
525 B
Markdown
23 lines
525 B
Markdown
|
---
|
|||
|
title: Python 捕获 Ctrl+C 手工终止程序的方法
|
|||
|
date: 2022-08-31 15:13:08
|
|||
|
sitemap: true
|
|||
|
keywords: [Python]
|
|||
|
categories: [Python]
|
|||
|
tags: [Python]
|
|||
|
---
|
|||
|
|
|||
|
日常编写调试运行程序过程中,难免需要手动终止程序。可以使用以下的方法捕获 KeyboardInterrupt,从而优雅地终止程序的运行。
|
|||
|
|
|||
|
``` python
|
|||
|
import sys, time
|
|||
|
|
|||
|
try:
|
|||
|
while True:
|
|||
|
# # DO THINGS ....
|
|||
|
time.sleep(1)
|
|||
|
except KeyboardInterrupt:
|
|||
|
# QUIT with Ctrl+C 在这里处理善后工作
|
|||
|
sys.exit()
|
|||
|
```
|