Depending on your system, press one of the following key combinations to end a Python program:

  • CTRL + C on Windows.
  • Control + C on Mac.

How to End the Interactive Python Command-Line Session

  • CTRL + Z on Windows.
  • Control + Z on Mac.

Terminate Script Using sys.exit() for simple programs

For simple Python programs, you can use the sys.exit() function to exit the program gracefully. This function takes an exit code as an argument, indicating whether the program left successfully or with an error.

Here’s an example of using sys.exit() in a Python program:

				
					import sys

def main():
    # your program logic here
    sys.exit(0)

if __name__ == "__main__":
    main()

				
			

In the above example, sys.exit(0) indicates that the program exited successfully.

Handling Exceptions with try/except

For more complex Python programs, it’s essential to handle exceptions gracefully. If an unhandled exception occurs in your program, it can crash, leaving resources allocated and files open.

To handle exceptions gracefully, you can use a try/except block. In the try block, you write the code that may raise an exception, and in the except block, you handle the exception.

Here’s an example of using try/except to handle exceptions in a Python program:

				
					import sys

def main():
    try:
        # your program logic here
    except Exception as e:
        print(f"An error occurred: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()

				
			

In the above example, any unhandled exceptions will cause the program to exit with an error code of 1. In addition, the except block also prints an error message to the console.

Using Context Managers

In Python, you can use context managers to ensure that resources are correctly cleaned up when your program ends. Context managers allow you to allocate resources at the beginning of a code block and automatically clean up those resources at the end.

Here’s an example of using context managers to open and close a file:

				
					with open("example.txt", "w") as f:
    f.write("Hello, World!")

				
			

In the above example, the with statement opens the file “example.txt” for writing. When the block ends, the file is automatically closed, ensuring all resources are released.

Wrap up

I appreciate you reading. I hope you were able to get your software to stop 🙂


Thanks for reading. Happy coding!