tqjustc
tqjustc

Reputation: 3814

how to stop a python script before it goes to end

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+

Upvotes: 1

Views: 1092

Answers (3)

user2555451
user2555451

Reputation:

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.

Upvotes: 1

mhlester
mhlester

Reputation: 23221

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.

Upvotes: 2

Ruben Bermudez
Ruben Bermudez

Reputation: 2323

use exit()

from sys import exit
print 'step 1'
exit()
print 'step 2'

Upvotes: 7

Related Questions