laitimes

[Programming Basics] Python command-line parsing library argparse learning notes

author:Pemba duck

The Python argparse tutorial shows how to parse command-line arguments in Python using the argparse module.

Table of Contents of Articles

  • 1 Instructions for use
  • 1.1 Python argparse optional parameters
  • 1.2 Required parameters for Python argparse
  • 1.3 Python argparse positional parameters
  • 1.4 Python argparse dest
  • 1.5 Python argparse type
  • 1.6 Python argparse default
  • 1.7 Python argparse metavar
  • 1.8 Python argparse append action
  • 1.9 Python argparse choices
  • 2 See also

1 Instructions for use

The argparse module makes it easy to write a user-friendly command-line interface. It parses the defined parameter sys.argv from it. The module also automatically generates help and usage messages and issues errors when the user provides invalid parameters for the program. Use ArgumentParser to create an analyzer and use add_argument() to add new parameter variables. Parameters can be optional, required, or positional. The common parameter settings in add_argument() are as follows:

  • name or flags, enter the name or list of parameters, e.g. foo or -f, --foo;
  • action, the action when the command line encounters a parameter, the default value is store;
  • store_const, the value is assigned as const;
  • append, which stores the entered values as a list, i.e. multiple values are saved if the parameters are repeated;
  • append_const, save a value defined in the parameter specification to a list;
  • count, which stores the number of encounters;
  • nargs, the number of command line arguments that should be read;
  • const, action and nargs;
  • defaul, the default value of the parameter;
  • type, the type to which the command line argument should be converted;
  • choices, a collection of available parameters;
  • required, which parameter is a required input parameter.
  • help;
  • metavar, an alternative name for the input parameter
  • dest, which is added to the property name on the object returned by parse_args();

1.1 Python argparse optional parameters

The following example creates a test1.py that is a simple parameter parser. add_argument add the -o and –out parameters, both of which have the same effect. The former is a parameter, and the abbreviation is only one letter, and the latter is a full parameter. If the input parameter is input, the output is some output. There is also a add_argument and a fixed parameter action='store_true', which indicates the action when the command line encounters a parameter, store sets the parameter to const, and the default value is store. Parameters are parsed parse_args (). The parsed parameter exists as an object property.

#!/usr/bin/env python

import argparse


parser = argparse.ArgumentParser()

# action 命令行遇到参数时的动作
# -o为短参数,--output长参数
parser.add_argument('-o', '--output', action='store_true', help="shows output")

# parse_args()解析参数
args = parser.parse_args()

# 如果存在output
if args.output:
   print("This is some output")
else:
   print("This is not some output")           
# 执行test1.py文件
# 输入--output参数
!python test1.py --output
print('-'*50)
# 输入-o参数
!python test1.py -o
print('-'*50)
# 什么都不输入
!python test1.py
print('-'*50)
# 输入--help参数
!python test1.py --help
!python test1.py -h           
This is some output
--------------------------------------------------
This is some output
--------------------------------------------------
This is not some output
--------------------------------------------------
usage: test1.py [-h] [-o]

optional arguments:
  -h, --help    show this help message and exit
  -o, --output  shows output
usage: test1.py [-h] [-o]

optional arguments:
  -h, --help    show this help message and exit
  -o, --output  shows output           

1.2 Required parameters for Python argparse

The following example creates a test2.py, .add_argument() is set to required = True, which means that the parameter is required, and the name option must be specified in this example. Otherwise, it fails.

#!/usr/bin/env python

import argparse

# 创建解析器
parser = argparse.ArgumentParser()
# 设置--name为必须参数  
parser.add_argument('--name', required=True)
# 解析参数
args = parser.parse_args()

print('Hello {}'.format(args.name))           
# 执行test2.py文件
# 不输入参数
!python test2.py
print('-'*50)
# 输入参数
!python test2.py --name hello           
usage: test2.py [-h] --name NAME
test2.py: error: the following arguments are required: --name
--------------------------------------------------
Hello hello           

1.3 Python argparse positional parameters

The following example creates test3.py the positional parameter does not need a prefix symbol and directly enters the parameter value.

#!/usr/bin/env python

import argparse

# positional args

parser = argparse.ArgumentParser()
   
parser.add_argument('name')
parser.add_argument('age')

args = parser.parse_args()

print('{} is {} years old'.format(args.name,args.age))           
!python test3.py -h
print('-'*50)
!python test3.py --name
print('-'*50)
# 输入参数
!python test3.py "jack" 12           
usage: test3.py [-h] name age

positional arguments:
  name
  age

optional arguments:
  -h, --help  show this help message and exit
--------------------------------------------------
usage: test3.py [-h] name age
test3.py: error: the following arguments are required: name, age
--------------------------------------------------
jack is 12 years old           

1.4 Python argparse dest

The dist option specifies a name for the add_argument() parameter. If it is not given, it is inferred from the options. The following example creates a test4.py with the -n parameter name set to now.

#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser()
   
parser.add_argument('-n', dest='now', action='store_true', help="shows now")

args = parser.parse_args()

# -n代表now
if args.now:
   print(args.now)           
# 运行文件
!python test4.py -n           
True           

1.5 Python argparse type

Use the type parameter to determine the parameter type. The following example creates a test5.py. The program displays n random integers from -100 to 100.

#!/usr/bin/env python

import argparse
import random


parser = argparse.ArgumentParser()

# type确定参数的类型值
parser.add_argument('-n', type=int, required=True, 
    help="define the number of random integers")
args = parser.parse_args()

n = args.n

# 输出随机数
for i in range(n):
    print(random.randint(-100, 100))           
# 运行程序
!python test5.py -n 5           
34
-81
76
-62
-66           

1.6 Python argparse default

🔥 If the value is not specified, this option specifies a default value. The following example creates a test6.py. The example calculates an exponent and does not require an exponential value; If not given, the default value is 2. If there are no required parameters for the input parameters, you can directly run the code to output the value. If you want to change the value in the code, you can copy the parameter directly, such as arg.b=2.

#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser()
# required设置强制性参数,设置输入参数
parser.add_argument('-b', type=int, required=True, help="defines the base value")
# default设置默认参数,设置指数值
parser.add_argument('-e', type=int, default=2, help="defines the exponent value")
args = parser.parse_args()

val = 1

base = args.b
exp = args.e

for i in range(exp):
    val *= base

print(val)           
# 使用 默认参数
!python test6.py -b 2
print('-'*50)
# 给定默认参数
!python test6.py -b 2 -e 3           
4
--------------------------------------------------
8           

1.7 Python argparse metavar

The metavar option names the false expected value and provides a helpful output. The following example creates a test7.py. In this example, the expected value is set to value. The default name is v.

#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser()
   
parser.add_argument('-v', type=int, required=True, metavar='value', 
    help="computes cube for the given value")
args = parser.parse_args()

print(args)

val = args.v

print(val * val * val)           
!python test7.py -h           
usage: test7.py [-h] -v value

optional arguments:
  -h, --help  show this help message and exit
  -v value    computes cube for the given value           

1.8 Python argparse append action

The append action allows for grouping duplicate options. The following example creates a test8.py.

#!/usr/bin/env python

import argparse

# append action allows to group repeating
# options

parser = argparse.ArgumentParser()
   
parser.add_argument('-n', '--name', dest='names', action='append', 
    help="provides names to greet")

args = parser.parse_args()

names = args.names

# 分组输出
for name in names:
    print('Hello {}!'.format(name))           
!python test8.py -n Jack -n Rosy --name Jane           
Hello Jack!
Hello Rosy!
Hello Jane!           

1.9 Python argparse choices

The choices option restricts the parameters to a given list. In the example test9.py, the now option can accept the following values: 1,2,3.

#!/usr/bin/env python

import argparse
import datetime
import time

parser = argparse.ArgumentParser()

parser.add_argument('--now', dest='format', type=int, choices=[1, 2, 3],help="shows num in given format")

args = parser.parse_args()
fmt = args.format

print(fmt)           
# 输入在可选范围内值
!python test9.py --now 1
print('-'*50)
# 输入不在可选范围内值
!python test9.py --now 4
print('-'*50)
# 不输入
!python test9.py           
1
--------------------------------------------------
usage: test9.py [-h] [--now {1,2,3}]
test9.py: error: argument --now: invalid choice: 4 (choose from 1, 2, 3)
--------------------------------------------------
None           

2 See also

  • ​Python argparse tutorial​​
  • argparse module - add_argument method
  • How to use add_argument().

Read on