使用 argparse

例一 位置参数

#!/usr/bin/env python3 

import  argparse
parser = argparse.ArgumentParser()  #生成一个解析器
parser.add_argument("pos",      #没有-开始的是“位置参数”
            help="输入浮点数",   #对这个参数的提示信息
            type=float)         #这个参数会解析为float 
      #Common built-in types and functions can be used directly as the value of the type argument type=len
args = parser.parse_args()      #解析参数
print(args.pos)

例二 action

>>> parser.add_argument('--foo', action='store_const', const=42) # 设置foo为常量42
>>> parser.add_argument('--foo', action='store_true',default=false) # 设置bar为true,默认为false
>>> parser.add_argument('--bar', action='store_false') # 设置bar为false
>>> parser.add_argument('--foo', action='append') #arg.py --foo 1 --foo 2 foo为[1,2]

例三 nargs

parser.add_argument('--foo', nargs=2)   #arg.py --foo 1 2 foo为['1', '2']
parser.add_argument('foo', nargs=2)    #arg.py  1 2  foo为['1', '2']
parser.add_argument('foo', nargs='?')    #arg.py  1 2  foo为['1', '2'] 如果没有参数,结果是None,多于1个提示错误
parser.add_argument('foo', nargs='+')    #arg.py  1 2  foo为['1', '2']  如果没有参数,提示错误
parser.add_argument('foo', nargs='*')    #arg.py  1 2  foo为['1', '2']   如果没有参数,结果是[ ]
parser.add_argument('foo', nargs=argparse.REMAINDER)    #arg.py  1 2  foo为['1', '2']   把剩余的放到foo列表里

nargs 的值可以为:

  • N (an integer). N arguments from the command line will be gathered together into a list.
  • '?'. One argument will be consumed from the command line if possible, and produced as a single item.
  • '*'. All command-line arguments present are gathered into a list.
  • '+'. Just like '*', all command-line args present are gathered into a list.
  • argparse.REMAINDER. All the remaining command-line arguments are gathered into a list.

例四 choices

>>> parser.add_argument('door', type=int, choices=range(1, 4))  #door只能是123
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,132评论 0 23
  • 对于我来说新年愿望是不可能一一实现的,但我自己要尝试一下。到年末完成以下清单的百分之八十我就算是在2017年不留遗...
    若尘少年阅读 361评论 1 2
  • 闭包是功能性自包含模块,可以在代码中被传递和使用。 Swift 中的闭包与 C 和 Objective-C中的 b...
    Mustard_Buli阅读 1,048评论 0 1
  • 上次写日记还是今年的二月,转眼,2017年也即将过完。今天看了篇文章受到感触,心想不能再这样虚度光阴,于是制定了...
    Lion_2f8c阅读 151评论 0 1