Python模塊之命令行參數解析


解析命令行參數模塊

Python中由三個內建的模塊用於處理命令行參數:
第一個:getopt,只能簡單的處理命令行參數

官網資料:https://docs.python.org/2/library/getopt.html#module-getopt
第二個:optparse,功能強大,易於使用,可以方便地生成標准的、符合Unix/Posix 規范的命令行說明。(Python2.7以后棄用,不會繼續發展)
官網資料:https://docs.python.org/2/library/optparse.html
第三個:argparse,使其更加容易的編寫用戶友好的命令行接口。它所需的程序進程了參數定義,argparse將更好的解析sys.argv。同時argparse模塊還能自動生成幫助及用戶輸入錯誤參數時的提示信息。

官網資料:https://docs.python.org/2/library/argparse.html#module-argparse

getopt

   在運行程序時,可能需要根據不同的條件,輸入不同的命令行選項來實現不同的功能。目前常用的由短選項和長選項兩種格式。短選項格式為"-"加上單個字母 選項,長選項為"--"加上一個單詞。長格式實在Linux下引入的。許多Linux程序都支持這兩種格式。在Python中提供了getopt模塊很好 的實現了對着兩種用法的支持,而且使用簡單。

獲取命令行參數

Python環境下可以使用sys模塊得到命令行參數

import getopt import sys print(sys.argv) C:\Users\Administrator\>python 222.py -o t --help cmd file1 file2 ['222.py', '-o', 't', '--help', 'cmd', 'file1', 'file2'] # 由此可見,所有命令行參數以空格為分隔符,保存在sys.argv列表中,其中第一個為文件名

選項的寫法要求:
短格式:"-"號后面要緊跟一個選項字母。如果還有此選項的附加參數,可以用空格分開,也可以不分開。長度任意,可以用引號。
例如:
-o
-o "a b"
長格式:"--"號后面要跟一個單詞。如果還有些選項的附加參數,后面要緊跟"=",再加上參數。"="號前后不能有空格。
例如:
--help=file1

如何使用getopt進行參數分析及處理?

第一步:導入sys,getopt模塊
第二步:分析命令行參數
第三步:處理結果

import getopt import sys # print(sys.argv) def usage(): print( """ Usage:sys.args[0] [option] -h or --help:顯示幫助信息 -m or --module:模塊名稱 例如:ansible all -m shell -a 'date' -a or --args:模塊對於的參數 例如:ansible all -m shell -a 'date' -v or --version:顯示版本 """ ) if len(sys.argv) == 1: usage() sys.exit() try: opts, args = getopt.getopt(sys.argv[1:], "ho:m:a:", ["help", "output="]) # sys.argv[1:] 過濾掉第一個參數(它是腳本名稱,不是參數的一部分) except getopt.GetoptError: print("argv error,please input") # 使用短格式分析串“ho:m:a:” 當一個選項只表示開關狀態時,即后面不帶任何參數時,在分析串中寫入選項字符,例如:-h表示獲取幫助信息,顯示完成即可,不需任何參數 當一個選項后面需要帶附加參數時,在分析串中寫入選項字符同時后面加一個“:”號,例如:-m表示指定模塊名稱,后面需加模塊名稱 # 使用長格式分析串列表:["help", "output="]。 長格式串也可以有開關狀態,即后面不跟"="號。如果跟一個等號則表示后面還應有一個參數。這個長格式表示"help"是一個開關選項;"output="則表示后面應該帶一個參數。 # print(opts) # print(args) # 調用getopt函數。函數返回兩個列表:opts和args。 # opts為分析出的格式信息,是一個兩元組的列表。每個元素為:(選項串,附加參數)。如果沒有附加參數則為空串''。 # args為不屬於格式信息的剩余的命令行參數。 # 整個過程使用異常來包含,這樣當分析出錯時,就可以打印出使用信息來通知用戶如何使用這個程序。 # 以下部分即根據分析出的結果做相應的處理,並將處理結果返回給用戶 for cmd, arg in opts: # 使用一個循環,每次從opts中取出一個兩元組,賦給兩個變量。cmd保存選項參數,arg為附加參數。接着對取出的選項參數進行處理。 if cmd in ("-h", "--help"): print("help info") sys.exit() elif cmd in ("-o", "--output"): output = arg elif cmd in ("-m", "--module"): module_name = arg elif cmd in ("-a", "--module_args"): module_args = arg elif cmd in ("-v", "--version"): print("%s version 1.0" % sys.argv[0])
import getopt  
    import sys  
      
    config = {  
        "input":"",  
        "output":".",  
          
    }  
      
    #getopt三個選項,第一個一般為sys.argv[1:],第二個參數為短參數,如果參數后面必須跟值,須加:,第三個參數為長參數  
    #是一個列表,  
    opts, args = getopt.getopt(sys.argv[1:], 'hi:o:d',   
          [  
            'input=',   
            'output=',   
            'help'  
            ]  
          )  
      
    #參數的解析過程,長參數為--,短參數為-  
    for option, value in opts:  
        if  option in ["-h","--help"]:  
            print """  
            usage:%s --input=[value] --output=[value]  
            usage:%s -input value -o value  
            """  
        elif option in ['--input', '-i']:  
            config["input"] = value  
        elif option in ['--output', '-o']:  
            config["output"] = value  
        elif option == "-d":  
            print "usage -d"  
      
    print config   
# 結果
輸入的參數:--input=c:\temp\aa -o c:\temp\output -d
打印的結果:
usage -d
{'input': 'c:\\temp\\aa', 'output': 'c:\\temp\\output'}
案例2:獲取用戶信息,生成配置信息

argparse

 argparse簡介

   argparse是Python用於解析命令行參數和選項的標准模塊,用於代替已經過時的optparse模塊。argparse模塊的作用是用於解析 命 令行參數,例如python parseTest.py input.txt output.txt --user=name --port=8080。

argparse講解

將以下代碼保存為prog.py

import argparse parser = argparse.ArgumentParser(description='Process some integers.') # 首先創建一個ArgumentParser對象 parser.add_argument('integers', metavar='N', type=int, nargs='+', # 添加參數 help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') # 添加--sum則返回所有數之和,否則返回列表中的最大值 args = parser.parse_args() print args.accumulate(args.integers)
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...] Process some integers. positional arguments: N an integer for the accumulator optional arguments: -h, --help show this help message and exit --sum sum the integers (default: find the max) # 輸入正確的參數信息 $ python prog.py 1 2 3 4 4 $ python prog.py 1 2 3 4 --sum 10 # 輸入錯誤的參數信息 $ python prog.py a b c usage: prog.py [-h] [--sum] N [N ...] prog.py: error: argument N: invalid int value: 'a'
ArgumentParser對象的參數
prog - The name of the program (default: sys.argv[0])
usage - The string describing the program usage (default: generated from arguments added to parser)
description - Text to display before the argument help (default: none)
epilog - Text to display after the argument help (default: none)
parents - A list of ArgumentParser objects whose arguments should also be included
formatter_class - A class for customizing the help output
prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
argument_default - The global default value for arguments (default: None)
conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
add_help - Add a -h/–help option to the parser (default: True)
每個參數的詳細說明:
prog:即運行程序的名稱,默認取sys.argv[0]的值,可以修改為指定的名稱
usage:指定usage信息的內容及格式,默認是根據你添加的信息自動生成的,可以自定義修改為指定的內容
description:這個程序的功能概述
epilog:在整個幫助信息最后添加的附加信息
parents:用於定義一些公共的信息供子類調用
formatter_class:整個信息的類定義,主要包含三個類,每個類的功能如下:
  • class argparse.RawDescriptionHelpFormatter # 如何顯示文本描述
  • class argparse.RawTextHelpFormatter # 如何顯示文本描述
  • class argparse.ArgumentDefaultsHelpFormatter # 自定添加參數信息
prefix_chars:自定義參數個前綴類型
fromfile_prefix_chars:指定文件替代命令行輸入參數的方式
argument_default:
conflict_handler:檢測是否存在相同的參數選項,不加該參數直接報錯,添加該參數可以兼容(conflict_handler='resolve') 
add_help:  設置是否顯示幫助信息那表之類(默認顯示)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

$ python myprogram.py --help
usage: myprogram.py [-h] [--foo FOO]

optional arguments:
 -h, --help  show this help message and exit
 --foo FOO   foo help
不設置該參數
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
>>> parser.add_argument('--foo', help='foo help')
>>> parser.print_help()
usage: PROG [--foo FOO]

optional arguments:
 --foo FOO  foo help
設置該參數
add_argument()方法    

    格式: ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

  • name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.    # 參數選項列表
  • action - The basic type of action to be taken when this argument is encountered at the command line.
  • nargs - The number of command-line arguments that should be consumed.
  • const - A constant value required by some action and nargs selections.
  • default - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • required - Whether or not the command-line option may be omitted (optionals only).
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parse_args().

實際案例講解

# 基本認識,只有就基本框架 import argparse parser = argparse.ArgumentParser() parser.parse_args() # 結果 C:\Users\Administrator\Desktop>python3 getopt_help.py -h usage: getopt_help.py [-h] optional arguments: -h, --help show this help message and exit C:\Users\Administrator\Desktop>python3 getopt_help.py foo usage: getopt_help.py [-h] getopt_help.py: error: unrecognized arguments: foo C:\Users\Administrator\Desktop>python3 getopt_help.py -f usage: getopt_help.py [-h] getopt_help.py: error: unrecognized arguments: -f # 結果分析 1)不給參數而運行這個程序,將不會得到任何結果 2)沒有做任何特別設置,可以得到一個很簡潔的幫助信息(第二三個例子) 3)無需人為設置--help參數,就能得到一個良好的幫助信息。但是若給其他參數(比如foo)就會產生一個錯誤。

 其他

 if len(sys.argv) == 1:
     parser.print_help()
     sys.exit(1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM