1. 使用 `sys.exit()` 函数:
import sys
sys.exit(0) 0 表示正常退出,非零值表示异常退出
2. 使用 `KeyboardInterrupt` 异常:
try:
while True:
运行的代码
except KeyboardInterrupt:
print("程序被中断")
3. 使用 `os._exit()` 函数:
import os
os._exit(0) 立即终止整个Python进程
4. 使用 `os.kill()` 函数发送 `SIGTERM` 信号:
import os
import signal
os.kill(os.getpid(), signal.SIGTERM) 向当前进程发送SIGTERM信号
5. 使用 `threading.Thread._stop()` 方法(不推荐,因为不安全):
import threading
def my_function():
while True:
运行的代码
my_thread = threading.Thread(target=my_function)
my_thread.start()
my_thread._stop() 停止线程的执行
请注意,使用 `sys.exit()`、`os._exit()` 或 `os.kill()` 函数会立即终止整个Python进程,而不仅仅是停止正在运行的代码块。而使用 `KeyboardInterrupt` 异常可以在捕获到异常后,继续执行后续的代码。