Option parser question - reading options from file as well as command line

Andrew Robert andrew.arobert at gmail.com
Tue May 16 18:44:21 EDT 2006


Max Erickson wrote:

> I don't know much about optparse, but since I was bored:
> 
>>>> help(o.parse_args)
> Help on method parse_args in module optparse:
> 
> parse_args(self, args=None, values=None) method of 
> optparse.OptionParser instance
>     parse_args(args : [string] = sys.argv[1:],
>                values : Values = None)
>     -> (values : Values, args : [string])
>     
>     Parse the command-line options found in 'args' (default:
>     sys.argv[1:]).  Any errors result in a call to 'error()', which
>     by default prints the usage message to stderr and calls
>     sys.exit() with an error message.  On success returns a pair
>     (values, args) where 'values' is an Values instance (with all
>     your option values) and 'args' is the list of arguments left
>     over after parsing options.
> 
>>>> o.parse_args('seven')
> Traceback (most recent call last):
>   File "<pyshell#15>", line 1, in ?
>     o.parse_args('seven')
>   File "C:\bin\Python24\lib\optparse.py", line 1275, in parse_args
>     stop = self._process_args(largs, rargs, values)
>   File "C:\bin\Python24\lib\optparse.py", line 1322, in _process_args
>     del rargs[0]
> TypeError: object doesn't support item deletion
> 
> That's the result of poking an optionParser instance in Idle. 
> parse_args is expecting something that looks like sys.argv[1:], which 
> is a list. You are passing it a string.
> 
> max
> 
Yup.. the code now works as:

parser = OptionParser()

if len(sys.argv) == 2:
    lines = open(sys.argv[1],"rb").readlines()
    for line in lines:
	    line=line.strip()
	    if not line:
		    continue
	    short, long, dest, help, default = line.split(";")
	    help = "\t\t" + help # Prepend tabs to help message
	    parser.add_option(short, long, dest=dest, help=help, default=default)
else:
    parser.add_option("-m","--qmanager", dest="qmanager",
                help="\t\tQueue Manager to inquire against"),
    parser.add_option("-q","--queue", dest="queue",
                help="\t\tQueue the message will be sent to"),
    parser.add_option("-d","--dest", dest="dest",
                help="\t\tDestination File Name"),
    parser.add_option("-f", "--file",
                action="store", type="string", dest="filename",
                help="File to be transmitted", metavar="FILE")

(options, args) = parser.parse_args()


thanks all for the insight



More information about the Python-list mailing list