1

In the main script, I want to stop it under some condition. I tried return but it is wrong since it is outside the function. I tried exit, but it does not stop. See the following:

print 'step 1'
exit
print 'step 2'

what should I do ? the version I used is IDLE 2.7.5+

tqjustc
  • 3,624
  • 6
  • 27
  • 42
  • 2
    Actually you shouldn’t have code outside functions. The established convention is that the only code outside functions (except for declarations) should be a call to a `main` function: [What does `if __name__ == "__main__":` do?](http://stackoverflow.com/q/419163) – Konrad Rudolph Mar 05 '14 at 22:02

3 Answers3

7

use exit()

from sys import exit
print 'step 1'
exit()
print 'step 2'
chepner
  • 497,756
  • 71
  • 530
  • 681
Ruben Bermudez
  • 2,293
  • 14
  • 22
2

If you're not in a function, use sys.exit()

Note that this will exit python entirely, even if called from a module that's inside a larger program.

It will usually be better organization to return from a function, and keep as much code inside functions as possible.

mhlester
  • 22,781
  • 10
  • 52
  • 75
1

Another way to exit a Python script is to simply raise the SystemExit exception with raise:

print 'step 1'
raise SystemExit
print 'step 2'

This solution does exactly what sys.exit does, except that you do not need to import sys first.


Also, your specific problem was caused by the fact that you were not actually calling the exit function:

print 'step 1'
exit() # Add () after exit to call the function
print 'step 2'

However, you should not use this solution because it is considered a bad practice. Instead, you should use sys.exit or raise as shown above.