Python Forum
python difference between sys.exit and exit()
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python difference between sys.exit and exit()
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')
Have you tried google? Many good articles about this.

Official documentation:

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')
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.
print("Oh no you are not!")
Oh no you are not!

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to find difference between fake driving license or real using python? pjaymn 5 2,797 Jun-14-2024, 07:01 AM
Last Post: Pedroski55
  Schedule exit a program at a specific time 4 am every day. chubbychub 3 382 May-17-2024, 03:45 PM
Last Post: chubbychub
  Basic Coding Question: Exit Program Command? RockBlok 3 718 Nov-19-2023, 06:31 PM
Last Post: deanhystad
  Why does [root.destroy, exit()]) fail after pyinstaller? Rpi Edward_ 4 732 Oct-18-2023, 11:09 PM
Last Post: Edward_
  fetching exit status hangs in paramiko saisankalpj 3 1,352 Dec-04-2022, 12:21 AM
Last Post: nilamo
  Failing reading a file and cannot exit it... tester_V 8 1,941 Aug-19-2022, 10:27 PM
Last Post: tester_V
  force a program to exit ? Armandito 3 2,751 May-12-2022, 04:03 PM
Last Post: Gribouillis
  Process finished with exit code 137 (interrupted by signal 9: SIGKILL) erdemath 2 9,868 Apr-18-2022, 08:40 PM
Last Post: erdemath
  Exit function from nested function based on user input Turtle 5 3,115 Oct-10-2021, 12:55 AM
Last Post: Turtle
  While loop doesn't exit KenHorse 3 2,107 Jun-20-2021, 11:05 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020