Sometimes when a condition is established, the program needs to be terminated. You can use sys.exit() to exit the program. sys.exit() will raise an exception
If this exception is not caught, then the python compiler will exit and the following program will not be executed.
If this exception is caught (try...except...finally), catching this exception can do some extra cleanup work, and the subsequent program will continue to execute.
Note: 0 means normal exit, other values (1-127) are abnormal, and abnormal events can be thrown for capture.
Another way to terminate the program os._exit()
In general, use sys.exit(), generally use os._exit() in the child process from fork
import os, sys
import pandas as pd
import numpy as np
df=pd.DataFrame({'a':[1,2,3,4],'b':['a','b','c',np.nan],'c':['2017-09','2017-09-12','2017-08-22','2017-07-11'],'d':['2017-09','2017-12','2017-08','2017-07']})
t=df.iloc[2,:].tolist()
df.columns=t
print(df)
c=[1,2,5]
dic={1:2,2:3,3:4}
# print(dic.keys())
new_col=[]for x in c:if x not in dic.keys():
new_col.append(x)if new_col:print(new_col)
sys.exit(1)print('ssss')
Knowledge point expansion:
1. sys.exit()
Executing this statement will directly exit the program, which is also a frequently used method, and does not need to consider the influence of factors such as the platform. It is generally the preferred method to exit the Python program.
This method contains a parameter status, which is 0 by default, which means normal exit, or 1, which means abnormal exit.
import sys
sys.exit()
sys.exit(0)
sys.exit(1)
This method raises a SystemExit exception (this is the only exception that will not be considered an error). When there is no setting to capture this exception, the program execution will exit directly. Of course, this exception can also be caught to perform some other operations.
2. os._exit()
The effect is also to exit directly without throwing an exception, but its use will be restricted by the platform, but our commonly used Win32 platform and UNIX-based platforms will not be affected.
It is said on Zhihu that the _exit() function of the C language is called (not verified)
3. os.kill()
Generally used to kill the process directly, but it can only be effective on the UNIX platform.
Basic principle: This function simulates the traditional UNIX function to send signals to the process, which contains two parameters: one is the process name, which is the process to receive the signal; the other is the operation to be performed.
So far this article on the method of ending running python is introduced. For more information about how to stop running python, please search the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support ZaLou.Cn more in the future!
Recommended Posts