Python sys.exit() Method

Python sys.exit() Method

  1. Syntax of Python sys.exit() Method
  2. Example Codes: Use sys.exit(0) Method for Successful Termination
  3. Example Codes: Use sys.exit(None) Method for Successful Termination
  4. Example Codes: Failed Termination With a Non-zero Value
  5. Example Codes: Failed Termination With an Error Message
  6. Example Codes: Failed Termination With a Dictionary
  7. Example Codes: Failed Termination With a Class

The sys module deals with the Python interpreter, it is a built-in module available in Python. The sys.exit() method allows us to stop the execution of a Python program, and it does so by raising a SystemExit exception.

Syntax of Python sys.exit() Method

sys.exit(arg)

Parameters

arg A parameter that defaults to 0. 0 refers to a successful termination of the process, and any non-zero value relates to an abnormal or unsuccessful termination.
Note that None is equivalent to giving a 0, which relates to a successful termination.

Returns

The exit() method does not return anything.

Example Codes: Use sys.exit(0) Method for Successful Termination

import sys

sys.exit(0)

Note that the default value is 0, so passing a 0 is optional.

Example Codes: Use sys.exit(None) Method for Successful Termination

import sys

sys.exit(None)

Example Codes: Failed Termination With a Non-zero Value

import sys

sys.exit(34)

This code throws an exception and will fail to terminate the program.

Example Codes: Failed Termination With an Error Message

import sys

sys.exit("ErrorName: This is an error message")

Output:

ErrorName: This is an error message

The exit() function will print the exact string as an output.

Example Codes: Failed Termination With a Dictionary

import sys

sys.exit({
    "text": "Hello",
    "number": 25,
    "array": [1, 2, 3, 4, 5]
})

Output:

{'text': 'Hello', 'number': 25, 'array': [1, 2, 3, 4, 5]}
process died unexpectedly: exit status 1

The exit() function will print the dictionary.

Example Codes: Failed Termination With a Class

import sys

class Text:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __repr__(self):
        return f"Text({self.a}, {self.b}, {self.c})"

sys.exit(Text(1, 2, 3))

Output:

Text(1, 2, 3)

The exit() function will print the string representation of the class object. If the class does not implement the __repr__() method, the object’s memory address is printed.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

LinkedIn GitHub

Related Article - Python Sys

  • Python sys.stdin Attribute
  • Python sys.argv List
  • Python sys.maxsize() Method
  • Python sys.stdout Method
  • Python sys.path Attribute