前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python argparse模块粗略了

python argparse模块粗略了

作者头像
py3study
发布2020-01-15 11:21:51
4770
发布2020-01-15 11:21:51
举报
文章被收录于专栏:python3

https://docs.python.org/2.7/library/argparse.html#module-argparse

看了一下python对于参数的处理,了解了argparse这个模块

import argparse

parser = argparse.ArgumentParser(description="calculate X to the power of Y")

group = parser.add_mutually_exclusive_group()

group.add_argument("-v", "--verbose", action="store_true")

group.add_argument("-q", "--quiet", action="store_true")

parser.add_argument("x", type=int, help="the base")

parser.add_argument("y", type=int, help="the exponent")

args = parser.parse_args()

answer = args.x**args.y

if args.quiet:

print answer

elif args.verbose:

print "{} to the power {} equals {}".format(args.x, args.y, answer)

else:

print "{}^{} == {}".format(args.x, args.y, answer)

第一步:定义一个argparse对象

使用argparse.ArgumentParser()来定义argparse对象

具体参数详见https://docs.python.org/2.7/library/argparse.html#argumentparser-objects

class argparse.ArgumentParser(prog=Noneusage=Nonedescription=Noneepilog=Noneparents=[]formatter_class=argparse.HelpFormatterprefix_chars='-'fromfile_prefix_chars=Noneargument_default=Noneconflict_handler='error'add_help=True)

  • 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)

第二步:添加参数arguments

使用add_argument()来添加参数

参数分为Positional Argument 和 Optional Argument

区分Positional Argument 和 Optional Argument 通过上文中argparse.ArgumentParser()的prefix_chars来定义,默认为“-”

具体参数详见https://docs.python.org/2.7/library/argparse.html#argumentparser-objects

class argparse.ArgumentParser(prog=Noneusage=Nonedescription=Noneepilog=Noneparents=[]formatter_class=argparse.HelpFormatterprefix_chars='-'fromfile_prefix_chars=Noneargument_default=Noneconflict_handler='error'add_help=True)

Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:

  • 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)

第三步:将参数转化为指定命名空间的属性

parser.parse_args()来实现这一功能

具体参数详见https://docs.python.org/2.7/library/argparse.html#the-parse-args-method

在示例代码中-v -q 为同组的互斥参数add_mutually_exclusive_group(),两个参数只可以出现一个,但不是必须出现。https://docs.python.org/2.7/library/argparse.html#mutual-exclusion

示例代码演示

1、

python ex1.py -h

usage: ex1.py [-h] [-v | -q] x y

calculate X to the power of Y

positional arguments:

x              the base

y              the exponent

optional arguments:

-h, --help     show this help message and exit

-v, --verbose

-q, --quiet

2、

python ex1.py 2 3

2^3 == 8

3、

python ex1.py 2 3  -v

2 to the power 3 equals 8

4、

python ex1.py 2 3  -q

8

5、

python ex1.py

usage: ex1.py [-h] [-v | -q] x y

ex1.py: error: too few arguments

6、

python ex1.py 2 3 -v -q

usage: ex1.py [-h] [-v | -q] x y

ex1.py: error: argument -q/--quiet: not allowed with argument -v/--verbose

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/06/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档