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.
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
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
> 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
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
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
> 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.
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.
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
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