Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Python by (47.6k points)

I am aware of the die() command in PHP which stops a script early.

How can I do this in Python?

1 Answer

0 votes
by (106k points)
edited by

In Python to terminate any script, you can use the sys module:-

import sys 

sys.exit()

The above code can be used to terminate any script.

sys.exit([arg]):-

This function is used to exit from Python. This is implemented by raising the SystemExit exception.

Talking about the optional argument arg, this can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination”.

When an error occurs then sys.exit("some error message") is a quick way to exit a program.

The exit() function ultimately “only” raises an exception, it will only exit the process when called from the main thread, and the exception is not intercepted.

The main and very important reason why you should prefer sys.exit because it is more "friendly" to other code, all it actually does is raise an exception.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94k users

Browse Categories

...