Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

optparse: best way

1 view
Skip to first unread message

hiral

unread,
Jun 8, 2010, 4:38:23 AM6/8/10
to
Hi,

I am using optparser to do following...

Command syntax:
myscript -o[exension] other_arguments
where; extension can be 'exe', 'txt', 'pdf', 'ppt' etc.


Now to parse this, I am doing following...

parser.add_option("-oexe', dest=exe_file...)
parser.add_option("-otxt', dest=txt_file...)
parser.add_option("-opdf', dest=pdf_file...)
parser.add_option("-oppt', dest=ppt_file...)

The above way is the most simple way to parser options.
Can you please suggest any other best way / optimized way to parse
these kind of options.

Thank you in advance.

Thomas Jollans

unread,
Jun 8, 2010, 5:03:33 AM6/8/10
to pytho...@python.org
On 2010-06-08 10:38, hiral wrote:
> Hi,
>
> I am using optparser to do following...
>
> Command syntax:
> myscript -o[exension] other_arguments
> where; extension can be 'exe', 'txt', 'pdf', 'ppt' etc.
>
>
> Now to parse this, I am doing following...
>
> parser.add_option("-oexe', dest=exe_file...)
> parser.add_option("-otxt', dest=txt_file...)
> parser.add_option("-opdf', dest=pdf_file...)
> parser.add_option("-oppt', dest=ppt_file...)
>
The format of options you're using here is totally non-standard. Yes,
many programs traditionally use it, but it's incompatible to the usual
UNIX and GNU recommendations. I've never actually heard of optparser,
but I'd expect it to have the usual limitations: GNU getopt (distributed
with Python by the way), I'm using the example because I know it fairly
well, lets you use either "-o exe" or "--output-format=exe" (GNU-style
long option) here.

So I'd recommend you either live with "-o exe" and the like, or you'll
probably have to write your own option parsing routine, which shouldn't
be too difficult, but really isn't worth it IMHO.

-- Thomas

Jean-Michel Pichavant

unread,
Jun 8, 2010, 6:03:27 AM6/8/10
to hiral, pytho...@python.org

Here's a solution:

import optparse

class Process:
PREFIX = 'dispatch_'
@staticmethod
def undef():
print 'unsupported file type'
@staticmethod
def dispatch_exe():
print 'Hello exe file !'

def dispatchFileType(option, opt, value, parser):
"""Called by the parser, -o option."""
# call the corresponding method in the process method
getattr(Process, Process.PREFIX + value, Process.undef)()

parser = optparse.OptionParser()
parser.add_option("-o", "--output-fileType", type="string",
action="callback", callback=dispatchFileType)

options, args = parser.parse_args()


Cheers,

JM


Ben Finney

unread,
Jun 8, 2010, 6:15:35 AM6/8/10
to
hiral <hiralsm...@gmail.com> writes:

> Command syntax:
> myscript -o[exension] other_arguments
> where; extension can be 'exe', 'txt', 'pdf', 'ppt' etc.

It's more generally applicable to refer to that as a “suffix” for the
filename, and specify the full suffix including the full-stop (‘.’)
character.

What your example suggests is that you want to have an option, “-o”,
which takes an argument which is the output suffix. I'd prefer to also
have a long option with a descriptive name for the same purpose.

So here's my interpretation::

>>> import optparse
>>> parser = optparse.OptionParser()
>>> parser.add_option(
... "-o", "--output-suffix",
... dest='out_suffix', metavar="SUFFIX",
... help="Specify SUFFIX as the suffix of the output filename.")
<Option at 0xf78d4350: -o/--output-suffix>
>>> print parser.format_option_help()
Options:
-h, --help show this help message and exit
-o SUFFIX, --output-suffix=SUFFIX
Specify SUFFIX as the suffix of the output filename.

> Can you please suggest any other best way / optimized way to parse
> these kind of options.

For testing the above, I make use of the ‘shlex’ module to split a
command-line string into separate arguments as the OptionParser will
expect::

>>> import shlex

The OptionParser instance, as the help message above explains, allows
the usual ways of specifying an argument to that option::

>>> cmdline_args = shlex.split("fooprog -o .exe spam beans")
>>> (opts, args) = parser.parse_args(cmdline_args[1:])
>>> opts.out_suffix
'.exe'

>>> cmdline_args = shlex.split("fooprog -o.txt spam beans")
>>> (opts, args) = parser.parse_args(cmdline_args[1:])
>>> opts.out_suffix
'.txt'

>>> cmdline_args = shlex.split("fooprog --output-suffix .pdf spam beans")
>>> (opts, args) = parser.parse_args(cmdline_args[1:])
>>> opts.out_suffix
'.pdf'

>>> cmdline_args = shlex.split("fooprog --output-suffix=.ppt spam beans")
>>> (opts, args) = parser.parse_args(cmdline_args[1:])
>>> opts.out_suffix
'.ppt'

--
\ “I used to be a proofreader for a skywriting company.” —Steven |
`\ Wright |
_o__) |
Ben Finney

Michele Simionato

unread,
Jun 8, 2010, 6:20:06 AM6/8/10
to

Use plac: http://pypi.python.org/pypi/plac
Here is an example:

import plac

EXTENSIONS = ('exe', 'txt', 'pdf', 'ppt')

@plac.annotations(
ext=('a valid extension', 'option', 'o', None, EXTENSIONS))
def main(ext, *args):
"Do something"

if __name__ == '__main__':
plac.call(main)

$ python myscript.py -h
usage: myscript.py [-h] [-o {exe,txt,pdf,ppt}] [args [args ...]]

Do something

positional arguments:
args

optional arguments:


-h, --help show this help message and exit

-o, --ext {exe,txt,pdf,ppt}
a valid extension

Peter Otten

unread,
Jun 8, 2010, 6:31:42 AM6/8/10
to
hiral wrote:

You could limit the value for the -o option with

parser.add_option("-o", dest="ext", choices="exe txt pdf ppt".split())

and do the actual work outside the OptionParser.

options, args = parser.parse_args()

def process_exe():
# whatever

actions = {"exe": process_exe, ...}
actions[options.ext]()

Peter

Hrvoje Niksic

unread,
Jun 8, 2010, 7:30:01 AM6/8/10
to
Thomas Jollans <tho...@jollans.com> writes:

> UNIX and GNU recommendations. I've never actually heard of optparser,
> but I'd expect it to have the usual limitations:

Hiral probably meant to write "optparse", which supports GNU-style
options in a fairly standard and straightforward way. Which includes
that defining a "-o"/"--output-format" option that takes an argument
allows you to write one of "-o exe", "-oexe", "--output-format=exe", or
"--output-format exe".

My recommendation is to use -o, and -oexe will work just fine.

hiral

unread,
Jun 9, 2010, 5:52:30 AM6/9/10
to
On Jun 8, 3:03 pm, Jean-Michel Pichavant <jeanmic...@sequans.com>
wrote:
> hiralwrote:
> JM- Hide quoted text -
>
> - Show quoted text -

Hi JM,

Here it gives...
$ python above_script.py -oexe abc
Hello exe file !
{'output_fileType': None} # print options
['abc'] # print args

In my case I require to have 'options' to consume 'abc' like...
{'output_fileType': 'abc'}

Thank you.

hiral

unread,
Jun 9, 2010, 5:54:12 AM6/9/10
to
On Jun 8, 4:30 pm, Hrvoje Niksic <hnik...@xemacs.org> wrote:
> Thomas Jollans <tho...@jollans.com> writes:
> > UNIX and GNU recommendations. I've never actually heard of optparser,
> > but I'd expect it to have the usual limitations:
>
> Hiralprobably meant to write "optparse", which supports GNU-style

> options in a fairly standard and straightforward way.  Which includes
> that defining a "-o"/"--output-format" option that takes an argument
> allows you to write one of "-o exe", "-oexe", "--output-format=exe", or
> "--output-format exe".
>
> My recommendation is to use -o, and -oexe will work just fine.

Thank you all :) for your kind suggestins.
All your suggestions are fine and valid, which suggest to have option
'-o' and take its value 'exe ppt pdf txt' etc.

Yes, I am planning to use GNU style options...
One advantage with this that user can pass a.txt but can specify it as
'-oexe' and it would get executed as 'process_exe()'.

So to say we don't have support for '-o<extensions> value' in python;
but there are ways to acheive this.
It seems as of now I should specify them as seperate options like...
> parser.add_option("-o', dest=exe_file...)


> parser.add_option("-oexe', dest=exe_file...)
> parser.add_option("-otxt', dest=txt_file...)
> parser.add_option("-opdf', dest=pdf_file...)
> parser.add_option("-oppt', dest=ppt_file...)

Thank you in advance.
-Hiral

Jean-Michel Pichavant

unread,
Jun 9, 2010, 6:11:51 AM6/9/10
to hiral, pytho...@python.org

use

python above_script.py -o "exe abc"

and change the dispatch function to

def dispatchFileType(option, opt, value, parser):
"""Called by the parser, -o option."""
# call the corresponding method in the process method

for item in value.split():
getattr(Process, Process.PREFIX + item, Process.undef)()


Regards,

JM

0 new messages