Python Forum
python difference between sys.exit and exit() - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: python difference between sys.exit and exit() (/thread-38683.html)



python difference between sys.exit and exit() - mg24 - Nov-11-2022

Hi Team,

In my project I used try except block ,
if exception occured I used sys.exit()

I saw exit() in someones code ,

when to use sys.exit and exit()

if not Path.exists(source_path):
        print(f'Source path: {source_path} does not exists')
        exit()
Thanks
mg


RE: python difference between sys.exit and exit() - deanhystad - Nov-12-2022

Have you tried google? Many good articles about this.

Official documentation:
https://docs.python.org/2/library/constants.html#quit
https://docs.python.org/2/library/sys.html#sys.exit
https://docs.python.org/2/library/os.html#os._exit

The short answer is that quit(), exit() and sysExit() are all pretty much the same. They raise a sysExit exception. I think exit() and quit() might just be references to sys.exit(). There is also os.exit() which kills a process, but doesn't necessarily exit a program.

You probably don't want to do this:
if not Path.exists(source_path):
        print(f'Source path: {source_path} does not exists')
        exit()
Using exit() like this can be ok, but generally it is a sign of sloppy programming. The programmer got into a mess and doesn't have an easy escape route. I would look for a less nuclear option. At a minimum raise a custom exception and put a handler somewhere. That way the program can differentiate between different reasons for escaping the program and take appropriate actions.

At the very least do this:
if not Path.exists(source_path):
        exit(f'Source path: {source_path} does not exists')
And remember that quit(), exit(), sys.exit() all just raise an exception. If you are sloppy with try/except, calling exit() might not exit your program.
try:
    exit("Quitting")
except:
    pass
print("Oh no you are not!")
Output:
Oh no you are not!