hlx
hlx

Reputation: 192

sys.exit() does not terminate my program

I want to exit a Python script if my try succeeds. My code just doesn't exit and continues to execute the rest of the script.

If I run python myscript.py --help, I need the script to exit. If I run python myscript.py I need do execute the except part.

try:
    if sys.argv[1] == '--help' or sys.argv[1] == '-help' or \
            sys.argv[1] == '-h' or sys.argv[1] == '--h':
        print "NAME"
        sys.exit("Usage : python go.py")
except:
    #REST OF THE CODE.

Upvotes: 3

Views: 5693

Answers (3)

aychedee
aychedee

Reputation: 25569

Why would you use a try / except block? Like bereal says, you are catching all exceptions and hiding problems. try /except blocks are for exceptional circumstances. Not alternate code paths.

def main():
    # main code block

if sys.argv[1] == '--help' or sys.argv[1] == '-help' or \
    sys.argv[1] == '-h' or sys.argv[1] == '--h':
    print "Help text"
else:
    main()

Also, as a general rule when using try /except. Just catch the exception that you care about. It's impossible to debug something that cannot even tell you what is wrong.

Upvotes: 5

Brendan Maguire
Brendan Maguire

Reputation: 4541

As a general comment, maybe you should look at using argparse. http://docs.python.org/library/argparse.html#module-argparse Using argparse you don't have to manually inspect the argv array; argparse will do all the work for you.

Upvotes: 1

bereal
bereal

Reputation: 34252

As the docs say, sys.exit in fact does nothing but raising SystemExit and you're intercepting it in the end. You either call sys.exit outside of try-except or catch it explicitly and then re-raise.

Upvotes: 10

Related Questions