This is my code:
if __name__ == "__main__":
try:
main()
except Exception:
exc_info = sys.exc_info()
traceback.print_exception(*exc_info)
os.killpg(0, signal.SIGKILL)
exit(0)
When an exception occurs in the program, I want to use the killpg method of the os module to terminate the current process, but an error message
AttributeError: module 'os' has no attribute 'killpg'
appears. I am using Python version 3.7.
Can you help me solve this problem? Thank you very much.
Note: you should learn how to look at Python documentation, it will simplify programming (and you will be more productive). So bookmark the python standard library documentation (which gives you also quick link to language documentation).
In any case, the relevant page: https://docs.python.org/3/library/os.html#os.killpg
(and an other trick about documentation: do you see the URL? Just replace /3/ with /2/ and you get documentation of Python 2. So, we see the other answer uses a wrong assumption (and
os.kill
may also not be available.The function
os.killpg
exists on both Python2 and Python3, but both pages indicates that it is available only on Unix/Linux and similar systems (so probably also on macos) (and the note: not Emscripten, not WASI means that also on Unix and Linux it will not work on the listed controlled and portable environment: javascript and WebAssembly, so inside browsers it will not work).Why? Python is not in control of processes, so it just handle the request to the operating system. Not all operating systems have the concept of process group, or they handle in a different way. Note:
os.kill
support windows only in Python 2.7 and Python 3.2 and later.In any case, it you want to terminate the current process, you should use
exit()
, or other stronger functions. And if you use threads, also there are special functions. You see various questions and answers in this site about it. (But your question is about usingos.killpg
so I'll not divert the answer with better methods).In short: the function send signals to own process group, but only on operating systems where process groups are available (so as 2023, not in Windows). It is not the best way to terminate the calling process.