argparse是python的一个命令行参数模块,可以解析命令行参数,生成帮助等。

你可以这样使用它:

  1. #!/usr/bin/python
  2. from argparse import ArgumentParser
  3. p = ArgumentParser(usage='it is usage tip', description='this is a test')
  4. p.add_argument('--one', default=1, type=int, help='the first argument')
  5. p.add_argument('--two, default=2, type=int, help='the second argument')
  6. p.add_argument('--docs-dir, default="./", help='document directory')
  7. args = p.parse_args()
  8. #可以打印出来查看
  9. print args
  10. #打印某一个参数
  11. print args.one
  12. print args.docs_dir   #经过parse_args()函数后参数名称去掉了前面的"--",所有的"-"转换为"_"

这个文件的名称叫做test.py , 你可以这样运行它:

./test.py

想要查看是否有哪些参数可以:

./test.py --help  或者  ./test.py -h

会打印出以下信息:

  1. usage: it is usage tip
  2. this is a test
  3. optional arguments:
  4. -h, --help  show this help message and exit
  5. --one ONE   the first argument
  6. --two TWO   the second argument
  7. --docs-dir DOCS_DIR   document directory

然后就可以带参数运行程序:

./test.py --one 10 --two 20 --docs-dir /opt/docs/

但是在这种情况下:“如果运行程序时带了一个不认识的参数”,就会报错:

./test.py --p 235

  1. usage: it is usage tip
  2. test.py: error: unrecognized arguments: ./test.py --p 235

有时我们不希望这样,我们的需求是:只提取有用的参数,不认识的参数丢弃但并不需要报错".

这时程序可以这样写:

  1. #!/usr/bin/python
  2. import sys
  3. from argparse import ArgumentParser
  4. p = ArgumentParser(usage='it is usage tip', description='this is a test')
  5. p.add_argument('--one', default=1, type=int, help='the first argument')
  6. p.add_argument('--two, default=2, type=int, help='the second argument')
  7. p.add_argument('--docs-dir, default="./", help='document directory')
  8. # 这个函数将认识的和不认识的参数分开放进2个变量中
  9. args, remaining = p.parse_known_args(sys.argv)
  10. #可以打印出来查看
  11. print args
  12. print remaining

再次运行程序:

./test.py --p 235

这个时候就会打印出:

  1. Namespace(docs_dir='./', one=1, two=2)
  2. ['./test.py', '--p', '235']

最新文章

  1. CG Rendering v.s. Browser Rendering
  2. VS.net 2013中使用Git建立源代码管理 版本管理
  3. RGB颜色矩提取算法——Matlab
  4. JS中级 - 01:DOM节点
  5. Python操作文件文档
  6. SCOPE_IDENTITY的作用
  7. 发现了一个制作iOS图标的利器
  8. UIcollectionView的使用(首页的搭建1)
  9. Restart-ServiceEx.psm1
  10. Nodejs in Visual Studio Code 08.IIS
  11. Symfony命令行
  12. 如何获取本地html文件的标题
  13. 内存排查 valgrind
  14. GitHub 简易使用
  15. java.lang.ArrayIndexOutOfBoundsException
  16. STM32学习笔记(一):跑马灯
  17. [NOI2009]诗人小G(dp + 决策单调性优化)
  18. Linux centos7. 配置安装Oracle
  19. mysql 开发进阶篇系列 27 数据库字符集设置
  20. PostgreSQL Q&A: Building an Enterprise-Grade PostgreSQL Setup Using Open Source Tools

热门文章

  1. PAT (Advanced Level) 1112. Stucked Keyboard (20)
  2. ubuntu 下重装mysql若干问题
  3. SEO优化之 主页上加上nofollow
  4. 使用maven开发过程中,pom报的一些错的解决方法
  5. BZOJ 1196 二分答案+并查集
  6. subversion javahl
  7. .net杂记
  8. Counting Intersections
  9. PAT (Advanced Level) 1018. Public Bike Management (30)
  10. php 设计模式系列(一)