1. 程式人生 > 實用技巧 >Python 利用argparse模組實現指令碼命令列引數解析

Python 利用argparse模組實現指令碼命令列引數解析

利用argparse模組實現指令碼命令列引數解析

By:授客 QQ:1033553122

#程式碼實踐1

study.py內容如下

#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = 'shouke'

import argparse

def argparseFunc():
  '''
  基於argparse模組實現命令引數解析功能
  執行示例:
       python study.py -i 172.19.7.236 -p 8080 -a -r
       python study.py --ip 172.19.7.236 --port 7077 --auth -w -v True
  '''

  parser = argparse.ArgumentParser(description="study.py usage help document")
  # 新增不帶預設值的可解析引數
  parser.add_argument("-i", "--ip", help="ip addr") #注意: -h、--help為內建引數,不可用
  parser.add_argument("-p", "--port",help="host port")

  # 新增帶預設值的可解析引數(# action = store_true 表示是如果使用了這個引數,則值引數值設定為True # 更多action配置可參考原始碼
  # 需要注意的是,不能為帶預設值引數指定引數值,會報錯,該引數值會被當作不識別的引數
  parser.add_argument("-a", "--auth", help="if auth need", action="store_true")


  # 新增互斥引數(比如 例中的-r和-w 同時只能用一個)
  exclusive_group = parser.add_mutually_exclusive_group()
  exclusive_group.add_argument("-r","--read", help="read enabled" , action="store_true")
  exclusive_group.add_argument("-w","--write", help="write enabled", action="store_true")

  # 新增引數時不設定設定引數說明
  parser.add_argument('-v') # show verbose

  # 新增引數時不設定引數全名
  parser.add_argument('-V', help="version")

  ARGS = parser.parse_args() # 獲取命令列引數
  print('ARGS:', ARGS)

  # 獲取某個引數值
  if ARGS.ip: # 注意,這裡的引數名,必須使用引數全稱
    print("host addr is: %s" % ARGS.ip)

  if ARGS.port:
    print("host port is: : %s" % ARGS.port)

  if ARGS.auth:
    print("auth need: : %s" % ARGS.auth)

  if ARGS.read:
    print("read enabled: %s" % ARGS.read)

  if ARGS.write:
    print("write enabled: %s" % ARGS.write)

argparseFunc()

執行測試

python study.py -i 172.19.7.236 -p 8080 -a -r
python study.py --ip 172.19.7.236 --port 7077 --auth -w -v True

  

結果如下

python study.py -i127.0.0.1 # 注意,引數和引數值之間可以沒有空格

結果如下

python study.py -notExists 1

結果如下

如上,以上程式碼實現是針對單個模組指令碼,如果要在多個模組中使用咋辦?解決方法為封裝為類,具體參見“程式碼實踐2”

#程式碼實踐2

argument_parser.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-


'''
@Author : shouke
'''


import argparse

class ArgParser(object):
  '''
     引數解析器
  '''


  def __init__(self,  none_exclusive_arguments, exclusive_arguments, description=''):
      self.parser =  argparse.ArgumentParser(description=description)

      self.add_none_exclusive_arguments(none_exclusive_arguments)
      self.add_exclusive_arguments(exclusive_arguments)

  def add_none_exclusive_arguments(self, options:list):
      '''
      新增常規選項(非互斥選項)
      :param options 格式為list型別,形如
      [
          '"-a", "--all", help="do not ignore entries starting with ."',
          '"-b", "--block", help="scale sizes by SIZE before printing them"',
          '"-C", "--color", help="colorize the output; WHEN can be 'never', 'auto'"',
          '"-flag", help="make flag", action="store_true"', # action="store_true" 表示如果不設定該選項的值,則預設值為true,類似的action="store_false" 表示預設值為false
      ]
      其中,每個list元素為argparse.ArgumentParserlei add_argument類函式實參的字串表示,add_argument函式定義add_argument(self, *args,**kwargs)
      '''

      for option in options:
          eval('self.parser.add_argument(%s)' % option)


  def add_exclusive_arguments(self, options:list):
      '''
      新增互斥選項
      :param options 格式為list,形如以下
       [
           ('"-r","--read",help="Read Action",action="store_true"',
            '"-w","--write",help="Write Action",action="store_true"')
       ]

      '''
      for option_tuple in options:
          exptypegroup = self.parser.add_mutually_exclusive_group()
          for item in option_tuple:
              eval('exptypegroup.add_argument(%s)' % item)


  @property
  def args(self):
      return self.parser.parse_args()

  

在xxx.py中引用(注意:為了讓引數解析器起到應起的作用,建議在指令碼最上方構造引數解析器物件)

study.py內容如下

#!/usr/bin/env python
# -*- coding:utf-8 -*-

__author__ = 'shouke'

from argument_parser import ArgParser

none_exclusive_arguments = [
    '"-ip", help="自動化測試服務平臺地址"',
    '"-projectId", help="自動化測試專案id"',
    '"-runEnv", help="自動化測試專案執行環境"',
    '"-logLevel", help="日誌級別"',
    '"-masterHost", help="master服務地址"',
    '"-masterPort", help="master服務埠"'
]

exclusive_arguments = [

   ('"-r", "--read", help="Read Action",action="store_true"',
    '"-w", "--write", help="Write Action",action="store_true"')
]


args = ArgParser(none_exclusive_arguments, exclusive_arguments).args

print(args)
print(args.ip)
print(args.read)

執行測試

python study.py -i 127.0.0.1 -r

執行結果如下