understanding OptionParser

后端 未结 3 1748
北荒
北荒 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)
    
    0 讨论(0)
  • 2020-12-19 02:13

    Your solution looks reasonable to me. Comments:

    • I don't understand why you turn month_abbr into a tuple; it should work fine without the tuple()
    • I'd recommend checking for invalid month value (raise OptionValueError if you find a problem)
    • if you really want the user to input exactly "01", "02", ..., or "12", you could use the "choice" option type; see option types documentation
    0 讨论(0)
  • 2020-12-19 02:17

    optparse is deprecated; you should use argparse in both python2 and python3

    http://docs.python.org/library/argparse.html#module-argparse

    0 讨论(0)
提交回复
热议问题