argparse

 argparse库是用来给python脚本传入参数的库

一、从最简单的应用开始

求两整数a,b之和

mycode.py:

import argparse
parser = argparse.ArgumentParser()
#创建一个命令行参数解析器实例
parser.add_argument("a",type=int)
#添加一个positional arguments,叫a,读取类型为int(默认是字符串)
parser.add_argument("b",type=int)
#添加一个positional arguments,叫b,读取类型为int(默认是字符串)
args = parser.parse_args()
#解析从命令行输入的参数,并将解析的结果存储到 args 对象中
#parse_args的类型是Namespaces,相当于一个字典,存放着所有positional arguments
sum=args.a+args.b       #从args调出参数a和b,求和
print(sum)

命令行:(别忘了先进入当前目录,用cd命令)

python mycode.py 1 2

输出:3

如果不带参数
就会报错,并且在usage后展示用法模板

>>>python mycode.py
usage: mycode.py [-h] a b
mycode.py: error: the following arguments are required: a, b

注:[-h]表示有一个optional argument叫做-h,这个是它自己带的,也就是help
我们用一下-h,它会教我们怎么打命令

>>>python mycode.py -h
usage: mycode.py [-h] a b

positional arguments:
  a
  b

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

加文字描述:
两种文字描述:
1、整个python文件: description=‘此代码用于求两个整数之和’
2、每个positional argument:help=“第一个整数”
方便用户查看

import argparse
parser = argparse.ArgumentParser(description='此代码用于求两个整数之和')
#这个parse对象相当于一个总容器,存放着全部的信息
parser.add_argument("a", type=int,help="第一个整数")
#添加一个positional arguments,叫a,读取类型为int(默认是字符串)
parser.add_argument("b",type=int,help="第二个整数")
#添加一个positional arguments,叫b,读取类型为int(默认是字符串)
args = parser.parse_args()
#parse_args的类型是Namespaces,相当于一个字典,存放着所有positional arguments
sum=args.a+args.b       #调出参数a和b,求和
print(sum)

效果:

PS C:\Users\fan.19\fan19-hub> python mycode.py -h
usage: mycode.py [-h] a b

此代码用于求两个整数之和

positional arguments:
  a           第一个整数
  b           第二个整数

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

二、add_argument函数参数

接受的值作用举例
name字符串变量的名字‘radius’
nargs数字或’?‘或’*‘或’+’用来说明传入的参数个数(符号意义和正则表达式里的一致)nargs=’?’ nargs=2
typelist, str, tuple, set, dict等设置读取参数的类型type=int
default类型跟type统一设置默认值default=1
choices装选项的list参数值只能从几个选项里面选择choices=[1,2,3,4]
requiredTrue或False这个可选参数是否必须有(只能用于-love这样的可选参数!否则报错)required=True
help字符串说明一下这个参数是干嘛的help=“I don’t know”
action六种内置动作一旦这个有参数,就会触发相应的动作action=‘store_true’

这几个键是最常用的,此表不全请注意
详细讲一下几个不太好懂的:

1.name

函数的第一项就是name

add_argument("b",type=int,help="第二个整数")
2.nargs

用来说明传入的参数的个数,可以是

  • 具体数字:要传进来几个
  • ‘*’:任意个 any
  • ‘?’:一个或者没有 1/0
  • ‘+’:至少一个 ≥1
    后期你调出这个参数的时候,它是一个list的形式储存你传入的东西
    那我们改进一下上面求两个整数和的程序
import argparse
parser = argparse.ArgumentParser(description='此代码用于求两个整数之和')
#这个parse对象相当于一个总容器,存放着全部的信息
parser.add_argument("integers", type=int,nargs=2,help="第一个整数")
#添加俩positional arguments,叫integers,读取类型为int
args = parser.parse_args()
#parse_args的类型是Namespaces,相当于一个字典,存放着所有positional arguments
integers=args.integers       #调出来intergers,它是一个list!!
print("integer的类型是:",type(integers))   
sum=sum(integers)  #list元素求和
print(sum)
3.type

type用来决定,你是以什么样的数据类型把参数读进来的
默认的话是字符串,跟input函数一样!!!!
看这个大乌龙程序:
mycode:

import argparse
parser = argparse.ArgumentParser(description='此代码用于求两个整数之和')
#这个parse对象相当于一个总容器,存放着全部的信息
parser.add_argument("a",help="第一个整数???不是")
#添加一个positional arguments,叫a,读取类型未指定(默认是字符串)
parser.add_argument("b",,help="第二个整数???不是")
#添加一个positional arguments,叫b,读取类型未指定(默认是字符串)
args = parser.parse_args()
#parse_args的类型是Namespaces,相当于一个list,存放着所有positional arguments
sum=args.a+args.b       #调出参数a和b,求和
print(sum)

命令行:

python mycode.py 1 2

输出的是12,而不是我们想要的1+2=3!!!!!!
这波是直接把两个字符连起来了qwq

import argparse

parser = argparse.ArgumentParser(description='命令行中传入一个数字')
parser.add_argument('integers', type=int, nargs='+',help='传入的数字')
args = parser.parse_args()

#对传入的数据进行加总
print(sum(args.integers)
3.action

argparse内置6种动作可以在解析到一个参数时进行触发:

store 保存参数值,可能会先将参数值转换成另一个数据类型。若没有显式指定动作,则默认为该动作。

store_const 保存一个被定义为参数规格一部分的值,而不是一个来自参数解析而来的值。这通常用于实现非布尔值的命令行标记。

store_ture/store_false 保存相应的布尔值。这两个动作被用于实现布尔开关。

append 将值保存到一个列表中。若参数重复出现,则保存多个值。

append_const 将一个定义在参数规格中的值保存到一个列表中。

version 打印关于程序的版本信息,然后退出

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-s', action='store', dest='simple_value',
        help='Store a simple value') 
#指定将输入的值存储在 Namespace 对象中的属性名为simple_value。如果用户在命令行中使用 -s 选项并##提供一个值,这个值将被赋给 simple_value

parser.add_argument('-c', action='store_const', dest='constant_value',
        const='value-to-store',
        help='Store a constant value')
#运行-c选项 constant_value 将被赋值为 value-to-store

parser.add_argument('-t', action='store_true', default=False,
        dest='boolean_switch',
        help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False,
        dest='boolean_switch',
        help='Set a switch to false')

parser.add_argument('-a', action='append', dest='collection',
        default=[],
        help='Add repeated values to a list')

parser.add_argument('-A', action='append_const', dest='const_collection',
        const='value-1-to-append',
        default=[],
        help='Add different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection',
        const='value-2-to-append',
        help='Add different values to list')

parser.add_argument('--version', action='version', version='%(prog)s 1.0')

results = parser.parse_args()
print 'simple_value     =', results.simple_value
print 'constant_value   =', results.constant_value
print 'boolean_switch   =', results.boolean_switch
print 'collection       =', results.collection
print 'const_collection =', results.const_collection
$ python argparse_action.py -h

usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f]
                          [-a COLLECTION] [-A] [-B] [--version]

optional arguments:
  -h, --help       show this help message and exit
  -s SIMPLE_VALUE  Store a simple value
  -c               Store a constant value
  -t               Set a switch to true
  -f               Set a switch to false
  -a COLLECTION    Add repeated values to a list
  -A               Add different values to list
  -B               Add different values to list
  --version        show program's version number and exit

$ python argparse_action.py -s value

simple_value     = value
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = []

$ python argparse_action.py -c

simple_value     = None
constant_value   = value-to-store
boolean_switch   = False
collection       = []
const_collection = []

$ python argparse_action.py -t

simple_value     = None
constant_value   = None
boolean_switch   = True
collection       = []
const_collection = []

$ python argparse_action.py -f

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = []

$ python argparse_action.py -a one -a two -a three

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = ['one', 'two', 'three']
const_collection = []

$ python argparse_action.py -B -A

simple_value     = None
constant_value   = None
boolean_switch   = False
collection       = []
const_collection = ['value-2-to-append', 'value-1-to-append']

$ python argparse_action.py --version

argparse_action.py 1.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值