473,403 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 software developers and data experts.

CVS style argument parsing?

Hello!

Is it possible to have CVS-style command line options with the optparse
module? I could get as far as:

import sys
from optparse import OptionParser, OptionGroup
parser = OptionParser()

opt_global = OptionGroup (parser, "Global options")
opt_global.add_option("-m", "--mode", choices=["import", "dump"],
dest="mode", default="dump",
help="One out of import, dump")
opt_global.add_option("-d", "--dbname", default="test",
help="The name of the database")
opt_global.add_option("-D", "--dbpath", default=Cnf.dbpath,
help="The path to the database")

opt_dump = OptionGroup (parser, "Dumper options")
opt_dump.add_option("-v", "--dump-values",
action="store_true", dest="values", default=False,
help="Dump values.")

How can I get rid of the "-m" option so that

myscript -dfoo dump -v

would be possible?

--
Please visit and sign http://petition-eurolinux.org and http://www.ffii.org
-- Josef Wolf -- jw@raven.inka.de --
Jul 18 '05 #1
4 1848
Don't use OptionGroups for each command. Instead, you'll have the
OptionParser for the "main" arguments, and the option parser for each
command.

By using parser.disable_interspersed_args() you can make the parsing of
"-a b -c".split() handle "-a" and return "b -c".split() as the
positional args. Then, depending on what b is, send -c to a separate
parser instance.

I don't see where disable_interspersed_args() is documented, but it's
right there in optparse.py

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFA/bb/Jd01MZaTXX0RAq/3AKCLvk6gBbfjgEg5DSKRIBVeXaI84wCfbl/F
HqObWHOMpSP5gp6MXHM3D4g=
=jaco
-----END PGP SIGNATURE-----

Jul 18 '05 #2
Jeff Epler schrieb im Artikel <ma*************************************@python.or g>:
Don't use OptionGroups for each command. Instead, you'll have the
OptionParser for the "main" arguments, and the option parser for each
command.
I tried to do this before, and had exactly the problem you describe below.
By using parser.disable_interspersed_args() you can make the parsing of ^^^^^^^^^^^^^^^^^^^^^^^^^^^ "-a b -c".split() handle "-a" and return "b -c".split() as the
positional args. Then, depending on what b is, send -c to a separate
parser instance.


Aaaahhh, this was the bit of information I was missing. Is it "legal" to
use this method? It seems not to be documented in the library reference?

Thanks!

--
Please visit and sign http://petition-eurolinux.org and http://www.ffii.org
-- Josef Wolf -- jw@raven.inka.de --
Jul 18 '05 #3
On Wed, Jul 21, 2004 at 06:37:05AM +0000, Josef Wolf wrote:
Jeff Epler schrieb im Artikel <ma*************************************@python.or g>:
By using parser.disable_interspersed_args() you can make the parsing of ^^^^^^^^^^^^^^^^^^^^^^^^^^^

[...]
Aaaahhh, this was the bit of information I was missing. Is it "legal" to
use this method? It seems not to be documented in the library reference?


I agree, it doesn't seem to be in the documentation. It's been in the
module since at least 2002, when it was called Optik, and has been
suggested many times to people who want to implement "cvs-like"
commandline parsers, according to a few google searches I performed.

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)

iD8DBQFA/nMMJd01MZaTXX0RAkPuAJ9L2ayRtABbS3fAN25ffibDohSXgwC fYlLC
WzJvu8bOnDVOCKATpFdc0x4=
=lX2/
-----END PGP SIGNATURE-----

Jul 18 '05 #4
Jeff Epler schrieb im Artikel <ma*************************************@python.or g>:
> By using parser.disable_interspersed_args() you can make the parsing of ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Aaaahhh, this was the bit of information I was missing. Is it "legal" to
use this method? It seems not to be documented in the library reference?


I tried it now and it mostly seems to work as expected. But there are
some cosmetic drawbacks:

1. When called "main.py dump -h" then _first_ the help for the subcommand
is printed and after that the help for the global options are printed.
I think this is because I am doing something very stupid with the
exception?
2. When invalid options are given, only the usage information is printed.
The list of available options is missing. (This is for both, the global
options as well as the subcommand options.)
3. When I replace the call to parser.print_help() in the exception handler
with a "pass" statement, (1.) seems to be fixed, but then no help at
all is printed when no subcommand is given.

Maybe someone could give me hints what I am doing wrong?

(I have attached the script (consiting of three modules: main.py, Opt.py
and Dump.py) at the end of this posting.)

PS: I am very interested in comments how to make things more python-ish.
I am new to python and am probably doing very stupid things :)
I agree, it doesn't seem to be in the documentation. It's been in the
module since at least 2002, when it was called Optik, and has been
suggested many times to people who want to implement "cvs-like"
commandline parsers, according to a few google searches I performed.


I have tried to google, but could not find anything. I get either
thousands of hits (alsmost all related to perforce) or nothing at all.
What keywords have you used?
here come the scripts:

#File Opt.py:
import sys
from optparse import OptionParser

class MyOptionParser:
subcommands={}

def __init__(self, mode, callback, help):
self.__parser=OptionParser("%%prog %s [%s-options]" % (mode,mode))
MyOptionParser.subcommands[mode] = {"obj" : self,
"func" : callback,
"help" : help}

def __getattr__(self, name):
return getattr(self.__parser, name)

def global_parser():
global opts, args, subopts, subargs
global subcommand

subcommands = MyOptionParser.subcommands

parser = OptionParser()
parser.disable_interspersed_args()

parser.add_option("-f", help="Foo option.")
parser.add_option("-b", help="Bar option.")

parser.set_usage("%prog [options]" +
" subcommand [subcommand-options]:\n\n" +
"Available subcommands:\n" +
"\n".join([" %-8s %s" % (k,subcommands[k]["help"])
for k in subcommands.keys()]))

(opts, args) = parser.parse_args()

try:
subcommand = subcommands[args[0]]
(subopts, subargs) = subcommand["obj"].parse_args(args[1:])
subcommand["func"](subargs)

except:
parser.print_help()

sys.exit()

global_parser=staticmethod(global_parser)
#File Dump.py:
import Opt

def main(args):
print Opt.opts
print Opt.subopts
print Opt.subargs

def init_main():
opt_dump=Opt.MyOptionParser("dump", main, "Dump database contents.")
opt_dump.add_option("-z", help="Baz option.")
opt_dump.add_option("-b", help="Blah option.")

init_main()
#File main.py:
import os
import sys

import Opt
import Dump

Opt.MyOptionParser.global_parser()
--
Please visit and sign http://petition-eurolinux.org and http://www.ffii.org
-- Josef Wolf -- jw@raven.inka.de --
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Jarson | last post by:
I am using the ACRONYM tag to provide an explanation of codes within my application. Example: <p>The circuit <acronym title="Circuit P123T: Picton SS to Telebary SS 345KV">P123T</acronym> is...
28
by: Michael B. | last post by:
I tend to use rather descriptive names for parameters, so the old style of declaration appeals to me, as I can keep a declaration within 80 chars: void * newKlElem...
64
by: Morgan Cheng | last post by:
Hi All, I was taught that argument valuse is not supposed to be changed in function body. Say, below code is not good. void foo1(int x) { x ++; printf("x+1 = %d\n", x); } It should be...
83
by: rahul8143 | last post by:
hello, what is difference between sizeof("abcd") and strlen("abcd")? why both functions gives different output when applied to same string "abcd". I tried following example for that. #include...
4
by: Bob hotmail.com> | last post by:
Everyone I have been spending weeks looking on the web for a good tutorial on how to use regular expressions and other methods to satisfy my craving for learning how to do FAST c-style syntax...
5
by: STeve | last post by:
Hey guys, I currently have a 100 page word document filled with various "articles". These articles are delimited by the Style of the text (IE. Heading 1 for the various titles) These articles...
6
by: Markus Ilmola | last post by:
How to a parse a string using C++ (standard library) same way as sscanf in C. For example if a have a string: My name is "John Smith" and I'm 13 years old and 120 cm tall. and a want to...
100
by: Angel Tsankov | last post by:
Can someone recommend a good source of C/C++ coding style. Specifically, I am interested in commenting style and in particular how to indent comments and the commented code, rather than when to...
21
by: Thomas Pornin | last post by:
Hello, with gcc-4.2.3, this does not compile: typedef int foo; int f(foo) int foo; { return foo; }
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.