python 命令行參數解析的標準模板

#!/usr/bin/env python
#-*-coding:utf-8-*-
# argparse-template.py bsxylj created (2017/08/19)

import argparse

#==================================================================
def make_argparse():
  ''' change this function for custom command line parameter.'''

  parser = argparse.ArgumentParser()

  # positional argument : parse by sequance , must be exist, 
  # must in right type , must in right sequance
  parser.add_argument("name", help="--------")          #default type is string
  parser.add_argument("tel",  help="--------",type=int) #custorm int type

  # optional argument : parse by key and value, no care 
  # to sequance , such as "-x=xxxx" or "-x xxxx"
  parser.add_argument("-o", "--output",  help="--------")
  parser.add_argument("-v", "--verbosity", help="--------", action="store_true")
  #This means that, if the option is specified, assign the value True to args.verbosity.
  # Not specifying it implies False.

  args = parser.parse_args()
  return args
#==================================================================


#main code
args = make_argparse(); 
print args.name
print args.tel
if args.verbosity:
  print "verbosity turned on"
if args.output:
  print "output : " + args.output

可使用如下形式調用:
argparse-template.py
argparse-template.py bsxylj 18612345678
argparse-template.py bsxylj 18612345678 -o=output_dir
argparse-template.py bsxylj 18612345678 -o output_dir
argparse-template.py bsxylj 18612345678 –output=output_dir
argparse-template.py bsxylj 18612345678 –output output_dir
argparse-template.py bsxylj 18612345678 -v
argparse-template.py bsxylj 18612345678 -v -o=output_dir
argparse-template.py bsxylj -v -o=output_dir 18612345678
argparse-template.py -o=output_dir -v bsxylj 18612345678

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章