Re: Do any of you recommend Python as a first programming language?
On 2008-03-22, bsoist <[EMAIL PROTECTED]> wrote: > On Mar 22, 12:40 pm, jmDesktop <[EMAIL PROTECTED]> wrote: >> For students 9th - 12th grade, with at least Algebra I. Do you think >> Python is a good first programming language for someone with zero >> programming experience? Using Linux and Python for first exposure to >> programming languages and principles. >> >> Thank you. > > Absolutely. I love using Python in "the real world" but it is > fantastic for beginning programmers. > > Python enforces good habits and presents many opportunities to discuss > programming from an academic perspective. Why does Python not have a > switch or until statement? Why doesn't it? > Why are very common objects (stack, queue, > linked list) not builtin? etc. I think I know this one: you just use builtin lists to do stacks, queues and, er, lists. -- http://mail.python.org/mailman/listinfo/python-list
Re: About reading Python code
On 2008-03-17, WaterWalk <[EMAIL PROTECTED]> wrote: > Hello. I wonder what's the effective way of figuring out how a piece > of python code works. With C I often find it very useful to be able to > run the code in step mode and set breakpoints in a debugger so I can > watch how the it executes, how the data change and how the code jumps > from one function to another. But with Python, the debugger is a > little primitive. The default IDLE doesn't even allow me to set a > breakpoint. It does, you just right-click and go "set breakpoint". But yes IDLE is a bit basic. -- http://mail.python.org/mailman/listinfo/python-list
Re: SV: SV: Regarding coding style
On 2008-03-08, K Viltersten <[EMAIL PROTECTED]> wrote: >> If you can't/don't look at the source file, >> then comments aren't going to help (except >> in the case of something like docstrings in >> Python). > > I strongly disagree. Now, perhaps we're > talking about different things, here? > Usually, in the header file (C++), there > won't be any source code, except for > method declarations. A common example: > > /** Projects an object from 3D to 2D using > the method of Alexander The Great. > \param 3D structure to be projected > \returns 2D projection > */ > public Proj2D get2Dfrom3D(Proj3D param); > > The above is, to me, very clear and > consistent. Not to mention, easily > handled with e.g. Doxygen to create a > readable documentation. > > I don't see how this is dislikeable. Please > explain. Perhaps the above IS what you > ment by "docstrings"? For Java, one has the > JavaDocs, a great tool, provided one will > comment each method and variable used. The problem is that tools like Doxygen and JavaDocs generate warnings and errors and things if everything isn't documented "completely". So you end up with a lot of silly boilerplate. I see this kind of nonsense a lot: /** * Get the width of a box * * @param box the box * @returns its width */ extern int box_get_width(box box); You are right that is it often useful to document what to pass to a method and what to expect back and that if this is done well in many cases it isn't necessary to see the implementation. But in many other cases it's obvious, and in other cases it's obvious if you just look at the source which you've got. What's needed is just a bit of common sense and pragmatism: APIs need more documentation if the source of the implementation isn't being released with them, and some APIs just need more documentation than others anyway. Python docstrings, like most things in Python, demonstrate this kind of common sense: you write what you want in them and as far as I can tell nothing complains if you don't write them at all. The lack of fascism is the big innovation. It sounds simple but it makes a huge difference: it's much easier to find (and keep up to date) the real documentation if it's not hidden in a forest of bogus documentation. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to manipulate elements of a list in a single line of code?
On 2008-02-25, mrstephengross <[EMAIL PROTECTED]> wrote: > I would like to translate the contents of a list. For instance, let's > say I've got a list of strings and I want to append "foo" to each > element. I might do the following; > > list1 = ['a', 'b', 'c'] > for i in range(0, len(list1)): list1[i] += 'foo' > > Ok, that much works. But what if I don't want to modify the contents > of list1. Instead, I want list2 to hold the modified contents, like > so: > > 1 list1 = ['a', 'b', 'c'] > 2 list2 = [] > 3 for item in list1: list2.append(item + 'foo') > > Is there a way to express lines 2-3 sort-of ilke this: > > list2 = [ for item in list1: item + 'foo' ] Yes, it's called a "list comprehension", and is many people's favourite Python feature. list2 = [x + 'foo' for x in list1] You can also add a condition list2 = [x + 'foo' for x in list1 if x != "bar"] for example. -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive generator
On 2008-02-13, Erich <[EMAIL PROTECTED]> wrote: > On Feb 12, 5:15 am, Ben C <[EMAIL PROTECTED]> wrote: >> I think this works OK, but it seems a bit odd. Is there something more >> "Pythonic" I should be doing? > > I have a similar tree to the one you describe here at work. I have a > visit function that is very similar to yours, but takes function > arguments for doing pre- and/or post- order operations on the node > (code below). It also yeilds the nodes, but in a postorder manner. The > flexibility is quite useful. Yes that's pretty good too, although usually I want either a callback or to yield a result, but not both, and often a function of a node passed in to say whether to prune at that point (i.e. not visit further descendents). For various other reasons I've now gone to a tree where each node has a parent, sibling and first child reference. No children array. The generator yields tuples of (DOWN, node), (RIGHT, node) and (UP, node), and is not itself recursive-- it uses the parent references instead. If the caller wants pre-order it just ignores UP visits. If it wants post-order it ignores DOWN. The distinction between DOWN and RIGHT is important if the caller wants to push and pop stacks as it walks the tree. The generator itself is not so pretty, but the caller can more easily do everything with it that it would be able to do if it was recursive itself. def genDescendents(self, prune = None): node = self dir = DOWN while 1: if prune and prune(node): if dir == DOWN: dir = RIGHT else: yield dir, node # Go down if we can, unless we've been there already, else # right, or as a last resort, up. if dir != UP: if node.firstChild: node = node.firstChild dir = DOWN else: # Back up through leaf nodes-- so we change dir but not # node. Sort of a U-turn. dir = UP elif node.sibling: node = node.sibling dir = RIGHT elif node.parent: node = node.parent dir = UP else: break > Regards, > Erich > > def visit(self,prefunc = None, postfunc = None): > if prefunc: > prefunc(self) > > for child in self.children: > for y in child.visit(prefunc, postfunc): > yield y > > if postfunc: > postfunc(self) > > yield self -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive generator
On 2008-02-12, Paul Hankin <[EMAIL PROTECTED]> wrote: > On Feb 12, 10:17 pm, Ben C <[EMAIL PROTECTED]> wrote: >> On 2008-02-12, Paul Rubin <> wrote: >> >> > Paul Hankin <[EMAIL PROTECTED]> writes: >> >> def genDescendants(self): >> >> return chain([self], *[child.genDescendants() >> >> for child in self.children]) >> >> > That is scary. It generates an in-memory list the size of the >> > whole subtree, at every level. Total memory consumption is maybe >> > even quadratic, depending on the tree shape, but even if it's >> > only linear, it's way ugly. >> >> This would probably be better (in terms of memory if not beauty): >> >> def genDescendants(self): >> return chain([self], *(child.genDescendants() >> for child in self.children)) > > No, it's the same I think. Yes I think you're right. The problem is really the *. The generator comprehension (child.genDescendants() ...) will have to be run to completion to build the arguments to pass to chain. So no laziness there. > forgot that a generator using yield isn't the same as the same > function that returns an equivalent generator, because one is lazy and > the other isn't. To get the lazy behaviour back, you'd have to > write > > def genDescendants(self): > for g in chain([self], *(child.genDescendants() > for child in self.children)): > yield g Is that lazy? It still seems like (child.genDescendants() ...) would have to be run all the way to the end before chain could be called. Unless * is lazy. I don't think it is, but I don't know for sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive generator
On 2008-02-12, Paul Rubin <> wrote: > Paul Hankin <[EMAIL PROTECTED]> writes: >> def genDescendants(self): >> return chain([self], *[child.genDescendants() >> for child in self.children]) > > That is scary. It generates an in-memory list the size of the > whole subtree, at every level. Total memory consumption is maybe > even quadratic, depending on the tree shape, but even if it's > only linear, it's way ugly. This would probably be better (in terms of memory if not beauty): def genDescendants(self): return chain([self], *(child.genDescendants() for child in self.children)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive generator
On 2008-02-12, Paul Hankin <[EMAIL PROTECTED]> wrote: > On Feb 12, 11:15 am, Ben C <[EMAIL PROTECTED]> wrote: >> Suppose I have an object containing an array called children. I can >> therefore build a tree out of such objects. >> The best I came up with so far is : >> >> def genDescendents(self): >> for child in self.children: >> yield child >> for grandChild in child.genDescendents(): >> yield grandChild > > Looks fine, although I'd include self in the generator because I think > that's more logical, (and spell descendant correctly :). I actually prefer descendent. It may be more American English since it's closer to Latin. "Descendant" is basically French. But anyway, never mind :) > def genDescendants(self): > yield self > for child in self.children: > for grandchild in child.genDescendants(): > yield grandchild > > > Often generators can be written more concisely with itertools at the > expense of some readability, and that's true here. > > from itertools import chain > > def genDescendants(self): > return chain([self], *[child.genDescendants() > for child in self.children]) Thanks for that, I was wondering if there might be something in itertools to do this. I think the first version is probably more readable though anyway. -- http://mail.python.org/mailman/listinfo/python-list
Recursive generator
Suppose I have an object containing an array called children. I can therefore build a tree out of such objects. I thought it might be useful to have a descendent generator, so I could write: for thing in self.genDescendents(): foo(thing) expecting foo to be called for each descendent in pre-order. The best I came up with so far is : def genDescendents(self): for child in self.children: yield child for grandChild in child.genDescendents(): yield grandChild I think this works OK, but it seems a bit odd. Is there something more "Pythonic" I should be doing? -- http://mail.python.org/mailman/listinfo/python-list
Re: MS Word parser
On 2007-06-13, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Jun 13, 1:28 am, Tim Golden <[EMAIL PROTECTED]> wrote: >> [EMAIL PROTECTED] wrote: >> > Hi all, >> > I'm currently using antiword to extract content from MS Word files. >> > Is there another way to do this without relying on any command prompt >> > application? >> >> Well you haven't given your environment, but is there >> anything to stop you from controlling Word itself via >> COM? I'm no Word expert, but looking around, this >> seems to work: >> >> >> import win32com.client >> word = win32com.client.Dispatch ("Word.Application") >> doc = word.Documents.Open ("c:/temp/temp.doc") >> text = doc.Range ().Text >> >> open ("c:/temp/temp.txt", "w").write (text.encode ("UTF-8")) >> >> >> TJG > > Tim, > I'm on Linux (RedHat) so using Word is not an option for me. Any > other suggestions? There is OpenOffice which has a Python API to it (called UNO). But piping through antiword is probably easier. -- http://mail.python.org/mailman/listinfo/python-list
Re: questions about programming styles
On 2007-05-20, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi all, I'm not skilled at programming, so sorry for my ignorance. > My questions: > > (1) > which is the better way to calculate the value of attributes of a class ? > for example: > > (A) > def cal_attr(self, args): > #do some calculations > self.attr = calculated_value > and then if the vlue of attribute is needed, > self.cal_attr(args) > some_var = self.attr > or I can define cal_attr() as follows: > (B) > def cal_attr(self, args): > #do some calculations > return calculated_value > and then, if the value of attribute is needed, > self.attr = self.cal_attr(args) > some_var = self.attr It looks from your example like this attr depends on the args passed to cal_attr. Is it really then an "attribute" of the object, or just the result of a calculation that the object provides? If the latter, you might not want the variable self.attr at all, and just write some_var = self.cal_attr(args) Otherwise self.attr just ends up storing the result of the previous call to cal_attr. Is that useful? Does any other part of the program actually need that? If not don't store it. > (2) > when to use class methods and when to use functions ? I think you just mean methods (Python has something special called "class methods" which are for, er, well, you almost never need them). > In my opinion, both of class methods and functions have advantages and > disadvantages. I have to pass many arguments to a function, which is > annoying. When using class methods, the arguments can be stored as > attributes of the class, which is convenient for later use. But I have > to create an object in advance. That's about right. There's no hard and fast rule. If you need those values again it may be worth storing them, but be wary of storing computed values if there's a chance they're going to get out of date. > I have googled the web, but haven't found too much specific answers. > Can somebody kindly answer my questions or point me to the resources > available on the web ? You're asking good questions and they don't have easy answers. -- http://mail.python.org/mailman/listinfo/python-list
Re: Controlling gnuplot via subprocess.Popen
On 2007-04-25, Peter Beattie <[EMAIL PROTECTED]> wrote: > I am trying to plot something in gnuplot 4.2 using co-ordinates a Python > 2.5 program computes. Here's what I'm doing: > > py> from subprocess import * > py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE) > py> plot.stdin.write("plot x*x") > > The first command dutifully opens gnuplot, but the second doesn't do > anything. Could someone favour me with an explanation as to the whyness? I think it may just be that you need a newline after "plot x*x", i.e. plot.stdin.write("plot x*x\n") or print >>plot.stin, "plot x*x" But some interactive programs need to be controlled with expect rather than just writing to their stdin. I'm unclear of the details, perhaps it's just ones that use curses in some form. I usually write the gnuplot commands to a file, and then use os.system("gnuplot plot.gpi") to run gnuplot in batch mode (or gnuplot -persist if you want the window). You can also use Popen instead of os.system. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange behaviour of 'is'
On 2006-09-21, Fijoy George <[EMAIL PROTECTED]> wrote: > Hi all, > > I am a bit perplexed by the following behaviour of the 'is' comparator > x = 2. x is 2. > False y = [2., 2.] y[0] is y[1] > True > > My understanding was that every literal is a constructure of an object. > Thus, the '2.' in 'x = 2.' and the '2.' in 'x is 2.' are different objects. > Therefore, the comparison yields false. > > But my understanding does not explain the result of the second comparison. > According to the experiment, y[0] and y[1] are the same object! I'm as baffled as you, even more so its implication: >>> a = 2. >>> b = 2. >>> a is b False >>> a, b = 2., 2. >>> a is b True -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL Image transform
On 2006-08-11, Dean Card <[EMAIL PROTECTED]> wrote: [snip] > thanks for the reply. I have been able to use the Image.PERSPECTIVE > transform via trial and error to get it to work properly for each transform. > What I am really looking for I guess is a way to calculate the 8 int tuple > to match the perspective change I am going for. For a given image there may > be 5 elements that need to be 'painted' on with perspective. A database > table will include the transform tuples based on the source image. So, by > passing a starting image and a pattern image, the starting image can be > covered with. Perhaps the best way to explain is visually > > http://seanberry.com/perspective.png > > What I need to know is how you take a surface like (P1, P5, P6, P2) and > describe it with the 8 int tuple? You could try asking this in comp.graphics.algorithms. The question is easily made non-Python-specific, just say you have a function in a library that does this: Transform each point {x,y} in an image into a new point {x1,y1} where {x1,y1} = {(ax + by + c)/(gx + hy + 1), (dx + ey + f)/(gx + hy + 1)} then ask how to choose the params a to h to achieve the effect illustrated on http://seanberry.com/perspective.png. -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL Image transform
On 2006-08-11, Dean Card <[EMAIL PROTECTED]> wrote: >> This looks like a correct description of the sources: >> >> In Image.py: >> >> elif method == PERSPECTIVE: >># change argument order to match implementation >>data = (data[2], data[0], data[1], >>data[5], data[3], >>data[4], >>data[6], >>data[7]) >> >> and then in Geometry.c: >> >> static int >> perspective_transform(double* xin, double* yin, int x, int y, void* >>data) >> { >>double* a = (double*) data; >>double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; >>double a3 = a[3]; double a4 = a[4]; double a5 = a[5]; >>double a6 = a[6]; double a7 = a[7]; >> >>xin[0] = (a0 + a1*x + a2*y) / (a6*x + a7*y + 1); >>yin[0] = (a3 + a4*x + a5*y) / (a6*x + a7*y + 1); >> >>return 1; >> } >> >> Something like this is almost what you what: >> >> im = im.transform(im.size, Image.PERSPECTIVE, (1, 0, 0, 0, 1, 0, -0.004, >> 0)) >> >> But the problem really is that the top row of the image is at at y of >> 0-- I think you want the origin of the image to be in the centre for >> this to work properly. >> >> Is there a way to do that in PIL? > > > thanks for the reply. I have been able to use the Image.PERSPECTIVE > transform via trial and error to get it to work properly for each transform. > What I am really looking for I guess is a way to calculate the 8 int tuple > to match the perspective change I am going for. For a given image there may > be 5 elements that need to be 'painted' on with perspective. A database > table will include the transform tuples based on the source image. So, by > passing a starting image and a pattern image, the starting image can be > covered with. Perhaps the best way to explain is visually > > http://seanberry.com/perspective.png > > What I need to know is how you take a surface like (P1, P5, P6, P2) and > describe it with the 8 int tuple? I think you want to work out normalized normals for each face of your cube, in 3D. This part is easy (or at least well-known) for any given set of Euler angles (rotation about each axis) or for an angle about an arbitrary axis. A normal can be visualized as a perpendicular spike sticking out of the centre of each face (for the sake of simplicity assume the centre of the cube is at the origin). A normal is "normalized" if dot(n, n) == 1. So, anyway, for a given face, you work out a normal with 3 components, n[0], n[1] and n[2]. Then I think it's likely that each of (a, b), (d, e) and (g, h) should be set to different combinations of two out of the three (maybe with some minus signs in here and there). Something like this: (a, b) <= (n[2], n[1]) (d, e) <= (n[0], n[2]) (g, h) <= (n[0], n[1]) Leaving c and f as zero. If I get the time I'll try and work it out properly and explain it. -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL Image transform
On 2006-08-09, Dean Card <[EMAIL PROTECTED]> wrote: > Okay, so here is the situation. I have need to do some on-the-fly image > creation. I have everything working great except for the last part of it, > applying a perspective type transform to the image. The transform will take > a rectangular 2D image and transform it to a 3D representation in 2D. > > Please see the link to see what I am trying to do: > http://seanberry.com/transform.png > > I have PIL v1.15 installed which has a PERSPECTIVE transform, but it does > not appear to do what I want - or I can't figure out how to use it correctly > because it is using a transform matrix's coefficients. > > Here is the only info I could find on the usage: > http://mail.python.org/pipermail/image-sig/2005-February/003198.html This looks like a correct description of the sources: In Image.py: elif method == PERSPECTIVE: # change argument order to match implementation data = (data[2], data[0], data[1], data[5], data[3], data[4], data[6], data[7]) and then in Geometry.c: static int perspective_transform(double* xin, double* yin, int x, int y, void* data) { double* a = (double*) data; double a0 = a[0]; double a1 = a[1]; double a2 = a[2]; double a3 = a[3]; double a4 = a[4]; double a5 = a[5]; double a6 = a[6]; double a7 = a[7]; xin[0] = (a0 + a1*x + a2*y) / (a6*x + a7*y + 1); yin[0] = (a3 + a4*x + a5*y) / (a6*x + a7*y + 1); return 1; } > This is for the creation of images to be used in Flash. Originally I was > doing the image processing in Flash because Flash 8 has a BitmapData class > which does the basics of images, copy, transform, etc. To accomplish the > transform I was using an algorithm that approximated triangles to fill and > worked really well, but I need the image processing to be server side, not > client. > > So, here I am. Anyone have any idea how to accomplish my goal here? Is > there a way to fill a triangle with a bitmap using PIL? What about better > docs on the PERSPECTIVE transform? > > Thanks for any and all help on this. Something like this is almost what you what: im = im.transform(im.size, Image.PERSPECTIVE, (1, 0, 0, 0, 1, 0, -0.004, 0)) But the problem really is that the top row of the image is at at y of 0-- I think you want the origin of the image to be in the centre for this to work properly. Is there a way to do that in PIL? -- http://mail.python.org/mailman/listinfo/python-list
Re: access abook addressbook with curses
On 2006-08-08, Fabian Braennstroem <[EMAIL PROTECTED]> wrote: > Hi Ben, > > * Ben C <[EMAIL PROTECTED]> wrote: >> On 2006-08-06, Fabian Braennstroem <[EMAIL PROTECTED]> wrote: >>> Hi Ben, >>> >>> * Ben C <[EMAIL PROTECTED]> wrote: >>>> On 2006-08-05, Fabian Braennstroem <[EMAIL PROTECTED]> wrote: >>>>> Hi, >>>>> >>>>> I want to get access to my abook address file with python. >>>>> Does anyone have some python lines to achive this using >>>>> curses? If not, maybe anybody has small python program doing >>>>> it with a gui!? >>>> >>>> You can just parse the abook addressbook with the ConfigParser, try >>>> this: >>>> >>>> import os >>>> from ConfigParser import * >>>> >>>> abook = ConfigParser() >>>> abook.read(os.environ["HOME"] + "/.abook/addressbook") >>>> >>>> for s in abook.sections(): >>>> print abook.items(s) >>> >>> Thanks! I found a different example too: >>> >>> import ConfigParser >>> import string >>> >>> config = ConfigParser.ConfigParser() >>> >>> config.read("/home/fab/.abook/addressbook") >>> >>> # print summary >>> print >>> for number in [2,200]: >>> print string.upper(config.get(str(number), "email")) >>> print string.upper(config.get(str(number), "name")) >>> print string.upper(config.get(str(number), "city")) >>> print string.upper(config.get(str(number), "address")) >>> >>> but the problem seems to be that abook does not write every >>> field, so I get an exception when there is a field missing: >>> >>> Traceback (most recent call last): >>> File "configparser-example-1.py", line 13, in ? >>> print string.upper(config.get(str(number), "city")) >>> File "/usr/lib/python2.4/ConfigParser.py", line 520, in get >>> raise NoOptionError(option, section) >>> ConfigParser.NoOptionError: No option 'city' in section: '2' >>> >>> Section 2 looks like: >>> >>> [2] >>> name=Andrs Gzi >>> [EMAIL PROTECTED] >>> nick=oz >>> >>> Is there a workaround? >> >> You can construct the parser with a dictionary of defaults: >> >> config = ConfigParser.ConfigParser({"city" : "unknown", >> "zip" : "unknown"}) >> >> that kind of thing. >> >> Or catch the exceptions. Or use config.options("2") to see what options >> exist in section 2 before you try to read them. > > Thanks! I will try it out! Looking at the bigger picture here, though, I may be giving you the wrong advice. Mutt just invokes abook to get the addresses I think, that's why you put set query_command="abook --mutt-query '%s'" So you could do the same (if what you're trying to do is write a mutt clone in Python): import subprocess name = "Andrs" subprocess.Popen("abook --mutt-query " + name, stdout=subprocess.PIPE, shell=True).communicate()[0] The difference is that this "leverages" abook to do the search, not just to store the data, which is a logical approach. On the other hand, this way, you require that abook is installed on the machine, which is no good if the object of the exercise is a portable Python-only solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: access abook addressbook with curses
On 2006-08-06, Fabian Braennstroem <[EMAIL PROTECTED]> wrote: > Hi Ben, > > * Ben C <[EMAIL PROTECTED]> wrote: >> On 2006-08-05, Fabian Braennstroem <[EMAIL PROTECTED]> wrote: >>> Hi, >>> >>> I want to get access to my abook address file with python. >>> Does anyone have some python lines to achive this using >>> curses? If not, maybe anybody has small python program doing >>> it with a gui!? >> >> You can just parse the abook addressbook with the ConfigParser, try >> this: >> >> import os >> from ConfigParser import * >> >> abook = ConfigParser() >> abook.read(os.environ["HOME"] + "/.abook/addressbook") >> >> for s in abook.sections(): >> print abook.items(s) > > Thanks! I found a different example too: > > import ConfigParser > import string > > config = ConfigParser.ConfigParser() > > config.read("/home/fab/.abook/addressbook") > > # print summary > print > for number in [2,200]: > print string.upper(config.get(str(number), "email")) > print string.upper(config.get(str(number), "name")) > print string.upper(config.get(str(number), "city")) > print string.upper(config.get(str(number), "address")) > > but the problem seems to be that abook does not write every > field, so I get an exception when there is a field missing: > > Traceback (most recent call last): > File "configparser-example-1.py", line 13, in ? > print string.upper(config.get(str(number), "city")) > File "/usr/lib/python2.4/ConfigParser.py", line 520, in get > raise NoOptionError(option, section) > ConfigParser.NoOptionError: No option 'city' in section: '2' > > Section 2 looks like: > > [2] > name=Andrs Gzi > [EMAIL PROTECTED] > nick=oz > > Is there a workaround? You can construct the parser with a dictionary of defaults: config = ConfigParser.ConfigParser({"city" : "unknown", "zip" : "unknown"}) that kind of thing. Or catch the exceptions. Or use config.options("2") to see what options exist in section 2 before you try to read them. -- http://mail.python.org/mailman/listinfo/python-list
Re: access abook addressbook with curses
On 2006-08-05, Fabian Braennstroem <[EMAIL PROTECTED]> wrote: > Hi, > > I want to get access to my abook address file with python. > Does anyone have some python lines to achive this using > curses? If not, maybe anybody has small python program doing > it with a gui!? You can just parse the abook addressbook with the ConfigParser, try this: import os from ConfigParser import * abook = ConfigParser() abook.read(os.environ["HOME"] + "/.abook/addressbook") for s in abook.sections(): print abook.items(s) -- http://mail.python.org/mailman/listinfo/python-list
Re: solving equation system
On 2006-07-17, TG <[EMAIL PROTECTED]> wrote: > > Ben C wrote: >> On 2006-07-17, TG <[EMAIL PROTECTED]> wrote: >> > Hi there. >> > >> > Anyone knows how to use numpy / scipy in order to solve this ? >> > >> > * A is an array of shape (n,) >> > * X is a positive float number >> > * B is an array of shape (n,) >> > * O is an array of shape (n,) containing only zeros. >> > >> > A.X - B = O >> > min(X) >> >> Are we solving for A, B or X? And what do you mean by min(X)? >> >> If we're solving for X there will be many combinations of A and B for >> which there is no solution. > > Sorry for the poor explanation. I'm trying to put it clear now. > > i've got A and B. I'm looking for X. I made a mistake in my equation >:-/ > > It's more like : > > A.X - B >= O How about this: from random import * def solve(A, B): return reduce(max, (float(b) / a for a, b in zip(A, B))) def test(): A = [random() for i in range(4)] B = [random() for i in range(4)] x = solve(A, B) for a, b in zip(A, B): print a, b, a * x - b test() This only works if all elements of both A and B are positive. > Well, maybe it will be much more simple if I explain the underlying > problem : > > I have an array of N dimensions (generally 2). > - A first calculation gives me a set of integer coordinates inside this > array, which I will call the point W. Is this an array of points, or an array of values, that contains only one point? > - After several other calculations, I've got a set of coordinates in > this N dimensional space that are floating values, and not bound to the > limits of my original N-array. This is the point L. > > What I want to do is to translate the point L along the vector LW Do you mean the vector L - W? (LW is a scalar, assuming dot product). > in order to get a point L' which coordinates are inside the original > N-dimensional array. Then it will be easy to get the closest integer > coordinates from L'. > I'm not sure this is clear ... pretty hard to talk about maths in > english. Not very clear to me I'm afraid! -- http://mail.python.org/mailman/listinfo/python-list
Re: solving equation system
On 2006-07-17, TG <[EMAIL PROTECTED]> wrote: > Hi there. > > Anyone knows how to use numpy / scipy in order to solve this ? > > * A is an array of shape (n,) > * X is a positive float number > * B is an array of shape (n,) > * O is an array of shape (n,) containing only zeros. > > A.X - B = O > min(X) Are we solving for A, B or X? And what do you mean by min(X)? If we're solving for X there will be many combinations of A and B for which there is no solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: embedding executable code in a regular expression in Python
On 2006-07-16, Avi Kak <[EMAIL PROTECTED]> wrote: > Folks, > > Does regular expression processing in Python allow for executable > code to be embedded inside a regular expression? > > For example, in Perl the following two statements > > $regex = qr/hello(?{print "saw hello\n"})mello(?{print "saw > mello\n"})/; > "jellohellomello" =~ /$regex/; > > will produce the output > > saw hello > saw mello > > Is it possible to do the same in Python with any modules that come > with the standard distribution, or with any other modules? You can use sub and make the replacement pattern a function (or any "callable" thing) and it gets called back with the match object: import re def f(mo): if "hello" in mo.groups(): print "saw hello" if "mello" in mo.groups(): print "saw mello" re.sub(r'(hello)(mello)', f, "jellohellomello") Actually I didn't know you could do that in Perl. The time I've found this useful in Python is substitutions to convert e.g. "background-color" into "backgroundColor"; a function turns the c into C. I always assumed in Perl you would need to use eval for this, but perhaps there is another way. -- http://mail.python.org/mailman/listinfo/python-list
Re: Configuring IDLE on Linux
On 2006-07-14, Adonis <[EMAIL PROTECTED]> wrote: > Satya Kiran wrote: >> Hello, >> I have upgraded to Python2.4 on my Red Hat 9.0 Linux box. >> I want to work with IDLE and ran a search to check it's presence. >> Here is what I get. >> >> [EMAIL PROTECTED] bin]# find / -iname idlelib >> /usr/local/lib/python2.4/idlelib >> >> [EMAIL PROTECTED] bin]# cd /usr/local/lib/python2.4/idlelib >> [EMAIL PROTECTED] idlelib]# python PyShell.py >> ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** >> >> How do I resolve this and get IDLE working? >> >> thanks in advance, >> Kiran Satya > > You must have the Tk libraries present in your system for Python to > compile Tkinter. Go to your distribution's site and try to see if they > offer a TCL/TK package and install it (being that it is Redhat they most > definitely must have one). Then recompile Python. This is exactly right, on a SUSE system (at least) it's the tk-devel and tcl-devel packages you need to have installed, because you're building Python and it needs to link against those things, not just use them. So although tcl/tk on its own it usually installed by default, you don't always get those -devel packages in a default setup. -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessors in Python (getters and setters)
On 2006-07-15, Gerhard Fiedler <[EMAIL PROTECTED]> wrote: > On 2006-07-15 06:55:14, mystilleef wrote: > >> In very well designed systems, the state of an object should only be >> changed by the object. > > IMO that's not quite true. Ultimately, the state always gets changed by > something else (user interaction, physical events); very few objects are > completely self-contained in their behavior. > > In most systems (and you possibly have written some of them) are objects > whose state gets changed by other objects -- possibly through the > intermediation of setter methods that do nothing else but set the state. > There's no conceptual difference between directly setting the state or > calling a setter function that does nothing else but directly setting the > state -- except for one unnecessary level of indirection in the latter. The conceptual difference is that a function call is more like an "event", a variable is more like a "process". An object that provides a setter is a process that is prepared to engage in this "set event". An object that exposes a variable is a process that interacts with this variable which the user is also invited to interact with concurrently. So with a setter in the API, conceptually, there are two processes sharing the set event: the object itself, and the process that's calling the setter. With an exposed variable, there are three: the object, the variable in between, and the calling process. Restricting yourself to setters and getters is a bit like saying we build a machine that only has touch-keys and lights on the outside. Shared variables are more like a machine with levers and dials you set, and bits that pop up, like the numbers on mechanical cash-registers. They have "state" on the outside, not just on the inside. Such designs can be less tolerant of unsympathetic input-- think how easy it is to jam up an old-fashioned typewriter if you just press a few keys at the same time. There isn't any practical difference, as you say, if all the setter does is set. But it might easily do a few other subtle things, in particular wait for a good moment to actually effect the change. -- http://mail.python.org/mailman/listinfo/python-list
Re: Absolute noob to Linux programming needs language choice help
On 2006-06-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hey guys, > > I am absolutely new to Linux programming, with no w##s programming > experience except a small amount of C++ console apps. > Reasonably new to Linux, BSD etc, got good sound networking base of > knowledge and dont have any problem working the command line etc. > > I want to learn a language that I can use in my networking duties that > is most likely to be of use to me. I have a few choices I can think of > being: > > Python > Perl > C > > Any other Langs out there that would be better suited? > > I want to be able to use the app's I write in OpenBSD and RH versions > of Linux > > What would you reccomend (Unbiased opinion please, I'm after the > functionality I'll love it later :) ) My favourite's Python, but Tcl is definitely worth a look. It's been around a bit longer than Python (so more time for every conceivable problem to have been met by someone and fixed), and I'm not an expert but I think it's particularly good for things like sockets-- they're just sort of built in and are very easy to work with. -- http://mail.python.org/mailman/listinfo/python-list
Re: clear memory? how?
On 2006-05-10, Gr�goire Dooms <[EMAIL PROTECTED]> wrote: > Ben C wrote: >> On 2006-05-09, Ben C <[EMAIL PROTECTED]> wrote: >>> def clearall(): >>> all = [var for var in globals() if "__" not in (var[:2], var[-2:])] >>> for var in all: >>> del globals()[var] >>> >>> since I think magic things always start and end with __. >> >> Oops, got that wrong anyway: >> >> should be: >> >> all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__")] > > You can also add > and var != "clearall" > >:-) Good point :) I've heard of "write once run anywhere", but this is "run once". -- http://mail.python.org/mailman/listinfo/python-list
Re: clear memory? how?
On 2006-05-09, Ben C <[EMAIL PROTECTED]> wrote: > def clearall(): > all = [var for var in globals() if "__" not in (var[:2], var[-2:])] > for var in all: > del globals()[var] > > since I think magic things always start and end with __. Oops, got that wrong anyway: should be: all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__")] -- http://mail.python.org/mailman/listinfo/python-list
Re: do "some action" once a minute
On 2006-05-09, Petr Jakes <[EMAIL PROTECTED]> wrote: > I would like to do "some action" once a minute. You can try the sched module (import sched). You give it a time at which to call a callback. Then in the callback you can reset the "alarm" for a minute later, using enterabs. If the task might take longer than a minute, it just means you'll be setting an alarm for a time in the past, but it should still get called. But there is another problem, which is that the queue will presumably get very big over time, so you'll need to clear it out now and again with empty()... which means keeping track of the event objects yourself, which is annoying. -- http://mail.python.org/mailman/listinfo/python-list
Re: clear memory? how?
On 2006-05-09, Diez B. Roggisch <[EMAIL PROTECTED]> wrote: > N/A wrote: > >> Hi all, >> I am learning Python. Just wondering how to clear saved memory in >> Python? Like in Matlab I can simply use "clear all" to clear all saved >> memory. > > You don't - python does it for you. It is called garbage collection. All you > have to to is get into granny-mode(tm): forget about things. That means: > once an object is not referenced by your code anymore, it will be cleaned > up. I think Matlab's "clear all" is more like what you might call "del all" in python. You could perhaps define it like this: def clearall(): all = [var for var in globals() if var[0] != "_"] for var in all: del globals()[var] This deletes any global not starting with an _, since it's probably inadvisable to delete this lot: {'__builtins__': , '__file__': '/etc/pythonstart', '__name__': '__main__', '__doc__': None} More correct I suppose might be something like this: def clearall(): all = [var for var in globals() if "__" not in (var[:2], var[-2:])] for var in all: del globals()[var] since I think magic things always start and end with __. Looking briefly at GNU octave which is similar to MatLab, clear all may also del all the locals; so you can do something similar with the builtin function locals(). -- http://mail.python.org/mailman/listinfo/python-list
Re: self modifying code
On 2006-04-29, Robin Becker <[EMAIL PROTECTED]> wrote: > When young I was warned repeatedly by more knowledgeable folk that self > modifying code was dangerous. > > Is the following idiom dangerous or unpythonic? > > def func(a): > global func, data > data = somethingcomplexandcostly() > def func(a): > return simple(data,a) > return func(a) It looks quite clever (a bit too clever ... :) > It could be replaced by > > data = somethingcomplexandcostly() > def func(a): > return simple(data,a) > > but this always calculates data. Why not just: data = None def func(a): global data if not data: data = somethingcomplexandcostly() return simple(data, a) Or nicer to use a "singleton" perhaps than a global, perhaps something like this: class Func(object): exists = False def __init__(self): assert not Func.exists Func.exists = True self.data = None def simple(self, a): assert self.data is not None # ... do something with self.data presumably return something def __call__(self, a): if self.data is None: self.data = somethingcomplexandcostly() return self.simple(a) func = Func() func(a) -- http://mail.python.org/mailman/listinfo/python-list
Re: Events in Python?
On 2006-04-26, nikie <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > >> Here is another non-pythonic question from the Java Developer. (I beg >> for forgiveness...) >> >> Does Python have a mechanism for events/event-driven programming? >> >> I'm not necessarily talking about just GUIs either, I'm interested in >> using events for other parts of an application as well. >> >> If there isn't some sort of event mechanism built into Python, where >> might I find some information about implementing one? > > Maybe I got your question wrong, but why not simply use something like: > > class Sender: > def __init__(self, event): > self.event = event > > def raiseEvent(self): > self.event("Event") > > class Receiver: > def receiveEvent(self, msg): > print "Received %r" % msg > > r = Receiver() > s = Sender(r.receiveEvent) > s.raiseEvent() > > You can pass around functions and bound methods, I always found that's > often a really good substitute for full-blown event mechanisms. Actually I'd say full-blown event mechanisms are a poor substitute for passing around bound-methods :) -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
On 2006-04-21, Alexis Roda <[EMAIL PROTECTED]> wrote: > Ben C escribió: >> On 2006-04-21, Ben C <[EMAIL PROTECTED]> wrote: >> Having said that, I attempted to confirm this using def rather than >> lambda, and encountered something I cannot explain at all-- it appears >> that the functions are getting redefined whenever they are called, to >> effect a kind of "dynamic scoping" behaviour. I would appreciate any >> explanation anyone can give of this: >> >> fns = [] >> for y in range(2): >> def fn(): >> yy = y # exactly the same with yy = int(y) >> print "defining fn that returns", yy >> return yy >> print "Appending at", y >> print fn, fn() >> fns.append(fn) > > > yy = y does assign y's current value (current == fn call time, not fn > definition time). To return 0 and 1 as expected you should create a > "different/private" y for every fn's definition. > > > > fns = [] > for y in range(2): > def fn(y=y): > yy = y > print "defining fn that returns", yy > return yy > print "Appending at", y > print fn, fn() > fns.append(fn) > > > Yes; the difficulty is that the body of the function is executed (obviously) every time you call it. The body of the function reads y which is a global variable and has whatever value it has at the time. The parameters are the only part of a function definition where you get to write some code that initializes things in the function's "frame" when the function is defined rather than when it's called. I got confused because I was thinking of yy = y in the body of fn's definition as an initialization, not as an assignment. In other languages it's possible to distinguish, but not in Python. Really this is what classes are for in Python: def f(x): return x * x class fn(object): def __init__(self, y): # "define-time" things are here self.y = y def __call__(self, x): # "call-time" things are here return f(x) * self.y fns = [fn(i) for i in range(1, 10)] for f in fns: print f(1) is I think quite a good way to do this. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
On 2006-04-21, Ben C <[EMAIL PROTECTED]> wrote: > On 2006-04-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: >> Hello, >> >> I need your help understanding lambda (and doing it a better way >> without). >> >> f = lambda x : x*x >> [...] >> # the idea is now to give the definition of the multiplication of >> functions and integers >> # (f * c)(xx) := f(x)*c >> [lambda xx: f(xx)*y for y in range(1,5)][0](1) >> # returns 4 >> # I would expect 1*x*x = 1 > > If you change the 5 in range(1,5) to a 10, this returns 9. > > So it looks like each of the lambda xx : f(xx) * y is getting the last > value of y. > > I can do this for example: > > f = lambda x : x * x > fns = [lambda xx: f(xx)*y for y in range(1,10)] > for fn in fns: > print fn(1) > > And I get 9 printed out 9 times. > > It does seem a bit surprising, but I suppose if you think about it > there's only one "y"-- the one in the outer scope. This one variable is > bound 9 times, to a new value each time. > > What one would need for it to work would be for each of the functions to > have a variable in its own scope. But you can't, as far as I know, > create local variables in functions defined with lambda. Having said that, I attempted to confirm this using def rather than lambda, and encountered something I cannot explain at all-- it appears that the functions are getting redefined whenever they are called, to effect a kind of "dynamic scoping" behaviour. I would appreciate any explanation anyone can give of this: fns = [] for y in range(2): def fn(): yy = y # exactly the same with yy = int(y) print "defining fn that returns", yy return yy print "Appending at", y print fn, fn() fns.append(fn) print "OK" for fn in fns: print "Calling", fn print fn, fn() y = 10 for fn in fns: print "Calling", fn print fn, fn() The output: Appending at 0 defining fn that returns 0 0 Appending at 1 defining fn that returns 1 1 OK Calling defining fn that returns 1 1 Calling defining fn that returns 1 1 Calling defining fn that returns 10 10 Calling defining fn that returns 10 10 -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda
On 2006-04-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello, > > I need your help understanding lambda (and doing it a better way > without). > > f = lambda x : x*x > [...] > # the idea is now to give the definition of the multiplication of > functions and integers > # (f * c)(xx) := f(x)*c > [lambda xx: f(xx)*y for y in range(1,5)][0](1) > # returns 4 > # I would expect 1*x*x = 1 If you change the 5 in range(1,5) to a 10, this returns 9. So it looks like each of the lambda xx : f(xx) * y is getting the last value of y. I can do this for example: f = lambda x : x * x fns = [lambda xx: f(xx)*y for y in range(1,10)] for fn in fns: print fn(1) And I get 9 printed out 9 times. It does seem a bit surprising, but I suppose if you think about it there's only one "y"-- the one in the outer scope. This one variable is bound 9 times, to a new value each time. What one would need for it to work would be for each of the functions to have a variable in its own scope. But you can't, as far as I know, create local variables in functions defined with lambda. -- http://mail.python.org/mailman/listinfo/python-list
Re: a subprocess qns
On 2006-04-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > hi > i wanted to start execute a command and put it in the background. i am > using Unix. If you use subprocess, or even os.spawn, it should be portable and work on all systems (although the docs list some restrictions). > Usually i start this command using something like this : > "/path/somecmd &" with the "&" to put it to background. You can still do that: os.system("/bin/mycmd &"), or use subprocess.Popen with True in its shell parameter. os.system invokes the shell, so this is not portable-- you must have a shell in which & means what you want (it works at least on bash and probably on some other Unix shells). > i looked at the subprocess module docs and came across this statement > Replacing os.spawn* > --- > P_NOWAIT example: > pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") >==> > pid = Popen(["/bin/mycmd", "myarg"]).pid > > > Can i ask if P_NOWAIT means the same as "&" ?? so if it is, then this > statement I think it does. > pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") > > will put mycmd into background and return to the caller...? Should do. -- http://mail.python.org/mailman/listinfo/python-list
Re: Activating Batch Files from Python
On 2006-04-19, Jeff Groves <[EMAIL PROTECTED]> wrote: >>How about sourcing it from a shell, then using that same shell instance >>to run the programs? > > How would I do that? As I've said, I haven't found a Python command > that lets you send multiple commands to the same shell yet. If I could, > my problem would be solved. If I understood correctly I think the idea is to run vars.bat first, then run the Python program in _that_ shell (so it inherits the environment) and then launch the other programs from the Python program. i.e. C:\> vars.bat C:\> python launcher.py You could put those commands in a batch file. So the outermost thing you run is a batch file, which starts Python, which starts the other programs. Seems quite a neat solution. -- http://mail.python.org/mailman/listinfo/python-list
Re: Activating Batch Files from Python
On 2006-04-19, Jeff Groves <[EMAIL PROTECTED]> wrote: > I'm writing a launcher that should do the following: > > 1. Activate a .bat file to set environmental variables. > 2. Start 3 programs, using said environmental variables as arguments. > > However, I can't get the environmental variables to stick because all > of Pythons' system start/open functions split off into their own little > subshells, therefore the .bat file doesn't affect the main shell. > > How can I use the .bat file to set environmental vars from Python? You can try launching a single shell with subprocess.Popen, and run everything inside that: from subprocess import * p = Popen("cmd", stdin = PIPE, stdout = PIPE) output, err = p.communicate(""" vars.bat prog1.exe prog2.exe prog3.exe """) print output I can't test this because I don't have a Windows system. Otherwise, as others have suggested, replace vars.bat with modifications to os.environ. -- http://mail.python.org/mailman/listinfo/python-list
Re: Decode html, or is it unicode, how?
On 2006-04-17, <[EMAIL PROTECTED]> <[EMAIL PROTECTED]> wrote: > Hi All, > I've done a bunch of searching in google and in python's help, but, > I haven't found any function to decode a string like: > Refresh! (ihenvyr) > In to plain english. > [...] I needed to do that the other day, and did it like this: def decode(line): pat = re.compile(r'(\d+);') def sub(mo): return unichr(int(mo.group(1))) return pat.sub(sub, unicode(line)) there may well be a better way though. -- http://mail.python.org/mailman/listinfo/python-list
Re: list.clear() missing?!?
On 2006-04-14, Sergei Organov <[EMAIL PROTECTED]> wrote: > Dennis Lee Bieber <[EMAIL PROTECTED]> writes: >> It always means bind... But if the LHS is a mutable object, AND you >> have specified a component of that object, it is the component that is >> being rebound... >> >> lst[:] = [] >> [...] > Me gets corrected, thanks. Now I need to unroll my mind somewhat back to > figure out when and why I started to believe it sometimes assigns ;) I used to think it assigned with things like integers, because if you write: a = 5 b = a b += 1 print a a is still 5. So it looked like a and b stored values and b got a "copy" of a's value. But this is the wrong interpretation, b += 1 is really b = b + 1, and rebinds b. You can see what's really going on if you use the id() function on a and b during these operations. The other reason for the confusion is that I think in Java a variable either stores a value, in the case of numbers, or a reference in the case of objects (or a copy-on-write reference, which behaves like a value, in the case of strings). In Python it's better to think of it as always a reference, and to think in terms of immutable vs. mutable objects that are referred to. If it weren't for the id() function I think the difference between "variable stores value", "variable stores immutable reference" and "variable stores copy-on-write reference" would be implementation detail and never visible to the programmer. That's why it's easy to be "confused"-- most of the time these interpretations are equivalent, so it doesn't matter which you work with. -- http://mail.python.org/mailman/listinfo/python-list
Re: trying to grasp OO : newbie Q?
On 2006-04-13, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hi, > > I just started with Python and I am new to OO programming. > Here is a simple code: > " > class Obj: > myVar = 1 > > def __init__(self): > myVar = 2 > > # > > > myObj = Obj() > > print myObj.myVar > " > > The output is of this script is '1'. I would except it to be '2'. > I not understanding something fundamentally here. Good example, it demonstrates these things quite well. My understanding of this is as follows: myVar is a class variable, because you define it in the body of the class statement (not in any method). In Python, classes and instances can both be thought of as dictionaries, i.e. sets of key-value pairs. In this example, Obj is a class and myObj is an instance. When you write print myObj.myVar, the interpreter looks first in myObj for a value matching the key "myVar". It doesn't find one there (I explain why not below). So it continues the search in myObj's class, which is the class Obj. It does find one there, with the value 1, so that's what you get. The myVar that you define in __init__ is not an instance variable, but a local variable (local to the function __init__). To make an instance variable you have to use "self" explicitly: def __init__(self): self.myVar = 2 If you write it like this, your program will print out 2. People coming from languages like C++ where this-> is implicit sometimes forget to write "self."; in Python you always need it to get at the instance. -- http://mail.python.org/mailman/listinfo/python-list
Re: new-style classes and len method
On 2006-04-13, Thomas Girod <[EMAIL PROTECTED]> wrote: > Hi there. > > I'm trying to use new-style classes, but there is something i'm > obviously missing > > here it is : > > class Data(list): > __slots__ = ["width", "height", "label"] > > def __init__(self,width,height,label=None): > list.__init__(self) > self.width = width > self.height = height > self.label = label > > def clear(cls): > while len(cls) > 0: del cls[0] > return > clear = classmethod(clear) > > #> d = Data(2,2) > #> d.clear() > TypeError: len() of unsized object > > off course it was working with : > > [...] > def clear(self): > while len(self) > 0: del self[0] > return > > So, I guess you can't use "cls" as a replacement for "self". So, what > do I have to use ??? You can use cls in a classmethod to refer to the class. You can use any name you want (well so long as it's not a "reserved word" I suppose). The same is true of self, it's just a param name (quite unlike JavaScript's "this"...). But I don't think it makes sense for clear to be a classmethod, since you presumably want a method that clears instances of lists? The error is because you're trying to take the len of the class itself, not the len of an instance of it. What you had before was OK. Although you don't need to write the loop, just del self[:] will do, and you can leave out the return statement if you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python2CPP ?
On 2006-04-12, Michael Yanowitz <[EMAIL PROTECTED]> wrote: > Hello: > >One topic that has always interested me are the Language translators. > Are there any that convert between Python and C++ or Python and Java? > I remember seeing one that converts from Python to or from Perl but couldn't > find it on a quick google search. I did find a Python2C > http://sourceforge.net/projects/p2c/ and I found: > http://www.strout.net/python/ai/python2c.py which are obviously incomplete. >I know there have been many discussions recently regarding C and C++. > I am (or is it - was?) a C/C++ programmer for over 15 years. Just started > with Python as we need to write come quick code in script form which can > be generated and run through an interpreter. >If not could there be a converter from Python to/from Language X and > from Language X to/from C or C++? I've heard of an incomplete Python to C++ translator called "Shedskin" http://pycode.com/modules/?id=40&PHPSESSID=1919541171352770795c2bcee95b46bd There's also a GNU project afoot for a Python to Scheme translator which I saw on http://savannah.gnu.org but now cannot find. This would be an interesting project, I suppose you'd write it in Python, then it could bootstrap itself into Scheme and C. Scheme can be translated to C using chicken: http://www.call-with-current-continuation.org/index.html -- http://mail.python.org/mailman/listinfo/python-list
Re: RegExp question
On 2006-04-11, Michael McGarry <[EMAIL PROTECTED]> wrote: > Tim, > > for some reason that does not seem to do the trick. > > I am testing it with grep. (i.e., grep -e '(and|or|xor)\s*#' myfile) Try with grep -P, which means use perl-compatible regexes as opposed to POSIX ones. I only know for sure that -P exists for GNU grep. I assumed it was a Python question! Unless you're testing your Python regex with grep, not realizing they're different. Perl and Python regexes are (mostly?) the same. I usually grep -P because I know Python regexes better than any other ones. -- http://mail.python.org/mailman/listinfo/python-list
Re: RegExp question
On 2006-04-11, Michael McGarry <[EMAIL PROTECTED]> wrote: > Hi, > > I would like to form a regular expression to find a few different > tokens (and, or, xor) followed by some variable number of whitespace > (i.e., tabs and spaces) followed by a hash mark (i.e., #). What would > be the regular expression for this? re.compile(r'(?:and|or|xor)\s*#') -- http://mail.python.org/mailman/listinfo/python-list
Re: About classes and OOP in Python
On 2006-04-11, Michele Simionato <[EMAIL PROTECTED]> wrote: > Roy Smith wrote: > >> That being said, you can indeed have private data in Python. Just prefix >> your variable names with two underscores (i.e. __foo), and they effectively >> become private. Yes, you can bypass this if you really want to, but then >> again, you can bypass private in C++ too. > Wrong, _foo is a *private* name (in the sense "don't touch me!"), __foo > on the contrary is a *protected* name ("touch me, touch me, don't worry > I am protected against inheritance!"). > This is a common misconception, I made the error myself in the past. Please explain! I didn't think _foo meant anything special, __foo expands to _classname__foo for some sort of name-hiding. What am I missing? -- http://mail.python.org/mailman/listinfo/python-list
Re: UnicodeDecodeError help please?
On 2006-04-07, Robin Haswell <[EMAIL PROTECTED]> wrote: > Okay I'm getting really frustrated with Python's Unicode handling, I'm > trying everything I can think of an I can't escape Unicode(En|De)codeError > no matter what I try. > > Could someone explain to me what I'm doing wrong here, so I can hope to > throw light on the myriad of similar problems I'm having? Thanks :-) > > Python 2.4.1 (#2, May 6 2005, 11:22:24) > [GCC 3.3.6 (Debian 1:3.3.6-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. import sys sys.getdefaultencoding() > 'utf-8' import htmlentitydefs char = htmlentitydefs.entitydefs["copy"] # this is an HTML © - a copyright symbol print char > © str = u"Apple" print str > Apple str + char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte a = str+char > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'utf8' codec can't decode byte 0xa9 in position 0: > unexpected code byte Try this: import htmlentitydefs char = htmlentitydefs.entitydefs["copy"] char = unicode(char, "Latin1") str = u"Apple" print str print str + char htmlentitydefs.entitydefs is "A dictionary mapping XHTML 1.0 entity definitions to their replacement text in ISO Latin-1". So you get "char" back as a Latin-1 string. Then we use the builtin function unicode to make a unicode string (which doesn't have an encoding, as I understand it, it's just unicode). This can be added to u"Apple" and printed out. It prints out OK on a UTF-8 terminal, but you can print it in other encodings using encode: print (str + char).encode("Latin1") for example. For your search engine you should look at server headers, metatags, BOMs, and guesswork, in roughly that order, to determine the encoding of the source document. Convert it all to unicode (using builtin function unicode) and use that to build your indexes etc., and write results out in whatever you need to write it out in (probably UTF-8). HTH. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert string
On 2006-04-05, Scott David Daniels <[EMAIL PROTECTED]> wrote: > Ben C wrote: >> ... But this puts an extra space on the end (so did the print i, >> version above). > Actually, no (the trailing-comma prints do a funny dance). > Check it out: [...] You're right, I tried it! Thanks for that. Useful, although I hope Python doesn't turn into a "do what I mean" language... -- http://mail.python.org/mailman/listinfo/python-list
Re: how to convert string
On 2006-04-05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > I want to print number 0 to 9 in one line like this > 0 1 2 3 4 5 6 7 8 9 > > if I do like this, it prints in different lines > > for i in xrange(10): > print i for i in xrange(10): print i, should work (comma after the i). > so i tried like this > > str = "" > for i in xrange(10): > str = i + " " > print str > > but i want to know how convert int i to string. There's a builtin function str (better not to call your string str). Here I've called it s: s = "" for i in xrange(10): s = str(i) + " " print s But this puts an extra space on the end (so did the print i, version above). Might be better therefore to use string.join: import string s = string.join(map(str, xrange(10)), " ") print s -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and SuSE 10.0
On 2006-04-05, Steve <[EMAIL PROTECTED]> wrote: > Hello, > > I was wondering if there is a wxPython RPM for SuSE 10.0 available. I > Googled for it with no luck, but I'm hopeful that there is one out > there. http://www.novell.com/products/linuxpackages/professional/python-wxgtk.html is the package you want I suppose, it's called python-wxGTK-2.6.1.0-4.i586.rpm. You get it with SUSE 10.0 pro but not in openSUSE. Don't know why not as it's GPL. So it exists, I can tell you that much... not sure where you can get it though. Googling the exact name throws up a few things. Ah here we are: http://www.vislab.uq.edu.au/research/accessgrid/software/suse/wxWindows/RPMS/python-wxGTK-2.6.1.0-4.i586.rpm -- http://mail.python.org/mailman/listinfo/python-list
Re: how to capture os.execvp into variable
On 2006-03-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > hi > i am using this code to run a ps command in unix > > def run(program, *args): > pid = os.fork() > if not pid: > os.execvp(program, (program,) + args) > return os.wait()[0] > > run("ps", "-eo pid,ppid,args") > > It runs fine, but i wish to store the results into a variablehow > can i do this ? I tried > to put ret=os.execvp(program, (program,) + args) but ret has no value > thanks Do you mean you want the output of ps? That seems most likely. In that case use os.popen. p = os.popen("ps -eo pid,ppid,args") output = p.read() p.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Writing web bots in python
On 2006-03-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > Hello, > I hav a question..How do I write a webbot that logs onto some website, > fills text into a textbox and submit that form, Sorry I am a novice in > python, apparently I have to use urllib, but I hav a few queries on > this, What happens when there are more input interfaces..does urllib > make somekind of a template when it does so..need more info on > this..links and tutorilas would be appreciated..thanx Not strictly Python related, but if you use Firefox, get the "Tamper Data" extension for it. This lets you see exactly what Firefox is submitting in the formdata, and what the urls are of the cgi scripts etc. I usually invoke a program called curl from python with os.popen, but this twill someone has suggested looks interesting. -- http://mail.python.org/mailman/listinfo/python-list
Re: calling another python file within python
On 2006-03-14, Kevin <[EMAIL PROTECTED]> wrote: > i have a python file called pyq which outputs stock quotes, currently i > also have a html file that takes stock ticker inputs, i would like to > bridge the two by building another program that takes the html inputs > and uses them to call the pyq stock ticker program and then output them > into a text file... > > any idea how to do this? my tentative code is: > > > > #!/usr/bin/python > > import os > import urllib > os.system("python pyq.py ibm > text1.txt") Rather than invoke the shell (which is what system does), you can just do it all from Python. Something like: import pyq pyq.run("ibm") Then in pyq.py, you could have something like this: def run(filename): # do whatever... def main(): # check args etc.. run(sys.argv[1]) if __name__ == "__main__": main() This way pyq would work from the shell if you wanted to run it that way, and also as a module. Not quite sure of the details of the input. If the other program is creating this file ibm which you're immediately reading as soon as it appears you'd probably be better off with a pipe. See Python docs for the "socket" module. Or less portably and if you're on a UNIX system you could use a named pipe (created with mkfifo). > note: currently the text1.txt outputted is just blank, however if i > run the command normally as 'python pyq.py ibm' in the command line, > it works correctly and gives me the price of ibm. If you launch pyq.py like this it has to be in the current working directory of the other program. If you just go os.system("pyq.py ibm") and pyq.py has the #! business at the start of it, then pyq.py has to be in your PATH. Otherwise it should work. So long as you're sure the file ibm has been created by this point. One of the benefits of doing it with import instead (the thing I described above) is you don't have to worry about the shell and its environment, or what PATH is, but only the Python environment (PYTHONPATH, sys.path, that kind of thing). It's more portable. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary project
> So here's a different approach, which I think does meet the spec: > > from itertools import tee > def allwords2(alphabet="abcd", maxlen = 4): > def wordgen(): > for char in alphabet: > yield char > for partial in allwordstee[1]: > if len(partial) == maxlen: > raise StopIteration > for char in alphabet: > yield partial+char > #tee creates two copies of the iterator: > # one is returned to the caller > # the other is fed back to the generator > allwordstee = tee(wordgen()) > return allwordstee[0] Very neat. I never knew about tee. -- http://mail.python.org/mailman/listinfo/python-list
Re: Dictionary project
On 2006-03-11, Michael Spencer <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: >> Hi All, >> First, I hope this post isn't against list rules; if so, I'll take note in >> the future. >> >> I'm working on a project for school (it's not homework; just for fun). >> For it, I need to make a list of words, starting with 1 character in length, >> up to 15 or so. >> It would look like: >> >> A B C d E F G ... Z Aa Ab Ac Ad Ae Aaa Aab Aac This is really "permutations" you're trying to work out I think. Python generators are quite good for this kind of thing. This works, but isn't especially pretty: import string def letters(): while 1: for char in string.lowercase: yield char yield None def count(n): digits = [letters() for i in range(n)] s = [d.next() for d in digits] def output(): print string.join(reversed(s), "") output() while 1: i = 0 while 1: s[i] = digits[i].next() if s[i] is not None: break s[i] = digits[i].next() i += 1 if i == n: return output() count(3) Obviously you can call count with any number, and if you just change letters() to yield members of some other set you can make permutations of different things. I think 15 is going to give you rather a lot of permutations though. 1677259342285725925376 to be precise. You might have to wait a rather long time. -- http://mail.python.org/mailman/listinfo/python-list