lisa1987
lisa1987

Reputation: 585

How to check if any sys.argv argument equals a specific string in Python

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

Answers (4)

shuttle87
shuttle87

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

pythondetective
pythondetective

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

lebeef
lebeef

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

dlask
dlask

Reputation: 8982

import sys

def help_required():
    return "-h" in sys.argv[1:]

Upvotes: 2

Related Questions