Python Tutorial 84: What are the ways for a program to actively exit the process? 5 ways, there is always one suitable for you

In Python, there are many ways to actively exit the program process. Here are 5 methods for your reference:
1.sys.exit(): This is the most common way, it will cause a SystemExit exception. If this exception is not caught, the Python interpreter will exit. You can optionally pass an exit status parameter to sys.exit(), 0 usually indicates a normal exit, and a non-zero value indicates an abnormal exit.

import sys  
sys.exit(0)  # 正常退出  
sys.exit(1)  # 异常退出

2.os._exit(): This function will immediately terminate the current process and will not perform any cleaning operations, so it is generally not recommended to be used in normal programs. But in the child process, in order to prevent sharing state with the Python interpreter of the parent process, this function is usually used.

import os  
os._exit(0)  # 立即退出,不执行任何清理操作

3.raise SystemExit: This method is similar to sys.exit(), but it throws an exception, so you need to catch it in a try/except block or handle it in a finally block.

raise SystemExit(0)  # 抛出异常,需要捕获或处理

4. Use os.kill(): This function will send a signal to the specified process. If the signal is SIGTERM (default value), the process will be terminated.

import os  
os.kill(pid, signal.SIGTERM)  # 发送SIGTERM信号给指定的进程pid,进程将会被终止

5.exit() is an exit method based on terminal commands. It can exit the Python interpreter and return a status code. When exiting using the exit() method, some cleaning work will be performed first, such as closing files, etc., and then the Python interpreter will exit. The following is sample code to exit the program using the exit() method:

exit(0) # 退出程序,返回状态码0

complete! ! thanks for watching

----------★★Historical blog post collection★★----------
My zero-based Python tutorial, Python introduction to advanced video tutorial Py installation py project Python module Python crawler Json
Insert image description here

Guess you like

Origin blog.csdn.net/gxz888/article/details/135105701