argparse 命令含参数模块

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

你可以这样使用它:

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

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

                                                ./test.py

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

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

会打印出以下信息:

命令行代码  收藏代码
  1. usage: it is usage tip  
  2.   
  3. this is a test  
  4.   
  5. optional arguments:  
  6.   -h, --help  show this help message and exit  
  7.   --one ONE   the first argument  
  8.   --two TWO   the second argument  
  9.   --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  

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

这时程序可以这样写:

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

再次运行程序:

                                      ./test.py --p 235

这个时候就会打印出:

命令行代码  收藏代码
  1. Namespace(docs_dir='./', one=1, two=2)  
  2. ['./test.py', '--p', '235']  
原文地址:https://www.cnblogs.com/skying555/p/5223956.html