python argparse(参数解析)模块学习(一)

时间:2022-09-13 18:57:08
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects. Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
"""

取自argparse-1.4.0

1、prog 程序名(默认是sys.argv[0])

import argparse
parser = argparse.ArgumentParser()
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: argparse-3.py [-h] optional arguments:
-h, --help show this help message and exit

显示程序名为:argparse-3.py

可通过设置prog改变结果

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3")
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] optional arguments:
-h, --help show this help message and exit

可见程序名已经修改为learn_argparse_3

2、usage 程序的使用用例,默认情况下回自动生成

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",usage="[-h] [--help] [...] [what you want???]")
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: [-h] [--help] [...] [what you want???] optional arguments:
-h, --help show this help message and exit

这里可见learn_argparse_3没有打印,故在自定义usage是要注意。

可用:

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",usage="%(prog)s [-h] [--help] [...] [what you want???]")
parser.add_argument('bar', nargs='+', help='bar help')
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] positional arguments:
bar bar help optional arguments:
-h, --help show this help message and exit

3、description help参数之前显示的信息

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description="A learn program")
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] A learn program optional arguments:
-h, --help show this help message and exit

description经常会被调用用了简单的描述这个程序的用途,默认在信息的前后会有换行

4、epilog 收场白,可在最后加入你想展示的信息

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description="A learn program",
epilog="All for one, one for all")
arg = parser.parse_args()

结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] A learn program optional arguments:
-h, --help show this help message and exit All for one, one for all

5、parents 有时候多个解析器共享一个参数,你可以将这个参数出递给parent

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int) parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description="A learn program",
epilog="All for one, one for all",
parents=[parent_parser])
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] A learn program optional arguments:
-h, --help show this help message and exit
--parent PARENT All for one, one for all

可见--parent 共享了

6、formatter_class 打印信息格式设定

    - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
ArgumentDefaultsHelpFormatter -- Formatter classes which
may be passed as the formatter_class= argument to the
ArgumentParser constructor. HelpFormatter is the default,
RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser
not to change the formatting for help text, and
ArgumentDefaultsHelpFormatter adds information about argument defaults
to the help.

摘自argparse-1.4.0

可见formatter_class有4个参数:HelpFormatter,RawDescriptionHelpFormatter,RawTextHelpFormatter,ArgumentDefaultsHelpFormatter

  • HelpFormatter 是默认参数
import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int) parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description='''
other men live ti eat, while i eat to live -- socrates
love rules his kingdom without a sword -- herbert''',
epilog='''
All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller''',
parents=[parent_parser],
formatter_class=argparse.HelpFormatter)
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] other men live ti eat, while i eat to live -- socrates love rules his kingdom
without a sword -- herbert optional arguments:
-h, --help show this help message and exit
--parent PARENT All for one, one for all -- dumas we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

可见HelpFormatter粗暴的去除了所有的'\s' '\n'

  • RawDescriptionHelpFormatter,description和epilog不做修改原样输出
import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int) parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description='''
other men live ti eat, while i eat to live -- socrates
love rules his kingdom without a sword -- herbert''',
epilog='''
All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller''',
parents=[parent_parser],
formatter_class=argparse.RawDescriptionHelpFormatter)
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] other men live ti eat, while i eat to live -- socrates
love rules his kingdom without a sword -- herbert optional arguments:
-h, --help show this help message and exit
--parent PARENT All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

然源码中好像在line之间加入了个indent,不明所以,有知道的小伙伴可以指导下吗?

  • RawTextHelpFormatter  会保留预定意的帮助信息中的空格
  • ArgumentDefaultsHelpFormatter会在HelpFormatter的基础上打印默认值给参数(测试发现在add_argument中无help参数也不会显示default)
import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6]) parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description='''
other men live ti eat, while i eat to live -- socrates love rules his kingdom without a sword -- herbert''',
epilog='''
All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller''',
parents=[parent_parser],
formatter_class=argparse.RawDescriptionHelpFormatter)
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] other men live ti eat, while i eat to live -- socrates love rules his kingdom without a sword -- herbert optional arguments:
-h, --help show this help message and exit
--parent PARENT All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

default值并没有打印出来

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6,],help='parent') parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description='''
other men live ti eat, while i eat to live -- socrates love rules his kingdom without a sword -- herbert''',
epilog='''
All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller''',
parents=[parent_parser],
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
arg = parser.parse_args()

运行结果:

argparse-learn]# python argparse-3.py -h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] other men live ti eat, while i eat to live -- socrates love rules his kingdom
without a sword -- herbert optional arguments:
-h, --help show this help message and exit
--parent PARENT parent (default: [1, 2, 3, 4, 5, 6]) All for one, one for all -- dumas we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

7、prefix_chars 自定义前缀,默认'-'

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6,],help='parent') parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description='''
other men live ti eat, while i eat to live -- socrates love rules his kingdom without a sword -- herbert''',
epilog='''
All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller''',
parents=[parent_parser],
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prefix_chars='=')
arg = parser.parse_args()

这是不能用“python argparse-3.py -h”,会报错

运行结果:

argparse-learn]# python argparse-3.py =h
usage: learn_argparse_3 [-h] [--help] [...] [what you want???] other men live ti eat, while i eat to live -- socrates love rules his kingdom
without a sword -- herbert optional arguments:
=h, ==help show this help message and exit
--parent PARENT parent (default: [1, 2, 3, 4, 5, 6]) All for one, one for all -- dumas we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller

8、fromfile_prefix_chars 有时候将从文件中读取参数,如果设置fromfile_prefix_chars参数的话,解析器会将带有这个前缀的参数当作文件处理

import argparse
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('-f')
print parser.parse_args(['-f', 'foo', '@args.txt'])

9、argument_default 给所有没有默认值的参数设置默认值。

import argparse
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("--parent", type=int,default=[1, 2, 3, 4, 5, 6,],help='parent')
parser = argparse.ArgumentParser(prog="learn_argparse_3",
usage="%(prog)s [-h] [--help] [...] [what you want???]",
description='''
other men live ti eat, while i eat to live -- socrates love rules his kingdom without a sword -- herbert''',
epilog='''
All for one, one for all -- dumas
we soon believe what we desire -- chaucer
the darkest hour is that before the dawn -- fuller''',
parents=[parent_parser],
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prefix_chars='-',
fromfile_prefix_chars='$',
argument_default='The default value for all arguments')
parser.add_argument('--argument_default')
print parser.parse_args()

运行结果:

Namespace(argument_default='The default value for all arguments', parent=[1, 2, 3, 4, 5, 6])

10、conflict_handler argumentparser对象不允许传入俩个相同的参数,否则会报错,通过设置conflict_handler为resolve,可以用新的参数覆盖旧的同名参数

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_4",
conflict_handler='resolve')
parser.add_argument('-b','--boy',help='boy')
parser.add_argument('--boy',help='girl')
parser.print_help()

运行结果:

argparse-learn]# python argparse-4.py
usage: learn_argparse_4 [-h] [-b BOY] [--boy BOY] optional arguments:
-h, --help show this help message and exit
-b BOY boy
--boy BOY girl

11、add_help默认情况下ArgumentParser对象对自动添加-h/--help选项,可设置add_help=False取消

import argparse
parser = argparse.ArgumentParser(prog="learn_argparse_4",
add_help=False)
parser.add_argument('boy',help='good boy help')
parser.print_help()

运行结果:

argparse-learn]# python argparse-4.py
usage: learn_argparse_4 boy positional arguments:
boy good boy help

python argparse(参数解析)模块学习(一)的更多相关文章

  1. python argparse(参数解析模块)

    这是一个参数解析,可以用它快捷的为你的程序生成参数相关功能 import argparse(导入程序参数模块) # 创建argparse对象,并将产品简要说明加入show = '程序说明' ===&g ...

  2. python之参数解析模块argparse

    2.7之后python不再对optparse模块进行扩展,python标准库推荐使用argparse模块对命令行进行解析. 简单入门 先来看个例子: argparse_test.py: import ...

  3. python命令行参数解析模块argparse和docopt

    http://blog.csdn.net/pipisorry/article/details/53046471 还有其他两个模块实现这一功能,getopt(等同于C语言中的getopt())和弃用的o ...

  4. python命令行解析模块--argparse

    python命令行解析模块--argparse 目录 简介 详解ArgumentParser方法 详解add_argument方法 参考文档: https://www.jianshu.com/p/aa ...

  5. $命令行参数解析模块argparse的用法

    argparse是python内置的命令行参数解析模块,可以用来为程序配置功能丰富的命令行参数,方便使用,本文总结一下其基本用法. 测试脚本 把以下脚本存在argtest.py文件中: # codin ...

  6. Python命令行参数解析模块getopt使用实例

    Python命令行参数解析模块getopt使用实例 这篇文章主要介绍了Python命令行参数解析模块getopt使用实例,本文讲解了使用语法格式.短选项参数实例.长选项参数实例等内容,需要的朋友可以参 ...

  7. Python 日期时间处理模块学习笔记

    来自:标点符的<Python 日期时间处理模块学习笔记> Python的时间处理模块在日常的使用中用的不是非常的多,但是使用的时候基本上都是要查资料,还是有些麻烦的,梳理下,便于以后方便的 ...

  8. Python命令行参数解析模块argparse

    当写一个Python脚本时经常会遇到不同参数不同功能的情况,如何做一个更好看的命令帮助信息以及对命令参数解析呢? 这就需要使用argparse模块 #!/usr/bin/env python # -* ...

  9. python之命令行参数解析模块argparse

    """argparse模块使得写用户友好性命令行接口很容易,程序定义所需要的参数,argparse会从ays.argv中提取出这些参数.argparse模块也能自动的产生 ...

  10. Day5 - Python基础5 常用模块学习

    Python 之路 Day5 - 常用模块学习   本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shel ...

随机推荐

  1. python多种格式数据加载、处理与存储

    多种格式数据加载.处理与存储 实际的场景中,我们会在不同的地方遇到各种不同的数据格式(比如大家熟悉的csv与txt,比如网页HTML格式,比如XML格式),我们来一起看看python如何和这些格式的数 ...

  2. 3分钟,9个Q&amp&semi;A让你快速知道Docker到底是什么

    不论是Google.Amazon.Microsoft.VMware都纷纷拥戴,加入Docker和Container所掀起的新时代云端虚拟化行列,这两项技术成为了IT界的新趋势.Docker和Conta ...

  3. maven Connection refused&colon; connect

    现象: 本地可以访问错误提示中的地址.但使用maven无法下载jar包. 环境: 浏览器上网需要使用代理 解决方法: 设置成正常代理可以.具体方法可以下载一个代理工具.只要IE配置成能直接访问http ...

  4. redis的文件事件处理器

    前言     C10K problem提出了一个问题,如果1w个客户端连接到server上,间歇性的发送消息,有哪些好的方案?     其中的一种方案是,每个线程处理多个客户端,使用异步I/O和就绪通 ...

  5. spoj 1812 LCS2(SAM&plus;DP)

    [题目链接] http://www.spoj.com/problems/LCS2/en/ [题意] 求若干个串的最长公共子串. [思路] SAM+DP 先拿个串建个SAM,然后用后面的串匹配,每次将所 ...

  6. android HttpGet 另开线程获取网络数据问题

    android跨线程通讯可以使用android.os.Handler-android.os.Message这两类对象完成. public static void getResultForHttpGet ...

  7. 【HDU】1754 I hate it ——线段树 单点更新 区间最值

    I Hate It Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  8. boost计算随机数和计算crc32简单示例 - jwybobo2007的专栏 - 博客频道 - CSDN&period;NET

    boost计算随机数和计算crc32简单示例 - jwybobo2007的专栏 - 博客频道 - CSDN.NET     boost::crc_32_type crc32;       crc32. ...

  9. Nginx安装手冊以及图片server部署

    1.      安装gcc yum install gcc 2.      安装pcre,pcre-devel 在zhoulh文件夹下建立source build文件夹 mkdir source bu ...

  10. 5、范围标签&lt&semi;fieldset&gt&semi;&lt&semi;&sol;fieldset&gt&semi;

    <fieldset style="border:0;border:1px solid red;"> <legend style="background- ...