add_argument:读入命令行参数,该调用有多个参数

ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)

  1. >>> parser.add_argument('-f', '--foo')    #选项参数
  2. >>> parser.add_argument('bar')        #位置参数

nargs: 当选项后接受多个或者0个参数时需要这个来指定
比如-u选项接受2个参数

  1. >>> parser.add_argument('-u',nargs=2)
  2. >>> parser.parse_args('-u a b'.split())
  3. Namespace(u=['a', 'b'])

当选项接受1个或者不需要参数时指定nargs=’?',当没有参数时,会从default中取值。对于选项参数有一个额外的情况,就是出现选项而后面没有跟具体参数,那么会从const中取值

  1. >>> parser.add_argument('-u',nargs='?')
  2. >>> parser.parse_args(''.split())
  3. Namespace(u=None)
  4. >>> parser.parse_args('-u a'.split())
  5. Namespace(u='a')
  6. >>> parser.add_argument('-u',nargs='?',default='d')
  7. >>> parser.add_argument('A',nargs='?',default='e')
  8. >>> parser.parse_args(''.split())
  9. Namespace(A='e', u='d')
  10. >>> parser.parse_args('-u'.split())
  11. Namespace(A='e', u=None)
  12. >>> parser.add_argument('-u',nargs='?',default='d',const='s')
  13. >>> parser.add_argument('A',nargs='?',default='T',const='P')
  14. >>> parser.parse_args(''.split())
  15. Namespace(A='T', u='d')
  16. >>> parser.parse_args('-u'.split())
  17. Namespace(A='T', u='s')
  18. >>> parser.parse_args('A'.split())
  19. Namespace(A='A', u='d')

而对于后面需要跟多个参数的情况(–foo a1 a2 a3…),则需要设置nargs=’*’

  1. >>> parser.add_argument('-u',nargs='*')
  2. >>> parser.parse_args('-u a b c d e'.split())
  3. Namespace(u=['a', 'b', 'c', 'd', 'e'])

nargs=’+'也和nargs=’*'一样,但是有一个区别当’+'时少于1个参数(没有参数)位置参数会报错误

  1. >>> parser.add_argument('u',nargs='+')
  2. >>> parser.parse_args(''.split())
  3. usage: [-h] u [u ...]
  4. : error: too few arguments

而‘*’会使用默认值

  1. >>> parser.add_argument('u',nargs='*',default='e')
  2. >>> parser.parse_args(''.split())
  3. Namespace(u='e')

default: 当参数需要默认值时,由这个参数指定,默认为None,当default=argparse.SUPPRESS时,不使用任何值

  1. >>> parser.add_argument('u',nargs='*',default=argparse.SUPPRESS)
  2. >>> parser.parse_args(''.split())
  3. Namespace()

type: 使用这个参数,转换输入参数的具体类型,这个参数可以关联到某个自定义的处理函数,这种函数通常用来检查值的范围,以及合法性

  1. >>> parser.parse_args('-u',type=int)
  2. >>> parser.add_argument('f',type=file)
  3. >>> parser.parse_args('-u 2 aa'.split())
  4. Namespace(f=<open file 'aa', mode 'r' at 0x8b4ee38>, u=2)

choices: 这个参数用来检查输入参数的范围

  1. >>> parser.add_argument('-u',type=int,choices=[1,3,5])
  2. >>> parser.parse_args('-u 3'.split())
  3. Namespace(u=3)
  4. >>> parser.parse_args('-u 4'.split())
  5. usage: [-h] [-u {1,3,5}]
  6. : error: argument -u: invalid choice: 4 (choose from 1, 3, 5)

required: 当某个选项指定需要在命令中出现的时候用这个参数

  1. >>> parser.add_argument('-u',required=True)
  2. >>> parser.parse_args(''.split())
  3. usage: [-h] -u U
  4. : error: argument -u is required

help: 使用这个参数描述选项作用

  1. >>> parser.add_argument('-u',required=True,default='wowo',help='%(prog)s for test sth(default: %(default)s)')
  2. >>> parser.print_help()                                                        usage: [-h] -u U
  3. optional arguments:
  4. -h, --help  show this help message and exit
  5. -u U        for test sth(default: wowo)

dest: 这个参数相当于把位置或者选项关联到一个特定的名字

  1. >>> parser.add_argument('--str',nargs='*')
  2. >>> parser.parse_args('--str a b c'.split())
  3. Namespace(str=['a', 'b', 'c'])
  4. >>> parser.add_argument('--str',nargs='*',dest='myname')
  5. >>> parser.parse_args('--str a b c'.split())
  6. Namespace(myname=['a', 'b', 'c'])

metavar: 这个参数用于help 信息输出中

    1. >>> parser.add_argument('--str',nargs='*',metavar='AAA')
    2. >>> parser.print_help()
    3. usage: [-h] [--str [AAA [AAA ...]]]
    4. optional arguments:
    5. -h, --help            show this help message and exit
    6. --str [AAA [AAA ...]]
    7. >>> parser.add_argument('str',nargs='*',metavar='AAA')
    8. >>> parser.print_help()
    9. usage: [-h] [AAA [AAA ...]]
    10. positional arguments:
    11. AAA
    12. optional arguments:

python argparse模块--转载的更多相关文章

  1. Python argparse 模块

    Python argparse 模块 test.py: import argparse argparser = argparse.ArgumentParser(add_help=False) argp ...

  2. python - argparse 模块学习

    python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...

  3. python argparse模块解析命令行选项简单使用

    argparse模块的解析命令行选项简单使用 util.py #!/usr/bin/env python # coding=utf-8 import argparse parser = argpars ...

  4. Python Argparse模块

    argparse模块 在Python中,argparse模块是标准库中用来解析命令行参数的模块,用来替代已经过时的optparse模块.argparse模块能够根据程序中的定义从sys.argv中解析 ...

  5. python argparse模块:命令行选项及参数解析

    位置参数:给一个例子: import argparse parser = argparse.ArgumentParser() parser.add_argument("echo") ...

  6. 聊聊Python ctypes 模块(转载)

    https://zhuanlan.zhihu.com/p/20152309?columnSlug=python-dev 作者:Jerry Jho链接:https://zhuanlan.zhihu.co ...

  7. Python argparse模块实现模拟 linux 的ls命令

    python 模拟linux的 ls 命令 sample: python custom_ls.py -alh c:/ 选项: -a ,--all 显示所有文件,包括'.'开头的隐藏文件 -l  列表显 ...

  8. python argparse模块的使用

    import argparse def get_parse(): # 初始化 parse = argparse.ArgumentParser() # 添加选项,类型为str,默认为空 parse.ad ...

  9. Python标准模块--argparse

    1 模块简介 你一定很奇怪Python是如何命令行中的变量的吧?argparse就是用来解决这个问题的,argparse是optparse的替代. 2 模块使用 2.1 开始 我发现解释一个编程的概念 ...

随机推荐

  1. [django]Django model中数据批量导入bulk_create()

    参考: https://www.cnblogs.com/ccorz/p/Django-model-zhong-shu-ju-pi-liang-dao-rubulkcreat.html import o ...

  2. col-md-*和col-sm-*

    屏幕大于(≥992px) ,使用col-md-* 而不是col-sm-*如果屏幕大于(≥768px),小雨<=992px,使用col-sm-* 而不是col-md-*

  3. [LeetCode] 292. Nim Game_Easy tag: Math

    You are playing the following Nim Game with your friend: There is a heap of stones on the table, eac ...

  4. [LeetCode] 225. Implement Stack using Queues_Easy tag: Design

    Implement the following operations of a stack using queues. push(x) -- Push element x onto stack. po ...

  5. git 下载单个文件 已经添加多个远程服务器

    175down vote It is possible to do (in the deployed repository) git fetch followed by git checkout or ...

  6. HTTP请求返回状态码详解

    当用户试图通过 HTTP 访问一台正在运行 Internet 信息服务 (IIS) 的服务器上的内容时,IIS 返回一个表示该请求的状态的数字代码.状态代码可以指明具体请求是否已成功,还可以揭示请求失 ...

  7. xcode6 新建项目真机调试无法全屏

    设置app ICons and Launch Images属性 通过设置启动图片,选择一张适配的图片(Default-568@2x)作为启动页的图片,可以解决全屏的问题

  8. sql server删除重复数据,保留第一条

    SELECT * FROM EnterpriseDataTools.Enterprise.CompanyMainwhere CompanyNo in (select CompanyNo from En ...

  9. Spring MVC 和 Struts2 的比较

    SpringMVC与Struts2的比较 1:框架核心机制:SpringMVC(DispatcherServlet)采用Servlet实现,Struts2采用Filter(StrutsPrepareA ...

  10. ATG精准科技-前端面试题

    1.请写出以下结果 for(var i=0; i<10; i++){ setTimeout(function () { console.log(i) },10) } 结果:打印10次190解析: ...