Basic usage of python-21-argparse

argparse is a command line parameter parsing package that comes with python, which can be used to easily read command line parameters.
File tt.py

import argparse
parser = argparse.ArgumentParser(description="Demo of argparse")
parser.add_argument('-n','--name', default='zhang')
parser.add_argument('-y','--year', default='20')
args = parser.parse_args()
print(args)
name = args.name
year = args.year
print('Hello {}  {}'.format(name,year))

Output display

Namespace(name='zhang', year='20')
Hello zhang  20

(1) The ArgumentParser class generates a parser object, in which the description describes what the parameter parser does. When the help information is displayed on the command line, you will see the description description information.
(2) Add parameters through the object's add_argument function. Here we have added two parameters name and year, where'-n' and'–name' indicate the same parameter, and the default parameter indicates that if no parameter is provided when running the command, the program will use this value as the parameter value.
(3) Use the parse_args of the object to obtain the parsed parameters.
(4)Command line input

CMD>python tt.py -n 'liu' --year '30'
Namespace(name="'liu'", year="'30'")
Hello 'liu'  '30'

(4) View help information

CMD>python tt.py -h
usage: tt.py [-h] [-n NAME] [-y YEAR]

Demo of argparse

optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME
  -y YEAR, --year YEAR

Guess you like

Origin blog.csdn.net/qq_20466211/article/details/113694772