tags:

views:

100

answers:

3

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?

+6  A: 

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().
Mark Byers
You can only use `return` in a function, and just letting the execution point reach the end of the script isn't really "halting execution"
Michael Mrozek
@Michael Mrozek: I disagree - reaching the end of the script is a way to halt execution. If he just wants to print "Hello world" then end the script then that's actually the most pythonic way to halt execution.
Mark Byers
+4  A: 

sys.exit

NullUserException
It might be a good idea to mention that you need to import sys. It also might be a good idea to mention that you need parentheses to actually call the function. Without the parentheses it will do nothing.
Mark Byers
+1 Read @Mark's comment; a bit lazy to edit my post.
NullUserException
+4  A: 

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.

cji