argparse 命令含参数模块
2024-09-02 05:29:21
argparse是python的一个命令行参数模块,可以解析命令行参数,生成帮助等。
你可以这样使用它:
- #!/usr/bin/python
- from argparse import ArgumentParser
- p = ArgumentParser(usage='it is usage tip', description='this is a test')
- p.add_argument('--one', default=1, type=int, help='the first argument')
- p.add_argument('--two, default=2, type=int, help='the second argument')
- p.add_argument('--docs-dir, default="./", help='document directory')
- args = p.parse_args()
- #可以打印出来查看
- print args
- #打印某一个参数
- print args.one
- print args.docs_dir #经过parse_args()函数后参数名称去掉了前面的"--",所有的"-"转换为"_"
这个文件的名称叫做test.py , 你可以这样运行它:
./test.py
想要查看是否有哪些参数可以:
./test.py --help 或者 ./test.py -h
会打印出以下信息:
- usage: it is usage tip
- this is a test
- optional arguments:
- -h, --help show this help message and exit
- --one ONE the first argument
- --two TWO the second argument
- --docs-dir DOCS_DIR document directory
然后就可以带参数运行程序:
./test.py --one 10 --two 20 --docs-dir /opt/docs/
但是在这种情况下:“如果运行程序时带了一个不认识的参数”,就会报错:
./test.py --p 235
- usage: it is usage tip
- test.py: error: unrecognized arguments: ./test.py --p 235
有时我们不希望这样,我们的需求是:只提取有用的参数,不认识的参数丢弃但并不需要报错".
这时程序可以这样写:
- #!/usr/bin/python
- import sys
- from argparse import ArgumentParser
- p = ArgumentParser(usage='it is usage tip', description='this is a test')
- p.add_argument('--one', default=1, type=int, help='the first argument')
- p.add_argument('--two, default=2, type=int, help='the second argument')
- p.add_argument('--docs-dir, default="./", help='document directory')
- # 这个函数将认识的和不认识的参数分开放进2个变量中
- args, remaining = p.parse_known_args(sys.argv)
- #可以打印出来查看
- print args
- print remaining
再次运行程序:
./test.py --p 235
这个时候就会打印出:
- Namespace(docs_dir='./', one=1, two=2)
- ['./test.py', '--p', '235']
最新文章
- CG Rendering v.s. Browser Rendering
- VS.net 2013中使用Git建立源代码管理 版本管理
- RGB颜色矩提取算法——Matlab
- JS中级 - 01:DOM节点
- Python操作文件文档
- SCOPE_IDENTITY的作用
- 发现了一个制作iOS图标的利器
- UIcollectionView的使用(首页的搭建1)
- Restart-ServiceEx.psm1
- Nodejs in Visual Studio Code 08.IIS
- Symfony命令行
- 如何获取本地html文件的标题
- 内存排查 valgrind
- GitHub 简易使用
- java.lang.ArrayIndexOutOfBoundsException
- STM32学习笔记(一):跑马灯
- [NOI2009]诗人小G(dp + 决策单调性优化)
- Linux centos7. 配置安装Oracle
- mysql 开发进阶篇系列 27 数据库字符集设置
- PostgreSQL Q&;A: Building an Enterprise-Grade PostgreSQL Setup Using Open Source Tools
热门文章
- PAT (Advanced Level) 1112. Stucked Keyboard (20)
- ubuntu 下重装mysql若干问题
- SEO优化之 主页上加上nofollow
- 使用maven开发过程中,pom报的一些错的解决方法
- BZOJ 1196 二分答案+并查集
- subversion javahl
- .net杂记
- Counting Intersections
- PAT (Advanced Level) 1018. Public Bike Management (30)
- php 设计模式系列(一)