Reputation: 585
In Python I would like to check if any argument that has been passed to my script equals "-h" (so that I can display a help banner and exit).
Should I loop through sys.argv values or is there a more simple way to achieve this?
Upvotes: 3
Views: 6762
Reputation: 15934
If all you are aiming to do is to search for -h
in the arguments then you can just iterate over the sys.argv
list and see if you find that value.
However it looks like the problem you are actually trying to solve is to create a parser for your command line arguments. If that's the case I think the best approach is to just use the argparse module which is designed to solve exactly this problem and avoid re-inventing the wheel. By default argparse
adds a help option with -h
or --help
. (However that default behaviour can be changed if need be, see the part of the docs that deals with that: https://docs.python.org/3/library/argparse.html#add-help)
Upvotes: 2
Reputation: 336
You can achieve with what lebeef and dlask mentioned. i would prefer to use fileinput and it is more sophcicated. You can import fileinput
import fileinput
if "-h" in fileinput.input():
display_help_text()
Upvotes: 0
Reputation: 61
Just check if the desired string exists in the list:
import sys
if "__main__" == __name__:
if "-h" in sys.argv:
print "This is a help text."
Upvotes: 6