Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sys.exit not working in try [duplicate]

Python 2.7.5 (default, Feb 26 2014, 13:43:17) [GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> try: ...  sys.exit() ... except: ...  print "in except" ... in except >>> try: ...  sys.exit(0) ... except: ...  print "in except" ... in except >>> try: ...  sys.exit(1) ... except: ...  print "in except" ... in except 

Why am not able to trigger sys.exit() in try, any suggestions...!!!

The code posted here has all the version details.

I have tried all possible ways i know to trigger it, but i failed. It gets to 'except' block.

Thanks in advance..

like image 450
onlyvinish Avatar asked Sep 18 '14 06:09

onlyvinish


People also ask

How do you force quit Python?

Ctrl + C on Windows can be used to terminate Python scripts and Ctrl + Z on Unix will suspend (freeze) the execution of Python scripts. If you press CTRL + C while a script is running in the console, the script ends and raises an exception.

Is it good to use Sys exit in Python?

Unlike quit() and exit(), sys. exit() is considered good to be used in production code for the sys module is always available. The optional argument arg can be an integer giving the exit or another type of object. If it is an integer, zero is considered “successful termination”.

What is exit () in Python?

Python's in-built exit() function is defined in site.py and is an alias for quit(). It works only if the site module is imported. Hence, it should not be used in production code, only in the interpreter. It's like a more user-friendly synonym of quit(). Like quit(), exit() also raises SystemExit exception.

Does SYS exit return?

sys. exit returns SystemExit Exception along with the passed argument. Note– If we are passing integer 0 as the argument, it means the termination is successful, and if we pass any other argument, it means that the termination is not successful.


1 Answers

sys.exit() raises an exception, namely SystemExit. That's why you land in the except-block.

See this example:

import sys  try:     sys.exit() except:     print(sys.exc_info()[0]) 

This gives you:

<type 'exceptions.SystemExit'> 

Although I can't imagine that one has any practical reason to do so, you can use this construct:

import sys  try:     sys.exit() # this always raises SystemExit except SystemExit:     print("sys.exit() worked as expected") except:     print("Something went horribly wrong") # some other exception got raised 
like image 85
tamasgal Avatar answered Sep 19 '22 12:09

tamasgal