Python 詳解命令行解析 - argparse


sys.argv

適合解析簡單的命令行

filename = arg_sys.py

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
需要模塊:sys
參數個數:len(sys.argv)
文件名: sys.argv[0]
參數1: sys.argv[1]
參數2: sys.argv[2]
......
'''
import sys
print "file = ", sys.argv[0]
for i in range(1, len(sys.argv)):
print "parameter%s = %s"%(i, sys.argv[i])

在dos輸入Python arg_sys.py 1 2 3 4 5

why choice argparse ?

2.7之后python不再對optparse模塊進行擴展,推薦使用argparse模塊對命令行進行解析。

來自stackoverflow的說明

As of 2.7, optparse is deprecated, and will hopefully Go away in the future.

argparse is better for all the reasons listed on its original page (http://code.google.com/p/argparse/):

  • handling positional arguments
  • supporting sub-commands
  • allowing alternative option prefixes like + and /
  • handling zero-or-more and one-or-more style arguments
  • producing more informative usage messages
  • providing a much simpler interface for custom types and actions

More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.

創建解析器 - ArgumentParser

import argparse
parser = argparse.ArgumentParser()
class ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)

創建一個ArgumentParser實例,ArgumentParser的參數都為關鍵字參數。

prog :文件名,默認為sys.argv[0],用來在help信息中描述程序的名稱。

usage :描述程序用途的字符串

description :help信息前顯示的信息

epilog :help信息之后顯示的信息

>>> import argparse
>>> parser = argparse.ArgumentParser(prog='my - program', usage='%(prog)s [optio
ns] usage',description = 'my - description',epilog = 'my - epilog')
>>> parser.print_help()
usage: my - program [options] usage

my - description

optional arguments:
-h, --help show this help message and exit

my - epilog

parents :由ArgumentParser對象組成的列表,它們的arguments選項會被包含到新ArgumentParser對象中。(類似於繼承)

formatter_class :help信息輸出的格式,為了美觀…

prefix_chars :參數前綴,默認為’-‘(最好不要修改)

fromfile_prefix_chars :前綴字符,放在文件名之前

conflict_handler :解決沖突的策略,默認情況下沖突會發生錯誤,(最好不要修改)

add_help :是否增加-h/-help選項 (默認為True),一般help信息都是必須的。設為False時,help信息里面不再顯示-h –help信息

argument_default: - (default: None)設置一個全局的選項的缺省值,一般每個選項單獨設置,基本沒用

添加參數選項 - add_argument

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

name or flags :參數有兩種,可選參數和位置參數

action: 默認為store

nargs: 參數的數量

const :保存一個常量

default :默認值

type :參數類型,默認為str

choices :設置參數值的范圍,如果choices中的類型不是字符串,記得指定type

required :該選項是否必選,默認為True

metaver:幫助信息中顯示的參數名稱

dest :參數名

>>> import argparse
>>> parser=argparse.ArgumentParser()
>>> parser.add_argument('--version', action='version', version='version 2.0')
_VersionAction(option_strings=['--version'], dest='version', nargs=0, const=None
, default='==SUPPRESS==', type=None, choices=None, help="show program's version
number and exit", metavar=None)
>>> parser.parse_args(['--version'])
version 2.0

例子:

import argparse

def parse_arguments(version_info, args=None):
parser = argparse.ArgumentParser()

parser.add_argument('-v', '--version', action='version',
version=version_info,
help='Show program version info and exit.')

parser.parse_args(args)
if __name__ == "__main__":

parse_arguments("${version_info}")

參考網址:

原文地址(http://blog.csdn.net/lis_12/article/details/54618868).


免責聲明!

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



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