optparse: best way

H

hiral

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

Thomas Jollans

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
 
J

Jean-Michel Pichavant

hiral said:
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.

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
 
M

Michele Simionato

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.

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
 
P

Peter Otten

hiral said:
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.

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
 
H

Hrvoje Niksic

Thomas Jollans said:
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.
 
H

hiral

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

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

hiral

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
 
J

Jean-Michel Pichavant

hiral said:
hiralwrote:
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.
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- 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.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top