前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python学习之argparse模块

python学习之argparse模块

作者头像
py3study
发布2020-01-09 09:54:27
1.6K0
发布2020-01-09 09:54:27
举报
文章被收录于专栏:python3

一、简介:

argparse是python用于解析命令行参数和选项的标准模块,用于代替已经过时的optparse模块。

argparse模块的作用是用于解析命令行参数,

例如 python parseTest.py input.txt output.txt --user=name --port=8080。

二、使用步骤:

1:import argparse

2:parser = argparse.ArgumentParser()

3:parser.add_argument()

4:parser.parse_args()

解释:首先导入该模块;然后创建一个解析对象;然后向该对象中添加你要关注的命令行参数和选项,

每一个add_argument方法对应一个你要关注的参数或选项;最后调用parse_args()方法进行解析

解析成功之后即可使用,下面简单说明一下步骤2和3。

三、方法ArgumentParser(prog=None, usage=None,description=None, epilog=None, parents=[],formatter_class=argparse.HelpFormatter, prefix_chars='-',fromfile_prefix_chars=None, argument_default=None,conflict_handler='error', add_help=True)

这些参数都有默认值,当调用parser.print_help()或者运行程序时由于参数不正确(此时python解释器其实也是调用了pring_help()方法)时,会打印这些描述信息,一般只需要传递description参数

如上。

四、方法add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

其中:

name or flags:命令行参数名或者选项,如上面的address或者-p,--port.

其中命令行参数如果没给定,且没有设置defualt,则出错。但是如果是选项的话,则设置为None

nargs:命令行参数的个数,

一般使用通配符表示,其中,'?'表示只用一个,'*'表示0到多个,'+'表示至少一个

default:默认值

type:参数的类型,默认是字符串string类型,还有float、int等类型

help:和ArgumentParser方法中的参数作用相似,出现的场合也一致

代码语言:javascript
复制
最常用的地方就是这些,其他的可以参考官方文档。下面给出一个例子,基本包括了常见的情形:

import argparse
def parse_args():
    description = usage: %prog [options] poetry-file
This is the Slow Poetry Server, blocking edition.
Run it like this:
  python slowpoetry.py <path-to-poetry-file>
If you are in the base directory of the twisted-intro package,
you could run it like this:
  python blocking-server/slowpoetry.py poetry/ecstasy.txt
to serve up John Donne's Ecstasy, which I know you want to do.
    parser = argparse.ArgumentParser(description = description)
    help = The addresses to connect.
 parser.add_argument('addresses',nargs = '*',help = help)
    help = The filename to operate on.Default is poetry/ecstasy.txt
 parser.add_argument('filename',help=help)
    help = The port to listen on. Default to a random available port.
 parser.add_argument('-p',--port', type=int, help=help)
    help = The interface to listen on. Default is localhost.
 parser.add_argument('--iface', help=help, default='localhost')
    help = The number of seconds between sending bytes.
 parser.add_argument('--delay', type=float, help=help, default=.7)
    help = The number of bytes to send at a time.
 parser.add_argument('--bytes', type=int, help=help, default=10)
 args = parser.parse_args();
    return args
if __name__ == '__main__':
    args = parse_args()
    for address in args.addresses:
        print 'The address is : %s .' % address
    print 'The filename is : %s .' % args.filename
    print 'The port is : %d.' % args.port
    print 'The interface is : %s.' % args.iface
    print 'The number of seconds between sending bytes : %f'% args.delay
    print 'The number of bytes to send at a time : %d.' % args.bytes</path-to-poetry-file>

运行该脚本:python test.py --port 10000 --delay 1.2 127.0.0.1 172.16.55.67 poetry/ecstasy.txt

输出为:

The address is : 127.0.0.1 .

The address is : 172.16.55.67 .

The filename is : poetry/ecstasy.txt .

The port is : 10000.

The interface is : localhost.

The number of seconds between sending bytes : 1.200000

The number of bytes to send at a time : 10.

使用方法:

    1、导入argparse模块   import argparse

    2、创建argparse对象   parser = argparse.ArgumentParser()

    3、添加命令行相关参数、选项  parser.add_argument("...")

    4、解析    parser.parse_args()

例一:(删除指定的zabbix screen)

代码语言:javascript
复制
#!/usr/bin/env python2.7

#coding=utf-8
import sys
import argparse
import zabbixAuth
import zabbixScreen
if __name__ == "__main__":
    #if len(sys.argv) < 2 :
    #    print "usage:",sys.argv[0],"screenName"
    #    sys.exit(1)
    #if sys.argv[1] == "-h" or sys.argv[1] == "--help":
    #    print "usage:",sys.argv[0],"screenName"
    #    sys.exit()
    #以下三行的功能等效于以上的if 语句
 parser = argparse.ArgumentParser()  #创建argparse对象
 parser.add_argument("screenName",help="Specifies the screen name of the is will be deleted")
 parser.parse_args()
    userAuth=zabbixAuth.zabbix_auth()
    token=userAuth.user_login()
    screenObj=zabbixScreen.zabbix_screen()
    screenidList=screenObj.screen_get(token,sys.argv[1])
    if screenidList != None:
        print "screenID:",screenObj.screen_delete(token,screenidList[0]),"delete success"
    else:
        print "The screen:",sys.argv[1],"does not exists"

例二:(创建自定义的zabbix screen)

代码语言:javascript
复制
#!/usr/bin/env python2.7
#coding=utf-8
import sys
import argparse
import zabbixAuth
import zabbixScreen
if __name__ == "__main__":
    #if len(sys.argv) < 4 :
    #    print "usage:",sys.argv[0],"screenName rows columns"
    #    sys.exit(1)
    #if sys.argv[1] == "-h" or sys.argv[1] == "--help":
    #    print "usage:",sys.argv[0],"screenName rows columns"
    #    sys.exit()
    #if sys.argv[2].isdigit()==False or sys.argv[3].isdigit()==False:
    #    print "Note: rows and columns is number"
    #    sys.exit()
    #以上注释的if 语句等效于以下5行
    parser = argparse.ArgumentParser()
    parser.add_argument("screenName",help="Given a string to set the screen name")
    parser.add_argument("rows",help="Given a number to set the lines",type=int)
    parser.add_argument("columns",help="Given a number to set the columns",type=int)
 parser.parse_args()
    if int(sys.argv[3])>3 :
        print "Note: columns must be less than 3"
        sys.exit()
    userAuth=zabbixAuth.zabbix_auth()
    token=userAuth.user_login()
    screenObj=zabbixScreen.zabbix_screen()
    screenidList=screenObj.screen_get(token,sys.argv[1])
    if screenidList != None:
        print "screen already exists"
else:
        print "screnn",sys.argv[1],"create success, screenid is",screenObj.screen_create(token,sys.argv[2],sys.argv[3],sys.argv[1])
import  argparse

__version__ = '1.1.1'
parser = argparse.ArgumentParser(description='hahahaaaa')
parser.add_argument('-V', '--version', action='version', version='%(prog)s '+__version__)
parser.add_argument('--name','-n',metavar='namemma',dest='name',type=str,help='your name',nargs=1)
parser.add_argument('-i',metavar='III',action='store_const',dest='iiii',const='ii',help="dfafsdf")
parser.add_argument("-z", choices=['a', 'b', 'd'],required=False)
parser.add_argument('foo')
args = parser.parse_args()
print(type(args))
print(args.name,args.iiii,args.foo)
ArgumentParser参数的简单说明
 epilog - 命令行帮助的结尾文字 
 prog - (default: sys.argv[0])程序的名字,一般不需要修改,另外,如果你需要在help中使用到程序的名字,可以使用%(prog)s
 prefix_chars - 命令的前缀,默认是-,例如-f/--file。有些程序可能希望支持/f这样的选项,可以使用prefix_chars="/"
 fromfile_prefix_chars - (default: None)如果你希望命令行参数可以从文件中读取,就可能用到。例如,如果fromfile_prefix_chars='@',命令行参数中有一个为"@args.txt",args.txt的内容会作为命令行参数
 add_help - 是否增加-h/-help选项(default:True),一般help信息都是必须的,所以不用设置啦。
add_argument:读入命令行参数,该调用有多个参数
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)
不带'--'的参数
    调用脚本时必须输入值
    参数输入的顺序与程序中定义的顺序一致
'-'的参数
    可不输入    add_argument("-a")
    类似有'--'的shortname,但程序中的变量名为定义的参数名
'--'参数
    参数别名: 只能是1个字符,区分大小写
    add_argument("-shortname","--name", help="params means"),但代码中不能使用shortname
 dest: 参数在程序中对应的变量名称 add_argument("a",dest='code_name')
    default: 参数默认值
    help: 参数作用解释  add_argument("a", help="params means")
    type : 默认string  add_argument("c", type=int)
    metavar: 参数的名字,在显示 帮助信息时才用到.
    action:
        store:默认action模式,存储值到指定变量。
        store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。
        store_true / store_false:布尔开关。可以2个参数对应一个变量。
        append:存储值到列表,该参数可以重复使用。
        append_const:存储值到列表,存储值在参数的const部分指定。
        count: 统计参数简写输入的个数  add_argument("-c", "--gc", action="count")
        version 输出版本信息然后退出。
    const:配合action="store_const|append_const"使用,默认值
    choices:输入值的范围 add_argument("--gb", choices=['A', 'B', 'C', 0])
 required:通常-f这样的选项是可选的,但是如果required=True那么就是必须的了
    nsrgs 用来指定参数的个数,可以是1,2,3....也可以是?或*或+
        ? 零个或一个
        * 零个或多个
        + 一个或多个
创建子parse,每个子parse对应自己的输入参数
import argparse
# sub-command functions
def subcmd_list(args):
   print "list"
def subcmd_create(args):
   print "create"
def subcmd_delete(args):
   print "delete"
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='commands')
# A list command
list_parser = subparsers.add_parser('list', help='Listcontents')
list_parser.add_argument('dirname', action='store',    help='Directory tolist')
list_parse.set_defaults(func=subcmd_list)
# A create command
create_parser = subparsers.add_parser('create', help='Create a directory')
create_parser.add_argument('dirname',action='store',help='New directoryto create')
create_parser.add_argument('--read-only',default=False, action='store_true',help='Setpermissions to prevent writing to the directory')
create_parser .set_defaults(func=subcmd_create)
# A delete command
delete_parser = subparsers.add_parser('delete',help='Remove a directory')
delete_parser.add_argument( 'dirname', action='store',help='The directory to remove')
delete_parser.add_argument('--recursive', '-r',default=False, action='store_true',help='Remove thecontents of the directory, too')
delete_parser .set_defaults(func=subcmd_delete)
args = parser.parse_args()
# call subcmd
args.fun(args)
使用帮助
# python args_subparse.py -h
usage: args_subparse.py [-h] {create,list,delete} ...
positional arguments:
  {create,list,delete}  commands
    list                Listcontents
    create              Create a directory
    delete              Remove a directory
optional arguments:
  -h, --help            show this help message and exit
# python args_subparse.py create -h
usage: args_subparse.py create [-h] [--read-only] dirname
positional arguments:
  dirname      New directoryto create
optional arguments:
  -h, --help   show this help message and exit
  --read-only  Setpermissions to prevent writing to the directory
# python args_subparse.py delete -h
usage: args_subparse.py delete [-h] [--recursive] dirname
positional arguments:
  dirname          The directory to remove
optional arguments:
  -h, --help       show this help message and exit
  --recursive, -r  Remove thecontents of the directory, too
# python args_subparse.py list -h
usage: args_subparse.py list [-h] dirname
positional arguments:
  dirname     Directory tolist
optional arguments:
  -h, --help  show this help message and exit
多个subparser 使用同样定义的参数
# add_help=False,必须指定,否则报-h重复定义
parents_parser = argparse.ArgumentParser(add_help=False)
parents_parser.add_argument('--foo', dest="foo", action='store_true')
parents_parser.add_argument('--bar', dest="bar", action='store_false')
parents_parser.add_argument('--baz', dest="baz", action='store_false')
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='commands')
m_parser = subparsers.add_parser("mysql", parents=[parents_parser], help="mysql method")
m_parser.set_defaults(func=sub_mysql)
o_parser = subparsers.add_parser("oracle", parents=[parents_parser], help="oracle method")
o_parser.set_defaults(func=sub_oracle)
args = parser.parse_args()
import argparse
parse = argparse.ArgumentParser()
parse.add_argument("a", help="params means")
parse.add_argument("-C", "--gc", default="count")
parse.add_argument("--ga", help="params means ga",dest='simple_value',choices=['A', 'B', 'C', 0])
parse.add_argument("--gb", help="params means gb",action="store_const",const='value-to-store')
args = parse.parse_args()
print args.simple_value,args.gb,args.gc
### add_argument 说明
不带'--'的参数
    调用脚本时必须输入值
    参数输入的顺序与程序中定义的顺序一致
'-'的参数
    可不输入    add_argument("-a")
    类似有'--'的shortname,但程序中的变量名为定义的参数名
'--'参数
    参数别名: 只能是1个字符,区分大小写
        add_argument("-shortname","--name", help="params means"),但代码中不能使用shortname
    dest: 参数在程序中对应的变量名称 add_argument("a",dest='code_name')
    default: 参数默认值
    help: 参数作用解释  add_argument("a", help="params means")
    type : 默认string  add_argument("c", type=int)
    action:
    store:默认action模式,存储值到指定变量。
    store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。
    store_true / store_false:布尔开关。可以2个参数对应一个变量。
    append:存储值到列表,该参数可以重复使用。
    append_const:存储值到列表,存储值在参数的const部分指定。
    count: 统计参数简写输入的个数  add_argument("-c", "--gc", action="count")
    version 输出版本信息然后退出。
    const:配合action="store_const|append_const"使用,默认值
    choices:输入值的范围 add_argument("--gb", choices=['A', 'B', 'C', 0])
from optparse import OptionParser  
[...]  
parser = OptionParser()  
parser.add_option("-f", "--file", dest="filename",  
                  help="write report to FILE", metavar="FILE")  
parser.add_option("-q", "--quiet",  
                  action="store_false", dest="verbose", default=True,  
                  help="don't print status messages to stdout")  
(options, args) = parser.parse_args()  
现在,妳就可以在命令行下输入:
<yourscript> --file=outfile -q  
<yourscript> -f outfile --quiet  
<yourscript> --quiet --file outfile  
<yourscript> -q -foutfile  
<yourscript> -qfoutfile  
上面这些命令是相同效果的。除此之外, optparse 还为我们自动生成命令行的帮助信息:
<yourscript> -h  
<yourscript> --help  
输出:
usage: <yourscript> [options]  
options:  
  -h, --help            show this help message and exit  
  -f FILE, --file=FILE  write report to FILE  
  -q, --quiet           don't print status messages to stdout  
简单流程
首先,必须 import OptionParser 类,创建一个 OptionParser 对象:
from optparse import OptionParser  
[...]  
parser = OptionParser()  
然后,使用 add_option 来定义命令行参数:

parser.add_option(opt_str, ...,  
                  attr=value, ...)  
每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 –file 分别是长短参数名:
parser.add_option("-f", "--file", ...)  
最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行:
(options, args) = parser.parse_args()  
注: 你也可以传递一个命令行参数列表到 parse_args();否则,默认使用 sys.argv[:1]。
parse_args() 返回的两个值:
options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就可以访问其对应的值: options.file 。
args,它是一个由 positional arguments 组成的列表。
Actions
action 是 parse_args() 方法的参数之一,它指示 optparse 当解析到一个命令行参数时该如何处理。actions 有一组固定的值可供选择,默认是’store ‘,表示将命令行参数值保存在 options 对象里。
示例
parser.add_option("-f", "--file",  
                  action="store", type="string", dest="filename")  
args = ["-f", "foo.txt"]  
(options, args) = parser.parse_args(args)  
print options.filename  
最后将会打印出 “foo.txt”。
当 optparse 解析到’-f’,会继续解析后面的’foo.txt’,然后将’foo.txt’保存到 options.filename 里。当调用 parser.args() 后,options.filename 的值就为’foo.txt’。
你也可以指定 add_option() 方法中 type 参数为其它值,如 int 或者 float 等等:
parser.add_option("-n", type="int", dest="num")  
默认地,type 为’string’。也正如上面所示,长参数名也是可选的。其实,dest 参数也是可选的。如果没有指定 dest 参数,将用命令行的参数名来对 options 对象的值进行存取。
store 也有其它的两种形式: store_true 和 store_false ,用于处理带命令行参数后面不 带值的情况。如 -v,-q 等命令行参数:
parser.add_option("-v", action="store_true", dest="verbose")  
parser.add_option("-q", action="store_false", dest="verbose")  
这样的话,当解析到 ‘-v’,options.verbose 将被赋予 True 值,反之,解析到 ‘-q’,会被赋予 False 值。
其它的 actions 值还有:
store_const 、append 、count 、callback 。
默认值
parse_args() 方法提供了一个 default 参数用于设置默认值。如:
parser.add_option("-f","--file", action="store", dest="filename", default="foo.txt")  
parser.add_option("-v", action="store_true", dest="verbose", default=True)  
又或者使用 set_defaults():
parser.set_defaults(filename="foo.txt",verbose=True)  
parser.add_option(...)  
(options, args) = parser.parse_args()  
from optparse import OptionParser  
[...]  
def main():  
    usage = "usage: %prog [options] arg"  
 parser = OptionParser(usage)  
    parser.add_option("-f", "--file", dest="filename",  
                      help="read data from FILENAME")  
    parser.add_option("-v", "--verbose",  
                      action="store_true", dest="verbose")  
    parser.add_option("-q", "--quiet",  
                      action="store_false", dest="verbose")  
    [...]  
  (options, args) = parser.parse_args()  
    if len(args) != 1:  
        parser.error("incorrect number of arguments")  
    if options.verbose:  
        print "reading %s..." % options.filename  
    [...]  
if __name__ == "__main__":  
    main()  
dd_argument:读入命令行参数,该调用有多个参数
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)
[python] view plaincopy
>>> parser.add_argument('-f', '--foo')    #选项参数 
>>> parser.add_argument('bar')        #位置参数 
nargs: 当选项后接受多个或者0个参数时需要这个来指定
比如
-u选项接受2个参数
[python] view plaincopy
>>> parser.add_argument('-u',nargs=2)  
>>> parser.parse_args('-u a b'.split()) 
Namespace(u=['a', 'b'])  
当选项接受1个或者不需要参数时指定nargs=’?',
当没有参数时,会从default中取值。
对于选项参数有一个额外的情况,就是出现选项而后面没有跟具体参数,那么会从const中取值
[python] view plaincopy
>>> parser.add_argument('-u',nargs='?') 
>>> parser.parse_args(''.split())  
Namespace(u=None)  
>>> parser.parse_args('-u a'.split())  
Namespace(u='a')  
>>> parser.add_argument('-u',nargs='?',default='d') 
>>> parser.add_argument('A',nargs='?',default='e')  
>>> parser.parse_args(''.split())  
Namespace(A='e', u='d')  
>>> parser.parse_args('-u'.split())  
Namespace(A='e', u=None)  
>>> parser.add_argument('-u',nargs='?',default='d',const='s')  
>>> parser.add_argument('A',nargs='?',default='T',const='P')  
>>> parser.parse_args(''.split())  
Namespace(A='T', u='d')  
>>> parser.parse_args('-u'.split())  
Namespace(A='T', u='s')  
>>> parser.parse_args('A'.split())  
Namespace(A='A', u='d')  
而对于后面需要跟多个参数的情况(–foo a1 a2 a3…),则需要设置nargs=’*’
[python] view plaincopy
>>> parser.add_argument('-u',nargs='*') 
>>> parser.parse_args('-u a b c d e'.split()) 
Namespace(u=['a', 'b', 'c', 'd', 'e'])  
nargs=’+'也和nargs=’*'一样,但是有一个区别当’+'时少于1个参数(没有参数)位置参数会报错误
[python] view plaincopy
>>> parser.add_argument('u',nargs='+')  
>>> parser.parse_args(''.split())  
usage: [-h] u [u ...]  
: error: too few arguments  
而‘*’会使用默认值
[python] view plaincopy
>>> parser.add_argument('u',nargs='*',default='e') 
>>> parser.parse_args(''.split())  
Namespace(u='e')  
default: 当参数需要默认值时,由这个参数指定,默认为None,当default=argparse.SUPPRESS时,不使用任何值
[python] view plaincopy
>>> parser.add_argument('u',nargs='*',default=argparse.SUPPRESS) 
>>> parser.parse_args(''.split())  
Namespace()  
type: 使用这个参数,转换输入参数的具体类型,这个参数可以关联到某个自定义的处理函数,这种函数
通常用来检查值的范围,以及合法性
[python] view plaincopy
>>> parser.parse_args('-u',type=int) 
>>> parser.add_argument('f',type=file) 
>>> parser.parse_args('-u 2 aa'.split())  
Namespace(f='aa', mode 'r' at 0x8b4ee38>, u=2)  
choices: 这个参数用来检查输入参数的范围
[python] view plaincopy
>>> parser.add_argument('-u',type=int,choices=[1,3,5]) 
>>> parser.parse_args('-u 3'.split())  
Namespace(u=3)  
>>> parser.parse_args('-u 4'.split())  
usage: [-h] [-u {1,3,5}]  
: error: argument -u: invalid choice: 4 (choose from 1, 3, 5)  
required: 当某个选项指定需要在命令中出现的时候用这个参数
[python] view plaincopy
>>> parser.add_argument('-u',required=True)  
>>> parser.parse_args(''.split())  
usage: [-h] -u U  
: error: argument -u is required  
help: 使用这个参数描述选项作用
[python] view plaincopy
>>> parser.add_argument('-u',required=True,default='wowo',help='%(prog)s for test sth(default: %(default)s)')  
>>> parser.print_help()                                                        usage: [-h] -u U  
optional arguments:  
  -h, --help  show this help message and exit  
  -u U        for test sth(default: wowo)  
dest: 这个参数相当于把位置或者选项关联到一个特定的名字
[python] view plaincopy
>>> parser.add_argument('--str',nargs='*') 
>>> parser.parse_args('--str a b c'.split())  
Namespace(str=['a', 'b', 'c'])  
>>> parser.add_argument('--str',nargs='*',dest='myname')
>>> parser.parse_args('--str a b c'.split())  
Namespace(myname=['a', 'b', 'c'])  
metavar: 这个参数用于help 信息输出中
[python] view plaincopy
>>> parser.add_argument('--str',nargs='*',metavar='AAA')  
>>> parser.print_help()  
usage: [-h] [--str [AAA [AAA ...]]]  
optional arguments:  
  -h, --help            show this help message and exit  
  --str [AAA [AAA ...]]  
>>> parser.add_argument('str',nargs='*',metavar='AAA')  
>>> parser.print_help()  
usage: [-h] [AAA [AAA ...]]  
positional arguments:  
  AAA  
optional arguments:  
  -h, --help  show this help message and exit
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档