Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: using sys.exit or SystemExit differences and suggestions

Reading online some programmers use sys.exit, others use SystemExit.
Sorry for the basic question:

  1. What is the difference?
  2. When do I need to use SystemExit or sys.exit inside a function?

Example

ref = osgeo.ogr.Open(reference) if ref is None:     raise SystemExit('Unable to open %s' % reference) 

or

ref = osgeo.ogr.Open(reference) if ref is None:     print('Unable to open %s' % reference)     sys.exit(-1) 
like image 350
Gianni Spear Avatar asked Dec 21 '12 15:12

Gianni Spear


People also ask

What is the difference between SYS exit and exit in Python?

The functions* quit(), exit(), and sys. exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys. exit() is always available but exit() and quit() are only available if the site module is imported.

Is it good to use Sys exit in Python?

exit([arg]) using Python. Unlike quit() and exit(), sys. exit() is considered good to be used in production code for the sys module is always available.

What does sys exit () do in Python?

exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.

Is Sys exit good practice?

You usually want to use sys. exit either to conditionally end your script somewhere in the middle of it (when it would be complicated to simply change the execution flow) or to return a different exit code.


1 Answers

No practical difference, but there's another difference in your example code - print goes to standard out, but the exception text goes to standard error (which is probably what you want).

like image 103
RichieHindle Avatar answered Sep 22 '22 14:09

RichieHindle