OptionParser模块学习

from optparse import OptionParser
import sys

useage = []
test_parser = OptionParser(usage="%prog [options]",version="%prog 1.0",description="脚本概括:学习otionparser")


test_parser.add_option("-f","--file",
                       # 这里的意思可以-f选项传递参数,也可以使用--file选项来传递参数
                       action="store",
                       # 说实话,这里没弄懂
                       dest="file_name",
                       # dest的意思-f选项或者--file选项后面传递的值会赋值给你file_name这个变量中,但是不能直接打印,后面会介绍如何打印
                       default="test_file",
                       # 如果-f选项后不传递任何的值,则默认值就是defalut赋值的值
                       help="input filaname",
                       # -f选项的帮助信息
                       type="string")
                        # -f选项后面的值的类型
test_parser.add_option("-d","--decv",
                       action="store",
                       dest="decv_name",
                       default="test_decv",
                       help="input decv name",
                       type="string")

if __name__ == '__main__':

    (options,args) = test_parser.parse_args(sys.argv[:])
   #用来接收选项的值
    print(options.file_name)
    print(options.decv_name)
    print(args)

  

脚本测试:

1、测试-h选项

E:python重头开始day41>python test_optionparser.py -h
Usage: test_optionparser.py [options]

脚本概括:学习otionparser

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -f FILE_NAME, --file=FILE_NAME
                        input filaname
  -d DECV_NAME, --decv=DECV_NAME
                        input decv name

E:python重头开始day41>

  

2、测试--version选项

E:python重头开始day41>python test_optionparser.py --version
test_optionparser.py 1.0

E:python重头开始day41>

  

3、测试默认参数的选项

E:python重头开始day41>python test_optionparser.py
test_file
test_decv
['test_optionparser.py']

  

4、测试-f和-d选项

E:python重头开始day41>python test_optionparser.py -d "dddd" -f "fffff"
fffff
dddd
['test_optionparser.py']

E:python重头开始day41>

  

5、测试--file和--decv选项

E:python重头开始day41>python test_optionparser.py --file "ccccc" -d "aaaaa"
ccccc
aaaaa
['test_optionparser.py']

  

原文地址:https://www.cnblogs.com/bainianminguo/p/8515784.html