Python模块之argparse

在编程语言中我们经常需要从命令行读取参数,解析参数的方式多种多样。


第一种:直接给定

              这种方法虽然实现起来方便,但是灵活性非常差,每次都需要打开python文件修改参数。


第二种: 手动解析

import sys
def TestSys():
    for arg in sys.argv[1: ] :        #对输入的第二个参数到最后,arg[0] 为第一个参数
    print arg 


第三种:自动解析(这里就要用到Python中的argparse模块,本篇文章也是主要讲这个模块)


1.创建解析器

import argparse
parser = argparse.ArgumentParser()

创建一个ArgumentParser实例对象,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)

prog:程序的名字,默认为sys.argv[0],用来在help信息中描述程序的名称。

1
2
3
4
5
6
>>> parser = argparse.ArgumentParser(prog= 'myprogram' )
>>> parser.print_help()
usage: myprogram [-h]
 
optional arguments:
  -h, --help  show  this  help message and exit

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

1
2
3
4
5
6
7
8
9
10
11
12
>>> parser = argparse.ArgumentParser(prog= 'PROG' , usage= '%(prog)s [options]' )
>>> parser.add_argument( '--foo' , nargs= '?' , help= 'foo help' )
>>> parser.add_argument( 'bar' , nargs= '+' , help= 'bar help' )
>>> parser.print_help()
usage: PROG [options]
 
positional arguments:
  bar          bar help
 
optional arguments:
  -h, --help   show  this  help message and exit
  --foo [FOO]  foo help

description:help信息前的文字。

epilog:help信息之后的信息

1
2
3
4
5
6
7
8
9
10
11
12
>>> parser = argparse.ArgumentParser(
...     description= 'A foo that bars' ,
...     epilog= "And that's how you'd foo a bar" )
>>> parser.print_help()
usage: argparse.py [-h]
 
A foo that bars
 
optional arguments:
  -h, --help  show  this  help message and exit
 
And that 's how you' d foo a bar

parents:由ArgumentParser对象组成的列表,它们的arguments选项会被包含到新ArgumentParser对象中。

1
2
3
4
5
6
7
>>> parent_parser = argparse.ArgumentParser(add_help=False)
>>> parent_parser.add_argument( '--parent' , type= int )
 
>>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
>>> foo_parser.add_argument( 'foo' )
>>> foo_parser.parse_args([ '--parent' '2' 'XXX' ])
Namespace(foo= 'XXX' , parent=2)

formatter_class:help信息输出的格式,

prefix_chars:参数前缀,默认为'-'

1
2
3
4
5
>>> parser = argparse.ArgumentParser(prog= 'PROG' , prefix_chars= '-+'
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值