wss1051 发表于 2018-8-10 06:16:39

使用docopt生成Python脚本参数项

# coding=utf-8  """1                        #这儿写标题,-h的时候会被打印出来
  Usage:                     #没有出现在Usage中的不规范用法,将会打印Usage段,并sys.exit(1)
  1.py D_IP init_instance [--configSvr] [--replname=<replSetName>] [-P PORT | --port=PORT] [--disk=data{}]
  1.py init_mongos [-P PORT | --port=PORT] [--instance=<IP>:<PORT>]
  1.py -h | --help
  Arguments:             #可以直接输入参数,而不用输入参数名。其位置由上面的Usage定义
  D_IPdestination IP
  Options:                                                                                  #对上面Usage中出现的参数的说明,
  -P PORT   Self port.                                                            #当一个参数项同时拥有-X --xx两种形式的表达方式的时候
  --disk=DATA_NUMBER    Install in /Data{}.                         #结果字典中返回的参数名为--xx
  --replname=<replSetName> ReplSet`s Name.                   #
  # 传值的参数项有两种表达方式 -X YY --xx=YY 或 -X <yy>, --xx <yy>
  #         前一种参数值提示应全大写,后一种用逗号分隔,提示应该用<>包裹
  """
  from docopt import docopt
  def concat_parameters(dict_a):
  opt_str = ''
  for i in dict_a.keys():
  # 如果该选项非false(有值,或True),且是--parameters,追加拼接到参数字符串中
  if dict_aand i == '--':
  print('key:', i)
  opt_str = opt_str+' {}={}'.format(i,dict_a)
  print(opt_str)
  if __name__ == '__main__':
  arguments = docopt(__doc__, version='0.1.1rc')#借用了脚本的__doc__属性存放参数说明
  # version选项指定了脚本的版本信息
  # print(arguments)
  if arguments['init_instance']:
  D_IP = arguments['D_IP']
  concat_parameters(arguments)
  elif arguments['init_mongos']:
  pass
页: [1]
查看完整版本: 使用docopt生成Python脚本参数项