understanding OptionParser

后端 未结 3 1754
北荒
北荒 2020-12-19 01:41

I was trying out optparse and this is my initial script.

#!/usr/bin/env python

import os, sys
from optparse import OptionParser

parser = Optio         


        
3条回答
  •  太阳男子
    2020-12-19 01:53

    Just to illustrate the choices-option of argparse.ArgumentParser's add_argument()-method:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    import sys
    from argparse import ArgumentParser
    from datetime import date
    
    parser = ArgumentParser()
    
    parser.add_argument("-u", "--user", default="Max Power", help="Username")
    parser.add_argument("-m", "--month", default="{:02d}".format(date.today().month),
                        choices=["01","02","03","04","05","06",
                                 "07","08","09","10","11","12"],
                        help="Numeric value of the month")
    
    try:
        args = parser.parse_args()
    except:
        parser.error("Invalid Month.")
        sys.exit(0) 
    
    print  "The month is {} and the User is {}".format(args.month, args.user)
    

提交回复
热议问题