1. 使用 `sys.exit()` 函数:
import syssys.exit(0) 0 表示正常退出,非零值表示异常退出
2. 使用 `KeyboardInterrupt` 异常:
try:while True:运行的代码except KeyboardInterrupt:print("程序被中断")
3. 使用 `os._exit()` 函数:

import osos._exit(0) 立即终止整个Python进程
4. 使用 `os.kill()` 函数发送 `SIGTERM` 信号:
import osimport signalos.kill(os.getpid(), signal.SIGTERM) 向当前进程发送SIGTERM信号
5. 使用 `threading.Thread._stop()` 方法(不推荐,因为不安全):
import threadingdef 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` 异常可以在捕获到异常后,继续执行后续的代码。
