473,789 Members | 2,799 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

optparse object population

Say I have
class Header:
def __init__(self):
self.foo = 0
# ... more fields

and I have some commandline options that can specify better values for things
in the header, such as foo. If I try the obvious (to me):
parser = optparse.Option Parser()
parser.add_opti on('--secret', type='string', dest='header', default=Header( ))
parser.add_opti on('--foo', type='int', dest='header.fo o')
(options, args) = parser.parse_ar gs()

when I run the program with "--foo 3", I'm sadly left with something like
this:
print options

<Values at 0xdeadbeef: {'header': <Header instance at 0xdeadbeef>,
'header.foo': 3}>

So when optparse first initializes the variables to None, it's creating a
'header.foo' that has nothing to do with header=Header() . Is there a way to
coerce optparse into populating an object for me? Yes, I could just do
something like this:
(options, args) = parser.parse_ar gs()
header = Header()
header.foo = options.foo
# ... more population of header

but I'd rather just end up with options.header that I could then use somewhere
else.

Am I going to have any success with this, or am I just SOL?

Thanks.

-E
Jul 18 '05 #1
1 2018
Eric O. Angell wrote:
Is there a way to coerce optparse into populating an object for me?


If you are dealing with just one object you can provide a custom values
parameter:

<code>
import optparse

class Header(object):
def __init__(self):
self.foo = "default-foo"
self.bar = "default-bar"
def __str__(self):
values = ["%s=%r" % nv for nv in self.__dict__.i tems()]
return "%s(%s)" % (self.__class__ .__name__, ", ".join(valu es))
__repr__ = __str__

p = optparse.Option Parser()
p.add_option("--foo")
p.add_option("--bar")
p.add_option("--baz")

header = Header()
options, args = p.parse_args(["--foo", "custom-foo", "--baz", "custom-baz"],
values=header)
print "options is header", options is header
# True
print "header", header
</code>

You can even expand that to work with nested objects, but it gets a little
messy and you are probably better off with Jeff Epler's approach here:

<code-continued>
# (insert above code here)

class Header2(Header) :
def __setattr__(sel f, name, value):
if "." in name:
left, right = name.split(".", 1)
setattr(getattr (self, left), right, value)
else:
object.__setatt r__(self, name, value)

header2 = Header2()
header2.nested = Header2() # I use the same class here because I'm
# lazy, not for technical reasons
p.add_option("--nested.foo")
options, args = p.parse_args(["--nested.foo", "hi there"], values=header2)
print options
</code-continued>

Especially, I have some doubts whether __setattr__("do tted.name", value)
will always be allowed.

Peter

Jul 18 '05 #2

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

Similar topics

7
2792
by: Henry Ludemann | last post by:
I've been writing an optparse alternative (using getopt) that is at a stage where I'd be interested in people's opinions. It allows you to easily creating command line interfaces to existing functions, using flags (which are optional) and arguments. It will automatically print a nicely formatted usage (eg: -h or --help), and easily & automatically validates parameter existence and type. You can download it, and read a bit more about it,...
1
2863
by: sector119 | last post by:
Hi I use optparse with callback action, my callback function return some value, but optparse does not store this value, options.callback_dest always is None. How can I store callback function return value or callback option value like store action do? I modify optparse.py Option::take_action def and add there:
5
2568
by: Sébastien Boisgérault | last post by:
Any idea why the 'options' object in # optparse stuff (options, args) = parser.parse_args() is not/couldn't be a real dict ? Or why at least it does not support dict's usual methods ? The next move after a parse_args is often to call a method 'do_stuff' with the args and options and
3
2460
by: Karlo Lozovina | last post by:
If I create a file with only one line: --- from optparse import OptionParser --- I get this when I try to run it from "DOS" prompt: Traceback (most recent call last): File "optparse.py", line 1, in ?
2
1037
by: Tim Arnold | last post by:
Hi, I'm writing a command-line interface using optparse. The cli takes several options with a single action and several parameters to be used in the resulting worker classes. I've been passing parameters from optparse to the workers in two ways: (1) creating a Globals.py module, set parameters once in the cli code and read it when needed in the worker class methods. Something like this: import Globals
7
4118
by: wannymahoots | last post by:
optparse seems to be escaping control characters that I pass as arguments on the command line. Is this a bug? Am I missing something? Can this be prevented, or worked around? This behaviour doesn't occur with non-control characters. For example, if this program (called test.py): from optparse import OptionParser parser = OptionParser() parser.add_option("-d", dest="delimiter", action="store")
0
1278
by: John O'Hagan | last post by:
Here's a strange one for you: I have a generator function which produces lists of numbers and takes options which influence the output. The generator contains a loop, and to enable the options to have a different value on each iteration, the options may themselves be instances of the same generator, in the form of attributes of an optparse object. In the body of the loop, the next() method is called on each generator to get the new value...
5
1376
by: RyanN | last post by:
Hello, I'm trying to teach myself OOP to do a data project involving hierarchical data structures. I've come up with an analogy for testing involving objects for continents, countries, and states where each object contains some attributes one of which is a list of objects. E.g. a country will contain an attribute population and another countries which is a list of country objects. Anyways, here is what I came up with at first:
1
1906
by: John O'Hagan | last post by:
Hello, I've recently found it convenient to do something like this: options = optparse_function(sys.argv) ##print options => ##{option_one:4, option_two:, option_three:'/home/files'} #(Note that this is not a dictionary, even though it looks like one; it's how
0
9665
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9511
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10139
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7529
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6768
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5551
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4092
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3697
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2909
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.