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 each time.
This enables me to either:
- pass an option either a single value as and have it yielded repeatedly by a
dummy generator,
- or, by using the (arbitrarily chosen) word "CTRL:" after the option,
followed by another set of options - in quotes - suitable for the main
generator, to pass a changing value.
The problem: whether it works or not depends on what name is given to the
destination in parser.values() ! Strange but true.
I haven't yet been able to figure out if there's any pattern to this, but
names that work include: "add", "A", "rand", and "updown". Some that don't
are "descend", "random", and "Z".
When it doesn't work, the error is:
TypeError: unsupported operand type(s) for +: 'int' and 'generator'
So apparently when given one of the "wrong" names, calling options.
[wrongname].next() yields another generator object, whereas with the "right"
names, it yields the expected value.
Below is a working "sandbox" version of the relevant part of the actual
program, but with a hard-coded value for the number list and only a single
option, --add, which either adds the number given next on the command line to
each element of the list, or, if followed by CTRL: '' " (that's a pair of
empty quotes) will sequentially do the same for each member of the list. (If
the option is repeated inside the quotes, the altered list will be used to
apply the addition, and so on.)
If you don't believe me (and I'm finding this hard to believe myself), try
some different names in the two inline-commented places (of course, both have
to be the same). Some will work, others won't.
I'm baffled, and hope someone here may be interested in figuring out why this
is happening.
Thanks,
John O'Hagan
Here's the code:
import sys
from optparse import OptionParser
def my_callback(opt ion, opt_str, value, parser):
rargs = parser.rargs
if rargs[0] == "CTRL:" :
setattr(parser. values, option.dest+"_c trl", rargs[1].split())
else:
value = abs(int(rargs[0]))
setattr(parser. values, option.dest, value)
def parse(option_li st):
parser = OptionParser()
parser.add_opti on("--add", action="callbac k", callback=my_cal lback,
dest="add") ## The troublesome name!
(options, args) = parser.parse_ar gs(option_list)
return options
def numerical_ctrl( generator):
for number_list in generator:
for number in number_list:
yield number
def dummy_ctrl(valu e):
while 1:
yield value
#This next bit should ideally be incorporated into the callback function above
#(later!)
#It converts the attributes of the "options" object to generators.
def iterizer( options ):
for opt in vars( options ) :
if "_ctrl" in opt:
ctrl_opts_list = getattr( options, opt )
setattr(options , opt, dummy_ctrl( getattr( options, opt ) ) )
opt = opt.replace( "_ctrl", "" )
ctrl_opts = parse( ctrl_opts_list )
ctrl_opts = iterizer( ctrl_opts )
generator = phrase_engine( ctrl_opts )
generator = numerical_ctrl( generator )
else:
generator = dummy_ctrl( getattr( options, opt ) )
setattr (options, opt , generator)
return options
#The number list generator:
def phrase_engine(o ptions):
counter = 0
while counter < 10:
sequence = [1, 2, 3]
add = options.add.nex t() ##Here is the troublesome name again.
if add :
sequence = [ i + add for i in sequence ]
yield sequence
counter += 1
options = parse( sys.argv[ 1: ] )
options = iterizer(option s)
for i in phrase_engine(o ptions):
print i 0 1281 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Hans-Joachim Widmaier |
last post by:
I was really pleased when the Optik module found its way into the
standard Python battery compartment, as it matched all my option
parsing requirements. But, as always, there's really nothing that does
all you ever want, especially when it comes to option parsing -
there's just too many schemes to handle them all comfortably.
With this program I'm working on, I started to recognize that not only
the functionality should be delegated to...
|
by: Eric O. Angell |
last post by:
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.OptionParser()
parser.add_option('--secret', type='string', dest='header', default=Header())
|
by: Kenneth McDonald |
last post by:
I'd like to propose a new PEP , for a
standard library module that deals with files and file paths in an
object oriented manner. I believe this module should be included as
part of the standard Python distribution.
Background
==========
Some time ago, I wrote such a module for myself, and have found it
extremely useful. Recently, I found a reference to a similar module,
http://www.jorendorff.com/articles/python/path/ by Jeff Orendorff.
|
by: Pupeno |
last post by:
Hello,
I am doing some extreme use of optparse, that is, extending it as explained
on
http://docs.python.org/lib/optparse-other-reasons-to-extend-optparse.html
I have subclassed OptionParser and Option. MyOptionParser uses MyOption as
option_class and in Python 2.4 it works. But I have to target Python 2.3.
In Python 2.3 the help and version options seem to be created before even a
parser is created and they are created using a hardcoded...
|
by: Mathias Waack |
last post by:
We've integrated python into a legacy application. Everything works fine (of
course because its python;). There's only one small problem: the
application reads the commandline and consumes all arguments prefixed with
a '-' sign. Thus its not possible to call a python module from the
commandline with a parameter list containing options prefixed by '-'
or '--' signs. Thats not a major problem, but it prevents us from using th
optparse...
| |
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= |
last post by:
I get the above error in some of the ASP.NET web applications on a
server, and I need some help figuring out how to deal with it.
This is a rather long post, and I hope I have enough details that
someone who bothers to read all of it have some pointers.
Note, I have posted the stack trace and the code exhibiting the problem
further down so if you want to start by reading that, search for +++
Also note that I am unable to reproduce...
|
by: Robert Kern |
last post by:
Jeff Keasler wrote:
If you code it up with unit tests and documentation, it has a good chance. But
in the meantime, you can tell optparse to stop processing options using the
standard "--" marker. For example:
$ cat mycommand.py
import optparse
parser = optparse.OptionParser()
|
by: Astley Le Jasper |
last post by:
Sorry for the numpty question ...
How do you find the reference name of an object?
So if i have this
bob = modulename.objectname()
how do i find that the name is 'bob'
|
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
|
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...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
| |
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |