1/23/2019

python "argparse" simple usage


If you use "argparse" lib, you can get the argument parameters very easily in python.
Let's look below code.

test1.py
import argparse

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
#param add
ap.add_argument("-z", "--zip", type=int, required=True, help="input zip code")
#param add
ap.add_argument("-n", "--name", type=str, required=True, help="input your name")

#get param
args = ap.parse_args()
print(args.zip)
print(args.name)
print('---------')

#get param
args = vars(ap.parse_args())
print(args["zip"])
print(args["name"])
..

The code accepts 2 arguments those are 'zip' and 'name'
So how to input argument?

See the several example

>python test1.py -z 1234 -n kjh
1234
kjh
---------
1234
kjh

>python test1.py
usage: test1.py [-h] -z ZIP -n NAME
test1.py: error: the following arguments are required: -z/--zip, -n/--name


>python test1.py -h
usage: test1.py [-h] -z ZIP -n NAME
optional arguments:
  -h, --help            show this help message and exit
  -z ZIP, --zip ZIP     input zip code
  -n NAME, --name NAME  input your name

you can send argument param
-z or --zip for zip code
-n or --name for name string


Thank you.

reference : https://docs.python.org/3/library/argparse.html