argparse 模块, 辅助模块 shlex

辅助模块 shlex

eg: shlex.split('lpp –species-list Na NaH')

弹出错误提示

  • 使用 parser.error("Your message.")

https://stackoverflow.com/questions/6722936/python-argparse-make-at-least-one-argument-required

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-process')
parser.add_argument('-upload')

args = parser.parse_args()

if not (args.process or args.upload):
parser.error('No action requested, add -process or -upload')

Action 类

查看原码

不手动输入参数值的方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import argparse

class CustomAction(argparse.Action):
    # 注意: 这里保留的参数是,parser.add_argument 中必须包含的参数
def __init__(self, option_strings, dest, default=None, **kwargs):

    # 这里是 要设置的parser.add_argument 默认参数
    super(CustomAction, self).__init__(option_strings=option_strings,
                                       dest=dest,
                                       default=default,
                                       # 表示 不需要参数值,也只能在这里设置
                                       # 否则 要在 add_argument , 上面的__init__中特别说明,
                                       nargs=0,
                                       ,**kwargs)

  def __call__(self, parser, namespace, values, option_strings=None):
      extrapolation = 'Criss-Cobble'
      setattr(namespace, self.dest, extrapolation)


if __name__ == '__main__':
    parser = argparse.add_argument('--use_criss_cobble', action=CustomAction)
    args = parser.parse_args(['--use_criss_cobble'])

print(args.use_criss_cobble)

# output: Criss-Cobble

add_argument

nargs

注意: 如果指定 nargs = 1, 或 nargs = 2 …

得到的结果是一个列表

多个输入

1
parser.add_argument('--items', type=str, nargs="+", default=[])