Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I halt execution in a python script? [duplicate]

Tags:

python

Possible Duplicates:
Programatically stop execution of python script?
Terminating a Python script

I want to print a value, and then halt execution of the script.

Do I just use return?

like image 982
Blankman Avatar asked Jul 31 '10 02:07

Blankman


2 Answers

You can use return inside the main function in you have one, but this isn't guaranteed to quit the script if there is more code after your call to main.

The simplest that nearly always works is sys.exit():

import sys
sys.exit()

Other possibilities:

  • Raise an error which isn't caught.
  • Let the execution point reach the end of the script.
  • If you are in a thread other than the main thread use thread.interrupt_main().
like image 93
Mark Byers Avatar answered Nov 02 '22 03:11

Mark Byers


There's exit function in sys module ( docs ):

import sys
sys.exit( 0 ) # 0 will be passed to OS

You can also

raise SystemExit

or any other exception that won't be caught.

like image 42
cji Avatar answered Nov 02 '22 03:11

cji