简体   繁体   中英

argparse in Python

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.

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, eg

$ python myprog.py    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM