I was trying out optparse
and this is my initial script.
#!/usr/bin/env python
import os, sys
from optparse import OptionParser
parser = Optio
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)
Your solution looks reasonable to me. Comments:
month_abbr
into a tuple; it should work fine without the tuple()
raise OptionValueError
if you find a problem)optparse
is deprecated; you should use argparse
in both python2 and python3
http://docs.python.org/library/argparse.html#module-argparse