Reputation: 192
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
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
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