在Python中,可以使用以下方法來(lái)停止正在運(yùn)行的代碼:
使用KeyboardInterrupt
異常:
可以在代碼中插入一個(gè)try-except
塊,在except
塊中捕獲KeyboardInterrupt
異常,并執(zhí)行相應(yīng)的停止代碼。例如:
try:
# 運(yùn)行的代碼
except KeyboardInterrupt:
# 停止代碼
使用sys.exit()
函數(shù):
可以調(diào)用sys.exit()
函數(shù)來(lái)退出Python程序。例如:
import sys
# 運(yùn)行的代碼
# 停止代碼
sys.exit()
使用os._exit()
函數(shù):
可以調(diào)用os._exit()
函數(shù)來(lái)立即終止Python進(jìn)程。例如:
import os
# 運(yùn)行的代碼
# 停止代碼
os._exit(0)
請(qǐng)注意,在使用sys.exit()
或os._exit()
函數(shù)時(shí),會(huì)立即終止整個(gè)Python進(jìn)程,而不僅僅停止正在運(yùn)行的代碼塊。而使用KeyboardInterrupt
異??梢栽诓东@到異常后,繼續(xù)執(zhí)行后續(xù)的代碼。