栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python学习笔记——argparse中的action=store

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python学习笔记——argparse中的action=store

前言

Python的命令行参数解析模块学习。

示例

参数解析模块支持action参数,这个参数可以设置为’store_true’、‘store_false’、'store_const’等。
例如下面这行代码,表示如果命令行参数中出现了"–PARAM_NAME",就把PARAM_NAME设置为True,否则为False。

parser.add_argument("--PARAM_NAME", action="store_true", help="HELP_INFO")
官方文档

‘store_true’ and ‘store_false’ - These are special cases of ‘store_const’ used for storing the values True and False respectively. In addition, they create default values of False and True respectively. For example:

‘store_true’ 和 ‘store_false’ -这两个是’store_const’的特例,分别用来设置True和False。另外,他们还会创建默认值。

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_true')
>>> parser.add_argument('--bar', action='store_false')
>>> parser.add_argument('--baz', action='store_false')
>>> parser.parse_args('--foo --bar'.split())
Namespace(foo=True, bar=False, baz=True)

多了解一点儿 自定义

你可以通过给定一个Action的子类或其他实现了相同接口的对象,来指定一个任意的action。
BooleanOptionalAction就是一个可以使用的action,它增加了布尔action特性,支持--foo和--no-foo的形式。

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action=argparse.BooleanOptionalAction)
>>> parser.parse_args(['--no-foo'])
Namespace(foo=False)
小结

'--foo', action='store_true',可以很方便地实现布尔类型的参数。

思考

Python3 开始,很多内置模块都转向了面向对象范式。
对于早期开始使用Python的用户来说,见到的代码更多是面向过程或者是函数风格的,例如,从Google开源的一些项目可以看到很多Python 2.x的代码风格。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/923546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号