argparse模块_argparse 命令行选项、参数和子命令解析器

argparse是Python标准库中推荐的命令行解释器,在一个鲁棒的程序中,对程序中参数的修改肯定不会去代码中修改,会通过argparse的方法或者log文件的方法,所以本文就argparse的简单用法进行学习记录。

a878d184f673796710ebd4b174482628.png

我们从一个简单的例子看起,整个argparse的使用主要有三部分组成

import 

一、位置参数

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')

parse.add_argument('echo',help='this option where return what you input')

opt = parser.parse_args() 
print(opt.echo)

0ccfccf5f6674a78125a3ccbb150bbd1.png
  • help参数用来描述获取该参数的帮助,使用-h或者--help命令可以查看帮助
(venv) D:Pycharmcifar10_classified>python opt.py --help
usage: This script is for argparse learning [-h] echo

positional arguments:
  echo        this option where return what you input

optional arguments:
  -h, --help  show this help message and exit
————————————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py -h
usage: This script is for argparse learning [-h] echo

positional arguments:
  echo        this option where return what you input

optional arguments:
  -h, --help  show this help message and exit
  • type用来指定输入该参数的类型
parse.add_argument('echo',help='this option where return what you input',type=int)


————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py hello
usage: This script is for argparse learning [-h] echo
This script is for argparse learning: error: argument echo: invalid int value: 'hello'
————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py 666
666

二、可选参数

1、指定参数

使用--option来指定可选参数,参数类型可以由type指定,但是必须有一个参数

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')

parse.add_argument('--input',help='this will return what you input',type = int)

arg = parse.parse_args()

print(arg.input)

例子如下

(venv) D:Pycharmcifar10_classified>python opt.py
None
————————————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py --input
usage: This script is for argparse learning [-h] [--input INPUT]
This script is for argparse learning: error: argument --input: expected one argument
————————————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py --input hello
usage: This script is for argparse learning [-h] [--input INPUT]
This script is for argparse learning: error: argument --input: invalid int value: 'hello'
————————————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py --input 666
666

2、标值参数

action = 'store_true'/'store_false'

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')

parse.add_argument('--flag',help='this is test for flag',action='store_true')

arg = parse.parse_args()

print(arg.flag)

运行程序结果如下

(venv) D:Pycharmcifar10_classified>python opt.py  --flag
True
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py
False

将action='store_true'改成action='store_false'结果恰好相反

(venv) D:Pycharmcifar10_classified>python opt.py  --flag
False
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py
True

当你为其指定一个值的时候,也会报错,说明这个标志只有存在和不存在的区别,不可以对其赋值

(venv) D:Pycharmcifar10_classified>python opt.py  --flag 1
usage: This script is for argparse learning [-h] [--flag]
This script is for argparse learning: error: unrecognized arguments: 1

也可以使用'store_const’来指定一个const参数

parse.add_argument('--store_con',action='store_const',const=12)
arg = parse.parse_args()
print(arg.store_con)

运行结果如下:

(venv) D:Pycharmcifar10_classified>python opt.py --store_con
12
————————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py --store_con 1
usage: This script is for argparse learning [-h] [--store_con]
This script is for argparse learning: error: unrecognized arguments: 1

3、限制参数的选项

使用choices来限制参数的选项

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')
parse.add_argument('--choice',choices=[1,2,3],type=int,help='the choice only can be used in [1,2,3]')

arg = parse.parse_args()
print(arg.choice)

程序运行结果如下

(venv) D:Pycharmcifar10_classified>python opt.py  --choice 1
1
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  --choice 2
2
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  --choice 3
3
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  --choice 4
usage: This script is for argparse learning [-h] [--choice {1,2,3}]
This script is for argparse learning: error: argument --choice: invalid choice: 4 (choose from 1, 2, 3)

4、使用count动作来计数某一可选参数出现次数

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')

parse.add_argument('--num','-n',action='count',help='this option is used for count')
arg = parse.parse_args()
# print(arg.choice)
if arg.num == None:
    print('count is 0')
if arg.num == 1:
    print('count is 1')
if arg.num == 2:
    print('count is 2')

程序运行结果如下:

(venv) D:Pycharmcifar10_classified>python opt.py  -n
count is 1
————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  -n
count is 1
————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  -nn
count is 2
————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  -n -n
count is 2
————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  -n --num
count is 2
————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py
count is 0
  • 如果不添加-n标值,action='count'动作值为None

5、使用default指定默认参数

可以在添加参数的时候使用default来指定默认的参数

三、结合位置参数和可选参数

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')

parse.add_argument("square", type=int,help="display a square of a given number")

parse.add_argument("-v", "--visible", action="store_true",help="increase output verbosity")

arg = parse.parse_args()

answer = arg.square**2
if arg.visible:
    print("the square of {} equals {}".format(arg.square, answer))
else:
    print(answer)

运行程序结果如下

(venv) D:Pycharmcifar10_classified>python opt.py  -v 2
the square of 2 equals 4
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  -v
usage: This script is for argparse learning [-h] [-v] square
This script is for argparse learning: error: the following arguments are required: square
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  2
4
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  2 -v
the square of 2 equals 4
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py  2 --visible
the square of 2 equals 4

细心的小伙伴可以发现在这个程序中命令顺序是无关紧要的,但是对于有多个位置参数的情况下,位置参数的顺序就很重要

import argparse

parse = argparse.ArgumentParser('This script is for argparse learning')

parse.add_argument("one")
parse.add_argument("two")

arg = parse.parse_args()
print(arg.one)
print(arg.two)

运行结果

(venv) D:Pycharmcifar10_classified>python opt.py  2,3
usage: This script is for argparse learning [-h] one two
This script is for argparse learning: error: the following arguments are required: two
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py
usage: This script is for argparse learning [-h] one two
This script is for argparse learning: error: the following arguments are required: one, two
——————————————————————————————————
(venv) D:Pycharmcifar10_classified>python opt.py 1 2
1
2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
命令行参数是在命令行中输入的选项参数,用于控制程序的行为。在使用命令行运行Python脚本时,可以通过命令行参数来传递额外的信息给程序。 例如,下面是一个运行 Python 脚本时使用了命令行参数的示例命令: ``` python script.py --model_name TextCNN --dataset dataset1 --classes_level2 29 --classes_level3 0 --classify_type level2_multi --fine_tune ``` 在上面的命令中,`--model_name`、`--dataset`、`--classes_level2`等是命令行选项,用于指定参数的名称。而`TextCNN`、`dataset1`、`29`、`0`、`level2_multi`等是相应选项的值。 使用 `argparse.ArgumentParser` 类可以定义这些命令行选项参数。可以通过调用 `add_argument()` 方法来添加选项参数的定义。例如, `parser.add_argument('--model_name', type=str, default=model_name, help='[TextCNN、TextRCNN、TextRNN、TextRNN_Att、DPCNN、FastText]')` 定义了一个名为 `--model_name` 的选项,它表示模型名称,并且它的类型为字符串 (`type=str`),默认值为 `model_name` 变量的值,同时还提供了帮助信息。 使用 `argparse.ArgumentParser()` 创建的解析器对象可以解析命令行参数,并将其转换为程序中的变量。通过调用 `parse_args()` 方法,可以解析并返回一个命名空间对象,其中包含了命令行参数的值。可以通过访问这个对象的属性来获取相应参数的值。 总之,`argparse.ArgumentParser` 类用于定义和解析命令行参数,而命令行参数则是在命令行中输入的选项参数,用于控制程序的行为。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值