XiaoKL学Python(D)argparse

该文以Python 2为基础。

1. argparse简介

argparse使得编写用户友好的命令行接口更简单。

argparse知道如何解析sys.argv。

argparse 模块自动生成 “帮助” 信息和 “使用” 信息。

当用户使用了错误的参数,argparse则报错。

2. argparse的使用

A) 使用argparse的第一步需要 创建ArgumentParser对象。

ArgumentParser对象将持有所有的解析命令的必要信息。

B) add_argument() 添加 关于程序参数的信息。

C) ArgumentParser对象使用 方法parse_args() 来解析参数。该方法检查命令行,将每个参数转换为

合适的类型,然后调用合适的Action。

3. ArgumentParser对象

创建新的ArgumentParser对象,所有的参数应该以 keyword arguments 进行传参。

1 class argparse.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)

prog: The name of the program (程序的名字)

usage: 描述如何使用程序。

description: 在 程序帮助 前面显示的文本。(默认:None)

epilog: 

parents:

formatter_class:

prefix_chars:

fromfile_prefix_chars:

argument_default:

conflict_handler:

add_help:

4. add_argument() 方法

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

5. Demo: ArgParseDemo.py

 1 from __future__ import print_function
 2 import argparse
 3 
 4 
 5 def main():
 6     parser = argparse.ArgumentParser()
 7     parser.add_argument('bar', nargs='?')
 8     parser.add_argument('foo', nargs='?')
 9     args = parser.parse_args()
10     print("foo: %s" % args.foo)
11     print("bar: %s" % args.bar)
12 
13 if __name__ == '__main__':
14     main()

运行该脚本如下: 

$ python ArgParseDemo.py ooo pp

foo: pp

bar: ooo


Reference

1. https://docs.python.org/2/library/argparse.html

2. Python Argparse Cookbook

https://mkaz.blog/code/python-argparse-cookbook/

3. How to Build Command Line Interfaces in Python With argparse

https://realpython.com/command-line-interfaces-python-argparse/

原文地址:https://www.cnblogs.com/cwgk/p/4448339.html