1. argparser模块介绍
在Python3.x中,自带的argparse模块能够方便地解析命令行参数,并提供友好的帮助信息。下面我们将详细介绍如何使用argparse模块。
2. 命令行参数类型
2.1 位置参数和可选参数
命令行参数可以分为位置参数和可选参数两种。位置参数是必需的参数,而可选参数则可以不用给出。
2.2 短选项和长选项
可选参数又可以分为短选项和长选项两种。短选项以单个短划线(-)开头,后接一个字母或数字。长选项以双短划线(--)开头,后接一个字符串。
2.3 参数类型
命令行参数还可以分为不同的类型,例如字符串、整数、浮点数等。在解析时argparse会自动将参数转换为指定的类型。
3. 基本用法
下面我们来看一下argparse的基本用法。我们创建一个hello.py的脚本,可以通过命令行参数来指定输出的字符串。如果不指定任何参数,则默认输出Hello, World!
import argparseparser = argparse.ArgumentParser()
parser.add_argument("-n", "--name", type=str,
help="specify the name to greet")
args = parser.parse_args()
name = args.name if args.name else "World"
print("Hello, {}!".format(name))
其中:
我们首先通过argparse.ArgumentParser()创建一个命令行参数解析器。
然后通过parser.add_argument()方法来添加可选参数。
最后通过parser.parse_args()方法来解析命令行参数。
在解析命令行参数后,通过args.name来获取--name参数的值。如果不指定,则用if ... else来设置默认值。
接下来我们来测试一下这个脚本。首先不带参数运行:
python hello.py输出:
Hello, World!然后带上--name参数运行:
python hello.py --name Alice输出:
Hello, Alice!4. 命令行参数解析器的详细用法
4.1 添加参数
除了最简单的用法之外,argparse还提供了丰富的命令行参数解析功能。
首先我们来看add_argument()方法的详细参数:
add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])参数说明:
name or flags:位置参数或可选参数的名字,例如"-n"和"--name"。
action:参数的行为,例如"store"、"store_const"、"store_true"、"store_false"、"append"、"append_const"、"version"等。
nargs:参数的个数,可以是数字(表示固定个数),也可以是"?"、"*"、"+"、argparse.REMAINDER等特殊字符。
const:用于设置"store_const"和"append_const"行为的固定值。
default:默认值。
type:参数的类型,例如int、float、str、bool等。
choices:可选值的列表。
required:设置参数是否必须。
help:帮助信息。
metavar:命令行输入的参数名称。
dest:参数的名称。
下面我们通过几个例子,来看一下这些参数的用法。
4.2 添加位置参数
位置参数从左往右依次添加,不需要指定参数名。例如下面这个例子:
parser = argparse.ArgumentParser()parser.add_argument("count", type=int, help="count the number of files")
args = parser.parse_args()
print("The count of files is:", args.count)
运行:
python filecount.py 10输出:
The count of files is: 104.3 添加可选参数
添加可选参数时,需要指定参数名,可以使用单个短划线或双短划线。
首先是单个短划线的例子:
parser = argparse.ArgumentParser()parser.add_argument("-c", "--count", type=int, default=1,
help="count the number of files")
args = parser.parse_args()
print("The count of files is:", args.count)
运行:
python filecount.py -c 10输出:
The count of files is: 10然后是双短划线的例子:
parser = argparse.ArgumentParser()parser.add_argument("--flag", action='store_true', help="set the flag")
args = parser.parse_args()
if args.flag:
print("The flag is set.")
运行:
python setflag.py --flag输出:
The flag is set.4.4 添加choices参数
choices参数用于设置可选值的列表。
parser = argparse.ArgumentParser()parser.add_argument("--level", choices=['low', 'medium', 'high'], help="set the level")
args = parser.parse_args()
print("The level is:", args.level)
运行:
python setlevel.py --level high输出:
The level is: high4.5 添加required参数
required参数用于设置参数是否必须。
parser = argparse.ArgumentParser()parser.add_argument("filename", help="specify the input filename")
parser.add_argument("--output", required=True, help="specify the output filename")
args = parser.parse_args()
print("The input filename is:", args.filename)
print("The output filename is:", args.output)
运行:
python fileconv.py input.txt --output output.txt输出:
The input filename is: input.txtThe output filename is: output.txt
如果不指定--output,会提示错误:
python fileconv.py input.txt输出:
usage: fileconv.py [-h] --output OUTPUT filenamefileconv.py: error: the following arguments are required: --output
4.6 添加metavar参数
metavar参数用于命令行输入的参数名称。
parser = argparse.ArgumentParser()parser.add_argument("--input", metavar="FILE", help="specify the input file")
parser.add_argument("--output", metavar="FILE", help="specify the output file")
args = parser.parse_args()
print("The input file is:", args.input)
print("The output file is:", args.output)
运行:
python convert.py --input=input.txt --output=output.txt输出:
The input file is: input.txtThe output file is: output.txt
其中的--input和--output就是metavar设置的名称。
5. 其他用法
5.1 添加子命令
argparse还支持添加子命令的功能,例如Git命令就是通过子命令实现的,例如git commit和git log。
下面是一个添加子命令的例子:
parser = argparse.ArgumentParser()subparsers = parser.add_subparsers(dest="subcommand")
parser_a = subparsers.add_parser("a")
parser_a.add_argument("count", type=int, help="count the number of files")
parser_b = subparsers.add_parser("b")
parser_b.add_argument("--file", help="specify the input file")
args = parser.parse_args()
if args.subcommand == "a":
print("The count of files is:", args.count)
elif args.subcommand == "b":
print("The input file is:", args.file)
运行:
python subcmd.py a 10输出:
The count of files is: 10再运行:
python subcmd.py b --file input.txt输出:
The input file is: input.txt其中add_subparsers()方法用于添加子命令,dest参数用于存储子命令的名称。然后每个子命令需要分别添加自己的参数。
5.2 自定义帮助信息
argparse会自动生成帮助信息,但是如果需要更详细的说明,可以通过description和epilog参数来添加描述信息和结尾信息。
parser = argparse.ArgumentParser(description="Command line tool to count files", epilog="Enjoy counting!")parser.add_argument("count", type=int, help="count the number of files")
args = parser.parse_args()
print("The count of files is:", args.count)
运行:
python countfiles.py --help输出:
usage: countfiles.py [-h] countCommand line tool to count files
positional arguments:
count count the number of files
optional arguments:
-h, --help show this help message and exit
Enjoy counting!
其中description参数用于添加描述信息,epilog参数用于添加结尾信息。
6. 总结
在Python中,通过argparse模块可以方便地解析命令行参数,并提供友好的帮助信息。在使用argparse时,需要注意不同类型的参数以及各种参数的用法,例如choices、required、metavar等。同时也可以通过add_subparsers()来添加子命令。



