11

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?

Community
  • 1
  • 1
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

3 Answers3

21

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
  • 811,555
  • 193
  • 1,581
  • 1,452
  • 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 Jul 31 '10 at 02:36
  • 1
    @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 Jul 31 '10 at 02:39
7

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
  • 6,635
  • 2
  • 20
  • 16
6

sys.exit

NullUserException
  • 83,810
  • 28
  • 209
  • 234
  • 3
    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 Jul 31 '10 at 03:03
  • +1 Read @Mark's comment; a bit lazy to edit my post. – NullUserException Jul 31 '10 at 03:31