Reputation: 48986
I came across this Python script:
parser = ap.ArgumentParser()
parser.add_argument("-t", "--trainingSet", help="Path to Training Set", required="True")
args = vars(parser.parse_args())
train_path = args["trainingSet"]
The points I didn't get are:
How do we use those arguments in the command line: "-t", "--trainingSet", help="Path to Training Set", required="True"?
What does args
mean? How was the training path retrieved?
Thanks.
Upvotes: 0
Views: 519
Reputation: 231738
Create a parser
object:
parser = ap.ArgumentParser()
add an argument definition to the parser (it creates an Action
object, though you don't need to worry about that here).
parser.add_argument("-t", "--trainingSet", help="Path to Training Set", required="True")
Tell the parser
to parse the commandline arguments that are available in sys.argv
. This a list of strings created by the commandline shell (bash or dos).
args = parser.parse_args()
args
is a argparse.Namespace
object. It is a simple object class. vars
converts it to a dictionary
argdict = vars(args)
This is ordinary dictionary access
train_path = argdict["trainingSet"]
you can get the same thing from the namespace
train_path = args.trainingSet
I'd recommend looking at args
print args
With this parser
definition, a commandline like
$ python myprog.py -t astring # or
$ python myprog.py --trainingSet anotherstring
will end up setting train_path
to the respective string value. It is up to the rest of your code to use that value.
The help
parameter will show up in the help message, such as when you do
$ python myprog.py -h
The required
parameter means that the parser
will raise an error if you don't provide this argument, e.g.
$ python myprog.py
Upvotes: 1