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?

5
  • There are different ways to terminate Python scripts. Can you post some code to give some context? Commented Jul 31, 2010 at 2:44
  • 3
    What the heck--how do you have 5.7K rep and ask this question? Commented Jul 31, 2010 at 3:02
  • 1
    Another duplicate: stackoverflow.com/questions/179369/… Commented Jul 31, 2010 at 3:07
  • @John He has 726 questions and 4 answers -- you don't need to answer questions to amass rep Commented Jul 31, 2010 at 3:25
  • @Mark Nicely done; voted to close all of them except 73663 Commented Jul 31, 2010 at 3:27

3 Answers 3

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().
Sign up to request clarification or add additional context in comments.

2 Comments

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: 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.
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.

Comments

6

sys.exit

2 Comments

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.
+1 Read @Mark's comment; a bit lazy to edit my post.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.