Understanding OptionParser

I tried optparse and this is my original script.

 #!/usr/bin/env python import os, sys from optparse import OptionParser parser = OptionParser() usage = "usage: %prog [options] arg1 arg2" parser.add_option("-d", "--dir", type="string", help="List of directory", dest="inDir", default=".") parser.add_option("-m", "--month", type="int", help="Numeric value of the month", dest="mon") options, arguments = parser.parse_args() if options.inDir: print os.listdir(options.inDir) if options.mon: print options.mon def no_opt() print "No option has been given!!" 

Now this is what I am trying to do:

  • If the argument is not specified with the parameter, it will take the default value. ie myScript.py -d will simply list the current directory or -m without any argument, the current month will be taken as an argument.
  • For "-month" only 01 to 12 is allowed as an argument
  • Want to combine several options to perform different tasks, i.e. myScript.py -d this_dir -m 02 will do something different than -d and -m as an individual.
  • It will print "No option is given !!" ONLY if the script option is missing.

Are they doable? I visited doc.python.org for possible answers, but as a beginner python, I lost myself in the pages. He greatly appreciated your help; thanks in advance. Hooray!!


Update: 16/01/11

I think I'm still missing something. This is now in my script.

 parser = OptionParser() usage = "usage: %prog [options] arg1 arg2" parser.add_option("-m", "--month", type="string", help="select month from 01|02|...|12", dest="mon", default=strftime("%m")) parser.add_option("-v", "--vo", type="string", help="select one of the supported VOs", dest="vos") options, arguments = parser.parse_args() 

It's my goal:

  • run the script without any option, will return option.mon [working]
  • run the script with the -m option, returning option.mon [working]
  • run the script with the ONLY -v option, ONLY return option.vos [does not work at all]
  • run the script with -m and -v, do another thing [before reaching the point]

When I run the script with only the -m option, option.mon is printed option.mon , and then option.vos , which I don't want at all. I really appreciate if someone can put me in the right direction. Hooray!!


3rd update
  #!/bin/env python from time import strftime from calendar import month_abbr from optparse import OptionParser # Set the CL options parser = OptionParser() usage = "usage: %prog [options] arg1 arg2" parser.add_option("-m", "--month", type="string", help="select month from 01|02|...|12", dest="mon", default=strftime("%m")) parser.add_option("-u", "--user", type="string", help="name of the user", dest="vos") options, arguments = parser.parse_args() abbrMonth = tuple(month_abbr)[int(options.mon)] if options.mon: print "The month is: %s" % abbrMonth if options.vos: print "My name is: %s" % options.vos if options.mon and options.vos: print "I'm '%s' and this month is '%s'" % (options.vos,abbrMonth) 

This is what the script returns when launched with various parameters:

 # ./test.py The month is: Feb # # ./test.py -m 12 The month is: Dec # # ./test.py -m 3 -u Mac The month is: Mar My name is: Mac I'm 'Mac' and this month is 'Mar' # # ./test.py -u Mac The month is: Feb My name is: Mac I'm 'Mac' and this month is 'Feb' 

I like only:

  1. `I'm 'Mac' and this month is 'Mar'` - as *result #3* 2. `My name is: Mac` - as *result #4* 

what am I doing wrong? Hooray!!


4th update:

Answering myself: in this way, I can get what I'm looking for, but I'm still not impressed.

 #!/bin/env python import os, sys from time import strftime from calendar import month_abbr from optparse import OptionParser def abbrMonth(m): mn = tuple(month_abbr)[int(m)] return mn # Set the CL options parser = OptionParser() usage = "usage: %prog [options] arg1 arg2" parser.add_option("-m", "--month", type="string", help="select month from 01|02|...|12", dest="mon") parser.add_option("-u", "--user", type="string", help="name of the user", dest="vos") (options, args) = parser.parse_args() if options.mon and options.vos: thisMonth = abbrMonth(options.mon) print "I'm '%s' and this month is '%s'" % (options.vos, thisMonth) sys.exit(0) if not options.mon and not options.vos: options.mon = strftime("%m") if options.mon: thisMonth = abbrMonth(options.mon) print "The month is: %s" % thisMonth if options.vos: print "My name is: %s" % options.vos 

and now this gives me exactly what I was looking for:

 # ./test.py The month is: Feb # ./test.py -m 09 The month is: Sep # ./test.py -u Mac My name is: Mac # ./test.py -m 3 -u Mac I'm 'Mac' and this month is 'Mar' 

Is this the only way to do this? Doesn't look like the β€œbest way” to me. Hooray!!

+7
source share
3 answers

Your decision seems reasonable to me. Comments:

  • I do not understand why you are turning month_abbr into a tuple; it should work fine without tuple()
  • I would recommend checking for an invalid month value ( raise OptionValueError if you find a problem)
  • If you really want the user to enter exactly β€œ01”, β€œ02”, ... or β€œ12”, you could use the option type β€œSelect”; see parameter type documentation
+1
source

optparse deprecated; you should use argparse both python2 and python3

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

0
source

Just to illustrate the selection option argparse.ArgumentParser add_argument () is a 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
source

All Articles