0

Python 的 argparse 的常见用法

 1 year ago
source link: https://zhiqiang.org/coding/python-argparse.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1、简单用法

## test.py
import argparse

parser = argparse.ArgumentParser("./test.py 用来做测试的",
    formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=50)

# add_argument your here
# parser.add_argument(...)
# parser.add_argument(...)

options = parser.parse_args()
print(options)

2、添加命令

最简单的例子:

## 不命名参数
# 识别 ./test.py a.xml
# options.xml = "a.xml"
parser.add_argument("xml", help="xml file")

## 命名参数
# 识别 ./test.py -x a.xml 
#      ./test.py --xml a.xml 
#      ./test.py --xml=a.xml
# options.xml = "a.xml"
parser.add_argument("-x", "--xml", help="xml file")

## 指定类型,不指定时默认都是字符串
# 识别 ./test.py -c 5  
# options.count = 5
parser.add_argument("-c", "--count", type=int, help="count")

## true/false 类型
# 识别 ./test.py -v
# options.valid = True
# 识别 ./test.py
# options.valid = False 
parser.add_argument("-v", "--valid", action="store_true", 
                    help="set valid to true")       

## 参数不提供时为None,可强制要求指定
# 识别 ./test.py -x abc 
# options.required = abc, options.unrequired = None
# 识别 ./test.py -y,会出错:必须指定-x。
parser.add_argument("-x", "--required", required=True)
parser.add_argument("-y", "--unrequired")

## 设置默认值
# 识别 ./test.py 
# options.xml = "a.xml"
parser.add_argument("-x", "--xml", default="a.xml") 

然后是数组参数,主要是指定 nargs ,可允许的值是*, +, 整数值和?

  • *表示接受任意多的参数,总是返回数组(包括空数组和长度为 1 的数组)。
  • +类似于*,但如果没有提供参数会报错,即至少要有一个参数。
  • 整数值表示接受指定数量的参数,总是返回数组(即使指定数量为 1 )。
  • ?:表示接受一个或 0 个参数。不返回数组!返回值或者 None。
## nargs=*,返回结果数组(即使只指定一个元素) 
# 识别 ./test.py a.xml b.xml
# options.xml = ["a.xml", "b.xml", ]
parser.add_argument("-x", "--xml", nargs="*", help="xml file")

结合nargs="*"constdefault可以设置一个特别有用的组合:

## 可以不指定参数,指定空参数,以及制定参数 
# 识别 ./test.py 
# options.delete = 0
# 识别 ./test.py -x
# options.delete = 5
# 识别 ./test.py -x 10
# options.delete = 10
parser.add_argument("-d", "--delete", nargs="?", const=5, default=0, type=int)

3、命令分组

这个主要是在显示帮助信息时把命令行参数分组,显得更清晰,比如我喜欢-h--log放到单独的分组。用法也可简单:

group = parser.add_argument_group("LOG和帮助")
group.add_argument("--log", default="info", help="设置LOG级别")
group.add_argument("-h", "--help", action="help", help="查看帮助信息")

4、子命令

git就大量使用了子命令,比如 git pull, git push 就是不同的子命令,子命令可以自己显示自己的帮助信息 git pull --help

使用子命令也很简单,下面创建了一个 pull 的子命令:

parser.add_argument("-p", "--print", action="store_true")

sub_parsers = parser.add_subparsers()
tdb_parser = sub_parsers.add_parser("pull", help="pull to remote")
tdb_parser.set_defaults(which="pull")

tdb_parser.add_argument("remote", help="remote url") 

那么我们会有以下结果:

./test.py -p pull github.com/fool
# options.print = True
# options.which = "pull"
# options.remote = "github.com/fool"

这里比较 trick 的一点是 tdb_parser.set_defaults(which="pull"),需要如此设置,才能让程序通过读取options.which判断进入了哪一个子命令。

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK