From rkern at ucsd.edu Mon Jun 27 07:47:04 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 27 Jun 2005 04:47:04 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <200506260559.18488.hancock@anansispaceworks.com> Message-ID: Steven D'Aprano wrote: > On Sun, 26 Jun 2005 23:22:00 -0500, Terry Hancock wrote: > >>>You need to differentiate >>> a = b = 1 >>>from >>> a = b == 1 >> >>Okay, I see what you mean. I can't ever recall having needed the >>second form, though. >> >>Of course, you could still do assignment like this: >> >>a, b = (1,)*2 >> >>But I guess that's not exactly elegant. ;-) > > In general that is not the same thing as a = b = obj. > > py> a, b = ([], []) > py> a.append(1) > py> b > [] > py> a = b = [] > py> a.append(1) > py> b > [1] What you wrote isn't, but what Terry wrote is. In [1]: a, b = ([],)*2 In [2]: a.append(1) In [3]: b Out[3]: [1] In [4]: a is b Out[4]: True -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From chinook.nr at tds.net Sat Jun 18 14:53:48 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 18 Jun 2005 14:53:48 -0400 Subject: OO approach to decision sequence? References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> <42B3D2BC.3050406@po-box.mcgill.ca> <1119100225.438987.221850@f14g2000cwb.googlegroups.com> Message-ID: <0001HW.BED9E5FC0007947DF0284550@news.gmane.org> On Sat, 18 Jun 2005 09:10:25 -0400, George Sakkis wrote (in article <1119100225.438987.221850 at f14g2000cwb.googlegroups.com>): > "Chinook" wrote: > >> I understand what you are saying. The point I'm messing up my head with >> though, is when the entity (tree node in my case or variable record content >> deconstructing in the aspect example I noted) is not an instance of a class >> already - it is obtained from an external source and only decipherable by >> its >> content. >> >> In practical terms that leaves me with some decision sequence regardless and >> I was wondering (from what Chris Smith said) how that might be done in OOP. >> The whole problem may be that I'm reading too much into what Chris said :~) >> I will dig back through the Tutor archives as you suggested. > > What you are looking for is what is called the 'factory method pattern' > (http://en.wikipedia.org/wiki/Factory_method_pattern) and it's one of > the cases where OOP doesn't eliminate the if/elif/elif (or switch in > C++/Java). That's ok though because, as you noticed, at some point you > have to take a decision. What's important is the "once and only once" > principle, that is all the decision logic is encapsulated in a single > method (or in python in a single function) instead of being replicated > every time you want to use an existing Node. > > Regards, > George > > George, Yes, that answers my question of how the issue is approached in OOP - thank you. I'll do some more googling to find examples in Python and then try refactoring my little utility. The effect on my little utility will be a verbose abstraction of a specific efficient top-down approach, but the intended goal is to learn how to better facilitate extensibility. Thanks to all that took the time to wade through my post and especially to those that offered their thoughts, Lee C From skromta at gmail.com Sun Jun 12 09:35:46 2005 From: skromta at gmail.com (Kalle Anke) Date: Sun, 12 Jun 2005 15:35:46 +0200 Subject: How to get/set class attributes in Python References: Message-ID: <0001HW.BED206D2002D2163F0407550@news.gmane.org> On Sun, 12 Jun 2005 13:59:27 +0200, deelan wrote (in article ): > the pythonic way is to use "property" (as others have already explained) > only when is *stricly necessary*. this may clarify things up: Thanks for the link (although Java was only one of the languages I was thinking of). Anyway, I got another "problem" (read: being used to do it like this in other languages). I'm used to use statically typed languages and for me one of the advantages is that I can be sure that a parameter is of a certain type. So in Java I could write void doSomething( data : SomeClass ){ ... } and I would be sure at compile time that I would only get SomeClass objects as parameters into the method. In learning Python I've understood that I should write code in such a way that it can handle different data and this is fine with me. But what if I have a class where different attributes should only have values of a certain type and everything else is an error. For example, if I have an class that defines three attributes: first and last name plus email address. The only valid data types for the first two are strings and for the last an EmailAddress class. How should I handle this in Python? Should I use just don't care (but I'm going to send the data to a database so I need to ensure that the data is OK)? Should I use 'isinstance' and check manually? Or should I do something else? (I've been trying to figure out this and other things but I haven't found much in books or web sites) jem From peter at engcorp.com Tue Jun 14 07:45:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 07:45:13 -0400 Subject: case/switch statement? In-Reply-To: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Message-ID: D H wrote: > Peter Hansen wrote: >> With a case statement, on the other hand, you *know* that it must be >> just simple conditionals (a series of x == some_constant tests), so >> you don't need to look at all the cases, just the one that interests you. > > Since you and Steve Holden agree that a case statement is useful, why > don't you propose it for python, or add it to the wiki page for Python > 3000. Two simple reasons. 1. You forgot my previous comment that "in current Python the equivalent approach is, of course, a dictionary of some kind, though it's arguable whether this is as clean in many cases as a case statement would be." 2. Just because something is "useful" doesn't mean it should be added to Python. The bar should be set much higher, and should include at least "and significantly better than any existing alternative way of doing the same thing." Now go read point 1 again... ;-) My point was not to suggest that I want a case statement in Python, nor even that a case statement is a good thing to have in a language (though it might be... it's not my place to say). My point was simply to point out that performance is not the only reason to use a case statement. -Peter From iseestars at gate.net Thu Jun 9 06:17:38 2005 From: iseestars at gate.net (inhahe) Date: Thu, 9 Jun 2005 06:17:38 -0400 Subject: splitting strings with python References: <1118308380.823382.146430@g47g2000cwa.googlegroups.com> Message-ID: wrote in message news:1118308380.823382.146430 at g47g2000cwa.googlegroups.com... > im trying to split a string with this form (the string is from a > japanese dictionary file with mulitple definitions in english for each > japanese word) > > > str1 [str2] / (def1, ...) (1) def2 / def3 / .... (2) def4/ def5 ... / > > > the varibles i need are str*, def*. > > sometimes the (1) and (2) are not included - they are included only if > the word has two different meanings > > > "..." means that there are sometimes more then two definitions per > meaning. > > > im trying to use the re.split() function but with no luck. > > Is this possible with python, or am i dreamin!? > > All the best, > > . > i don't think you can do it with string.split, although i guess you could do it with re.split, although i think it's easier to use re.findall. import re re.findall("[a-zA-Z][ a-zA-Z0-9]*", inputstring) should work. From lycka at carmen.se Fri Jun 10 08:27:53 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 10 Jun 2005 14:27:53 +0200 Subject: circular import Module In-Reply-To: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > Hello, > > I have two modules (file1.py and file2.py) > Is that ok in python (without any weird implication) if my module > import each other. I mean in module file1.py there exist command import > file2 and in module file2.py there exist command import file1? Even if it works, it gives you a hint of a design problem that might come back and bite you later. If file1 depends on file2 *and* vice versa, it seems those two modules are tightly coupled. Perhaps they should be one module rather than two, or perhaps some redesign should be made to untangle this cycle. It happens that old Java programmers make one module per class when they start using Python. That's more or less equivalent of never using more than 8.3 characters in filenames in modern operating systems, or to make a detour on your way to work because there used to be a fence blocking the shortest way a long time ago... :) Due to the cycle, you can never use file1 without file2 or vice versa. Why do you then want it to be two different modules instead of one? As others noted, you can usually fix your cycle problems by importing in a local scope, but just because you can, it doesn't mean that you should... From Baboon1234 at aol.com Thu Jun 2 11:11:41 2005 From: Baboon1234 at aol.com (Baboon1234 at aol.com) Date: Thu, 2 Jun 2005 11:11:41 EDT Subject: help Message-ID: <1d7.3db374ed.2fd07bad@aol.com> When i try to open IDLE(python GUI) it says that i have a socket error: conection refused what do i do to fix this -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjbottaro at alumni.cs.utexas.edu Mon Jun 6 12:59:26 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Mon, 06 Jun 2005 11:59:26 -0500 Subject: how to get name of function from within function? References: Message-ID: Hey again Steven, I'm still having problems... Steven Bethard wrote: > Something like this might work: > > py> class C(object): > ... def func_a(self): > ... print "func_a" > ... def func_b_impl(self): > ... print "func_b" > ... raise Exception > ... def __getattr__(self, name): > ... func = getattr(self, '%s_impl' % name) > ... wrapped_func = self._impl_wrapper(func) > ... setattr(self, name, wrapped_func) > ... return wrapped_func > ... def _impl_wrapper(self, func): > ... def wrapper(*args, **kwargs): > ... try: > ... return func(*args, **kwargs) > ... except: > ... print "entered except" > ... raise > ... return wrapper > ... > py> c = C() > py> c.func_a() > func_a > py> c.func_b() > func_b > entered except > Traceback (most recent call last): > File "", line 1, in ? > File "", line 15, in wrapper > File "", line 6, in func_b_impl > Exception > > The idea here is that __getattr__ is called whenever the class doesn't > have a particular function. The __getattr__ method then tries to find a > corresponding _impl function, wraps it with appropriate try/except code, > and returns the wrapped function. The problem is: >>> c.func_b.__name__ 'wrapper' That messes up SOAPpy's RegisterFunction() method which apparently depends on the __name__ of the function to publish it as an available SOAP function. Any suggestions on how to change the name of c.func_b to 'func_b' instead of 'wrapper'? > HTH, > STeVe Thanks a bunch, -- C From jeremy+complangpython at jeremysanders.net Tue Jun 28 11:40:02 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 28 Jun 2005 16:40:02 +0100 Subject: Dictionary to tuple References: <42c169d0$0$23811$626a14ce@news.free.fr> Message-ID: Erik Max Francis wrote: > But it doesn't return a tuple of them. Which is what the tuple call > there does. Yes, but I think he meant: t = tuple(d.items()) -- Jeremy Sanders http://www.jeremysanders.net/ From tjreedy at udel.edu Wed Jun 1 13:43:42 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 13:43:42 -0400 Subject: NSLU2 and python - a love story ? References: <1117629593.000908.294450@g43g2000cwa.googlegroups.com> Message-ID: "Thomas W" wrote in message news:1117629593.000908.294450 at g43g2000cwa.googlegroups.com... > If you haven't heard about the NSLU2-box yet start with the references > below and then google for it. It's very small, quiet, cheap and runs a > complete linux system, with python available ( and MySQL, PostgreSQL, > Apache etc etc ). It's very cool =) > [1] : http://www.nslu2-linux.org/ > [2] : > http://www.linksys.com/products/product.asp?grid=35&scid=43&prid=640 The Linksys product literature [2] never mentions the word Linux, so I gather a) that it is an add-on and b) that the user group [1] is quite unofficial. For those curious, the price is about $100. The product lit also says 0 about the internal hardware but I found this: http://www.nslu2-linux.org/wiki/Info/CPUOverview. 266 Mhtz, 32 Mb Ram + 8 MB flash, which is pretty minimal these days. So unless one wants it for the designed purpose (or similar), it is not obviously cheap. I am curious what Python application you have in mind. Terry J. Reedy From claird at lairds.us Thu Jun 23 14:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Jun 2005 18:08:02 GMT Subject: Allowing only one instance of a script? References: <11blen3dogr9t96@corp.supernews.com> <11bljln726sohf6@corp.supernews.com> Message-ID: <1v9ro2-on4.ln1@lairds.us> In article <11bljln726sohf6 at corp.supernews.com>, Grant Edwards wrote: . . . >You can also use a network port instead of a file. Binding a >socket to a port is an exclusive and atomic operation. An >advantage to the network port scheme is that the "lock" >automatically goes away if the program dies. A disadvantiage is >that it can't contain information (date/time/PID) like a file >can. . . . While you write elsewhere in this thread, Grant, that pid-in-a-file is the "usual" way, I much prefer this technique of opening a simple TCP/IP server. While I recognize the disadvantage you describe, I choose to regard it as an opportunity--since I have launched the server anyway, I simply have it report to me (that is, any connecting client) all the information I might want want. From harold.fellermann at upf.edu Tue Jun 7 13:52:51 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 7 Jun 2005 19:52:51 +0200 Subject: How do I know when a thread quits? In-Reply-To: References: <42a5adbe.7c818c0e.6475.0cf7@mx.gmail.com> Message-ID: <198daa02eef9a5e8e0a2933687d18c6f@upf.edu> On 07.06.2005, at 16:44, harold fellermann wrote: > import thread > > def parentThread() : > lock = thread.allocate_lock() > child = thread.start_new_thread(childThread,(parent,)) > lock.acquire() > > def childThread(parent) : > parent.lock.acquire() > do_something_with_vars_from(parent) > parent.lock.release() > # don't do anything with parents vars after releasing the lock > > > I did not test it, but I cannot see any reason why this should fail. > >> After the childThread executes parent.lock.release() execution may be >> taken away from it and given to the parent thread(note that the child >> thread hasn't quit yet). The parent thread which is waiting on the >> lock gets released and quits. Now the "still running" child thread >> tries to exit and based on my assumption attempts to call some cleanup >> func in some module which has been GC'ed due to the exit of the parent >> thread. This leads to an exception being thrown. >> Referencing the module locally on the child thread does not seem like an >> elegant solution besides I don't know which modules are involved in >> cleaning I wander how much an issue this fear really is. To my understanding, this situation can only happen, when the child thread accessess a module that was imported locally within the parent thread. Does anyone with a better understanding of the internals of the interpreter know whether such a thing can occur? If so, in what circumstances? - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr From paulm at barley.vel.net Thu Jun 30 17:54:55 2005 From: paulm at barley.vel.net (paulm) Date: Thu, 30 Jun 2005 16:54:55 -0500 Subject: Newbie backreference question References: <42C463F4.2040005@syscononline.com> Message-ID: Larry Bates wrote: > a='test string' > print a.split()[:-1] > > I'm assuming that you want the last space separated word? > > Larry Bates > > > paulm wrote: >> Hi, >> In perl I can do something like: >> >> $a = 'test string'; >> $a =~ /test (\w+)/; >> $b = $1; >> print $b . "\n"; >> >> and my output would be "string". >> >> How might this snippet be written in python? >> >> Thanks to all... No, sorry - my bad. I am looking to assign the backreference to another variable so it can be treated seperately. So perhaps: $a = 'test string two'; $a =~ /test \w{2}([\W\w]+)/; $b = $1; print $b . "\n"; producing "ring two". I have read the docs and faqs but remain too dense to comprehend. Thanks again... From peter at engcorp.com Thu Jun 23 23:02:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Jun 2005 23:02:11 -0400 Subject: os.system(cmd) isn't working In-Reply-To: References: <3hv2j3Fit96kU1@individual.net> Message-ID: Terry Hancock wrote: > On Thursday 23 June 2005 01:19 am, Paul Watson wrote: > >>"Gregory Pi?ero" wrote in message >>news:mailman.787.1119499378.10512.python-list at python.org... >>os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' >>"www.blendedtechnologies.com"') >> > You don't have any spaces between the command and the argument, I spent a while trying to prove that to myself as well, but eventually I concluded that the fact that the ' and the " after the plus sign are on separate lines must mean that there was whitespace between them, or the line break would have occurred before the ' ... but it did seem like a good theory while it lasted. ;-) -Peter From igorcarron at gmail.com Sun Jun 5 10:11:30 2005 From: igorcarron at gmail.com (igorcarron at gmail.com) Date: 5 Jun 2005 07:11:30 -0700 Subject: Grand Challenge Pegasus Team: Programming Pegasus Bridge 1 ? In-Reply-To: References: <1117915995.759559.240730@g47g2000cwa.googlegroups.com> Message-ID: <1117980690.297105.276840@z14g2000cwz.googlegroups.com> Thank you Alex for your feedback. What I am really proposing is for others to test their software on our vehicle for the very reason that there are a lot of unknowns that I cannot believe can directly modeled into an ODE type of engine (as you call it.) Several reasons for this: - one piece of data is the images taken from the vehicle, since we do not use ranging system like lidar, data fusion using imagery and IMU data is at the center of devising a good algorithm for an autonomous vehicle. Unless one were to create a world with different illumination, shadowing (something that would be quite an undertaking on its own), it would not be a perfect fit to try out a new algorithm. Another data stream is sound as recorded in the vehicle, I am not sure on how to generate this type of information. - an ODE engine would mean that the dynamics of the vehicle and the terrain would be known in advance. This is rarely the case. - Our software is being tested on that vehicle already and the vehicle is ready, it would cost us less to try it out on the vehicle directly. Thanks for the pointer on PyODE. Igor. From dalke at dalkescientific.com Tue Jun 14 04:56:46 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 14 Jun 2005 08:56:46 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <3r4sa1dqi3qbdfqpepcg0p0imnbhg65c8b@4ax.com> Message-ID: Andreas Kostyrka wrote: > On Tue, Jun 14, 2005 at 12:02:29AM +0000, Andrea Griffini wrote: >> Caching is indeed very important, and sometimes the difference >> is huge. ... > Easy Question: > You've got 2 programs that are running in parallel. > Without basic knowledge about caches, the naive answer would be that > the programs will probably run double time. The reality is different. Okay, I admit I'm making a comment almost solely to have Andrea, Andreas and Andrew in the same thread. I've seen superlinear and sublinear performance for this. Superlinear when the problem fits into 2x cache size but not 1x cache size and is nicely decomposable, and sublinear when the data doesn't have good processor affinity. Do I get an A for Andre.*? :) Andrew dalke at dalkescientific.com From michele.simionato at gmail.com Sun Jun 19 12:05:46 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 19 Jun 2005 09:05:46 -0700 Subject: Why is there no instancemethod builtin? In-Reply-To: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> References: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> Message-ID: <1119197146.922190.38000@g44g2000cwa.googlegroups.com> In this case I have used hasattr(obj, "__iter__") instead of isinstance(obj, list) (strings are iterable but do not have __iter__ method). I think hasattr is much better since it works for tuples and custom iterables too. Michele Simionato From dimitri.pater at gmail.com Thu Jun 23 19:13:29 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Fri, 24 Jun 2005 01:13:29 +0200 Subject: string capitalize sentence In-Reply-To: <17083.16558.675538.436340@montanaro.dyndns.org> References: <17083.16558.675538.436340@montanaro.dyndns.org> Message-ID: thanks, a lot it works! still learning something every day... Dimitri On 6/24/05, Skip Montanaro wrote: > > > dimitri> I came up with the following solution: > > dimitri> a = 'harry is a strange guy. so is his sister, but at least she > is not a > dimitri> guy. i am.' > dimitri> b = a.replace('. ', '.') > dimitri> splitlist = b.split('.') > dimitri> newlist = [] > dimitri> for i in range(len(splitlist)): > dimitri> i = ''.join(splitlist[i].capitalize() + '.' > dimitri> newlist.append(i) > dimitri> cap = ' '.join(newlist).replace(' .', '') > dimitri> print cap > > No need for the replace(). Just split on ". ". No need for a for loop > either, or the temp variable cap. Use a list comprehension. The result is: > > print ". ".join([s.capitalize() for s in a.split(". ")]) > > Skip > -- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjuranic at gmail.com Thu Jun 23 16:12:12 2005 From: sjuranic at gmail.com (Steve Juranich) Date: Thu, 23 Jun 2005 13:12:12 -0700 Subject: Hardening enviroment by overloading __import__? Message-ID: <56190b6c05062313125aef8332@mail.gmail.com> If this is a FAQ, please let me know where the answer is. I have in some code an 'eval', which I hate, but it's the shortest path to where I need to get at this point. I thought that one way I could harden the enviroment against malicious code would be to temporarily disable the import statement by overloading __import__, but I tried what seemed obvious to me, and it didn't work. What I want do do is something like this: def __import__(*args, **kwargs): raise ImportError, 'Not so fast, bucko!' eval(potentially_dangerous_string) del __import__ # To get the builtin behavior back. Am I barking up the wrong tree with __import__?? Where should I look for this answer? Thanks. -- Steve Juranich Tucson, AZ USA From evenprimes at gmail.com Wed Jun 29 08:33:22 2005 From: evenprimes at gmail.com (Chris Cioffi) Date: Wed, 29 Jun 2005 08:33:22 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: One of my votes would be for something like: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303481 or http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303770. We use something like these in the stdlib already (time_struct), but don't supply a ready solution for people to implement their own. FWIW, I'm writing all my new DB code to return tuples with named elements just to improve the readability of my programs. Anyplace where a normal positional tuple is returned could be improved with named attribute access and this wouldn't break existing code like switching to a return object would. On 27/06/05, Reinhold Birkenfeld wrote: > > Hello, > > at the moment python-dev is discussing including Jason Orendorff's path > module > into the standard library. > > Do you have any other good and valued Python modules that you would think > are > bug-free, mature (that includes a long release distance) and useful enough > to > be granted a place in the stdlib? > > For my part, ctypes seems like a suggestion to start with. > > Reinhold > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Obviously crime pays, or there'd be no crime." -- G. Gorden Liddy -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.renan at gmail.com Thu Jun 30 05:09:53 2005 From: c.renan at gmail.com (Statesman) Date: 30 Jun 2005 02:09:53 -0700 Subject: =?iso-8859-1?q?script_fichiers_binaires_lecture_=E9criture?= Message-ID: <1120122593.162554.71410@g14g2000cwa.googlegroups.com> Je connais mal python et n'est pas trop le temps de m'y plonger bien que cela semble ?tre assez puissant... import sys import ixio import os M = ixio.getMAC("eth0") S = "%08X %08X" % (M[0] | M[1]<<8 | M[2]<<16 | M[3]<<24, M[4] | M[5]<<8) K = "Errorin:" if len(sys.argv) <> 3: print "Usage %s " % sys.argv[0] else: I = open(sys.argv[1],"rb")#ouverture de tpsd.pre avec le flag rb pour read in binary mode O = open(sys.argv[2],"wb") while 1: blk = I.read(1<<13) try: i = blk.index(K) blk = "%sErrorin:%s%s" \ % (blk[:i],S,blk[i+len(K)+len(S):]) O.write(blk) except ValueError: O.write(blk) if len(blk)<1<<13: break O.close() I.close() Voici l'erreur que j'obtiens en essayant d'ex?cuter ce script: AttributeError: 'string' object has no attribute 'index' D'apr?s moi, index est une m?thode de la classe string et non un attribut...Je ne comprend donc pas... Enfin, je pr?cise que je suis malheureusement en version 1.5 de python... :( Autre question: 1<<13 est cens? ?tre une taille en octet: comment cela se lit-t-il? Merci d'avance de m'aclairer sur cette erreur et cette question. From newsgroups at jhrothjr.com Sun Jun 19 15:34:13 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 19 Jun 2005 13:34:13 -0600 Subject: Why is there no instancemethod builtin? References: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> <1119197146.922190.38000@g44g2000cwa.googlegroups.com> <1119201221.143713.8890@z14g2000cwz.googlegroups.com> <1119202546.388847.114650@g14g2000cwa.googlegroups.com> <1119203542.789312.5620@g44g2000cwa.googlegroups.com> Message-ID: <11bbi5o11pjcj1f@news.supernews.com> "George Sakkis" wrote in message news:1119203542.789312.5620 at g44g2000cwa.googlegroups.com... > Michele Simionato wrote: >> I think strings do not have __iter__ on purpose, exactly to distinguish >> them from other iterables, since sometimes it is nice to consider them >> atomic, but I am not sure of this. You should ask the developers. Anyway, >> the >> right definition of iterable is (as I was told) "an object X such that >> iter(X) does not throw an exception". > > Hmm.. not a very insightful definition unless someone knows the > implementation of iter(). > >> Objects following the __getitem__ protocol - such as strings - are >> iterables >> even if they do not have an __iter__ method. > > It would be more uniform if the default 'type' metaclass added an > __iter__ method to classes that define __getitem__ but not __iter__ > with something like: > > from itertools import count > > def __iter__(self): > for i in count(): > try: yield self[i] > except IndexError: raise StopIteration Unfortunately it doesn't work: getitem can be defined for a class that acts like a dictionary: that is, the items are not integers, let alone integers that extend in a strict sequence from 0. John Roth > > George > From falcon3166 at hotmail.com Tue Jun 28 14:42:17 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 28 Jun 2005 12:42:17 -0600 Subject: Python/IDLE - text in different colours References: Message-ID: <42c19a13$0$7025$b9fe7a78@news.usenetrevolution.com> Bill. The way is the click on view, then click script checker, or something like that. It will color code the text for you. Nathan "Bill Davy" wrote in message news:d9rfb9$ob7$1 at nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com... > To make life easier for my users, I'd like to colour my prompt string (as > handed to raw_input()) a different colour to that produced by print. I'm > using Python 2.4.1 and IDLE 1.1.1 on Windows XP. Is it possible, and if so, > how? > tia, > Bill > > -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From adam1800uk at yahoo.co.uk Mon Jun 6 12:06:53 2005 From: adam1800uk at yahoo.co.uk (Adam Munoz Lopez) Date: Mon, 6 Jun 2005 17:06:53 +0100 (BST) Subject: Lost in the inheritance tree... THANKS! In-Reply-To: <1118073214.264097.85130@g49g2000cwa.googlegroups.com> Message-ID: <20050606160653.81254.qmail@web25010.mail.ukl.yahoo.com> Thanks a lot for your quick response. I actually just found the answer by myself before reading your reply. Just printed out the code and read it. The mistake was pretty obvious then. Yes, Ill try your suggestion. I was just trying to experiment a bit with inheritance to understand how it works better. Once again thanx a lot. Its the first time I post and Im pretty impressed by the speed with which you guys replied. Adam. --- Jordan Rastrick wrote: > Although you get infinite recursion with this code, > you still get > enough information on the error from the interpreter > to help you debug. > > Running IDLE, I get a traceback of: > > File "C:/Documents and > Settings/Jordan/Desktop/more_blah.py", line 11, > in __init__ > self.createFrames() > File "C:/Documents and > Settings/Jordan/Desktop/more_blah.py", line > 19, in createFrames > textFrame=TextFrame(self,300,600) > File "C:/Documents and > Settings/Jordan/Desktop/more_blah.py", line > 31, in __init__ > RootFrame.__init__(self,parent,myHeight,myWidth) > > repeated indefinitely. At a glance, this tells you: > > * That __init__ (of the RootFrame method) calls > self.createFrames() > * createFrames(), in turn, calls > TextFrame(self,300,600) > * This leads to RootFrame.__init__ being called once > more > > So theres youre infinite recursion. RootFrame's > __init__ calls > createFrames which creates a new TextFrame - meaning > TextFrame.__init__ > gets called, and this calls its parent's __init__ > method, and so on ad > infinitum. > > This is a pretty good demonstration of the prinicple > that you should do > as little as is nessecary to create an object - if > possible, try to > calling other methods on an object in its __init__ > method. > > Without knowing more about youre program, and with > only limited GUI > building experience (and none in Python), I'd guess > the most likely > solution is for TextFrame to inherit from > Tkinter.Frame directly - > having it inheret from RootFrame doesn't really make > much sense as far > as I can see. TextFrame is, I would guess, intended > as a component of > RootFrame, not a subclass. Thats another important > OO prinicple - don't > overuse inheritance, often simple composition (one > object having > another as an attribute) is the right solution. > > If TextFrame really is supposed to inherit from > RootFrame, try to > explain why. > > -- > http://mail.python.org/mailman/listinfo/python-list > ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From applegrew at gmail.com Thu Jun 23 15:58:38 2005 From: applegrew at gmail.com (Apple Grew) Date: Fri, 24 Jun 2005 01:28:38 +0530 Subject: Help wanted in piping in Windows Message-ID: <42BB146E.4060800@gmail.com> I want to develope a Winboard like application which will support Winboard protocol. For that I require to know how to handle piping in Python. I seperated out module popen2, but when I use fileObject.readline() then it halts the program if the sub-process is waiting for user input; will executing the readline() part in a seperate thread be helpful? My target platform is Windows. Links to helpful web resources and sample Python codes will be highly appreciated. Regards, Apple From ggg at zzz.it Wed Jun 8 12:31:08 2005 From: ggg at zzz.it (deelan) Date: Wed, 08 Jun 2005 18:31:08 +0200 Subject: MoinMoin WikiName and python regexes In-Reply-To: References: Message-ID: Ara.T.Howard wrote: (...) > and i'm not that familiar with python syntax. to me this looks like a map > used to bind variables into the regex - or is it binding into a string then > compiling that string into a regex - regexs don't seem to be literal > objects > in pythong AFAIK... i'm thinking i need something like > > word_rule = > ur'(?:(? % { > ^ > ^ > ^ > 'u': config.chars_upper, > 'l': config.chars_lower, > 'subpages': config.allow_subpages and (wikiutil.CHILD_PREFIX + > '?') or '', > 'parent': config.allow_subpages and (ur'(?:%s)?' % > re.escape(PARENT_PREFIX)) or '', > } > > and this seems to work - but i'm wondering what the 's' in '%(u)s' implies? > obviously the u is the char range (unicode?)... but what's the 's'? an example may help here: >>> a = 123 >>> '%04d' % a '0123' >>> '%f' % a '123.000000' >>> '%s' % a '123' that "s" tells python to convert the number as string. the form %(key)s tells python to lookup a dictionary "key" and format the found value into a string: >>> d = {'key': 123} >>> '%(key)s' % d '123' so in your code there's some keys named 'u', 'l', 'subpages', etc. and their values are substitued into that big RE, replacing the corresponding key names. HTH. -- deelan From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Tue Jun 21 00:25:27 2005 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Tue, 21 Jun 2005 04:25:27 -0000 Subject: references/addrresses in imperative languages References: <1119323217.670985.68250@o13g2000cwo.googlegroups.com> Message-ID: <11bf5ln27f0qf6f@corp.supernews.com> "Kaz Kylheku" wrote: # SM Ryan wrote: # > # easy way to see this, is to ask yourself: how come in mathematics # > # there's no such thing as "addresses/pointers/references". # > # > The whole point of Goedelisation was to add to name/value references into # > number theory. # # Is that so? That implies that there is some table where you can # associate names (or whatever type of locators: call them pointers, # whatever) with arbitrary values. But in fact that's not the case. Do you really believe the Goedel number of a statement is the statement itself? Is everything named Kaz the same as you? -- SM Ryan http://www.rawbw.com/~wyrmwif/ So....that would make Bethany part black? From l.serwatka at gazeta-dot-pl.no-spam.invalid Tue Jun 7 10:48:34 2005 From: l.serwatka at gazeta-dot-pl.no-spam.invalid (ls) Date: Tue, 7 Jun 2005 14:48:34 +0000 (UTC) Subject: how to export data from ZODB to text files References: Message-ID: Hi Peter, Thank you for your reply. I already can access file using code >>> from ZODB import FileStorage, DB >>> storage = FileStorage.FileStorage('mydatabase.fs') >>> db = DB(storage) >>> connection = db.open() >>> root = connection.root() But this is the point where my konwledge ends since I`m not a Python programmer. I don`t know what is the structure of ZODB, I`m just looking for code, or some tool, which I can use to export data from Data.ts file to plain text file. I`m looking for easiest way to export data from ZODB and put it to MySQL later. Do you know what way I should choose? I have to know Python language to finish this task? -- Lukasz From tdelaney at avaya.com Sun Jun 5 20:30:31 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 6 Jun 2005 10:30:31 +1000 Subject: For review: PEP 343: Anonymous Block Redux and GeneratorEnhancements Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE72128D@au3010avexu1.global.avaya.com> Nicolas Fleury wrote: > def getFirstLine(filename): > with opening(filename) as file > return file.readline() Your tastes definitely disagree with the majority of Python programmers then, including Guido. Scoping is defined in Python by indentation. If you want the above sort of thing, you're going to have to write a new PEP, and I'd be very surprised to see it accepted. But there's nothing stopping you from doing so. > def getFirstLine(filename): > with opening(filename) as file: > return file.readline() This is beautiful and explicit. What else could you want? The syntax: with EXPR1 as VAR1, EXPR2 as VAR2: ... was discussed on python-dev. It wasn't explicitly rejected, but the feeling seemed to be that it was an unnecessary complication as far as PEP 343 is concerned. There's nothing stopping another PEP proposing this as an extension to PEP 343, and there's nothing stopping that being in Python 2.5 if it's accepted. PEP 343 was originally PEP 340 (and several other things) and was quite complicated at one point (it originally contained PEP 342 as well). The PEP in its current state represents 2 months of discussion, complication and (finally) simplification. Its semantics are clear and unambiguous. And (as Guido states) it will obsolete 4(?) other PEPs. Be sure to read the referenced PEPs (and the ones referenced from them) - they contain a lot of history. Also read PEP 346 for a competing PEP to PEPs 340 and 343 that gradually converged to PEP 343 - most importantly, it contains the rejected options (that seem to have been lost from PEPs 340 and 343). Tim Delaney From mwm at mired.org Tue Jun 28 20:08:47 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 28 Jun 2005 20:08:47 -0400 Subject: Excellent Site for Developers References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> <3Xive.2320$W74.614@newssvr30.news.prodigy.com> Message-ID: <86u0jim3cg.fsf@bhuda.mired.org> "Philippe C. Martin" writes: > Woof! > > And I thought my english was improving ! > > I'm laughing very hard right now, thanks ! > > Philippe You might note that a fisherman who is trolling is *not* called a troll. In that context, the "troll" is the lure/line that is being used to troll. And to think people wanted to *program* in this language! Skip Montanaro wrote: > >> >> Philippe> Not being from anglo-saxon heritage, I keep wondering why >> Philippe> spammers always (or very often) get called 'trolls' ? >> >> Fishing from a boat that is moving slowly is called "trolling". You're >> slowly dragging bait or a lure through the water to entice a fish to bite >> your hook. Similarly, when someone posts a provocative message to a >> mailing list or Usenet newsgroup (or other discussion forum, I suppose) >> they are often trying to get someone else to "take their bait". >> >> See also: http://www.answers.com/troll >> >> Skip > -- Mike Meyer http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rkern at ucsd.edu Thu Jun 30 22:57:02 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 19:57:02 -0700 Subject: shelve in a ZipFile? In-Reply-To: <200506302110.45978.hancock@anansispaceworks.com> References: <200506302110.45978.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > I only just recently had a look at the shelve module, and it > looks pretty handy, my only question being, what if I really > want two shelves? Must I use two files? > > Also, it seems strange that shelve only works with > filenames. I would've expected there to at least be > a variant that would put a shelve database on a file > that is opened for read/write (that is a file object). shelve uses one of the available dbm modules which are usually coded in C and use external libraries. You might subclass Shelf to use a dumbdbm (which is in Python) modified to use arbitrary file-like storage. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From qwweeeit at yahoo.it Tue Jun 21 07:01:04 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 21 Jun 2005 04:01:04 -0700 Subject: Create our own python source repository References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> <1118156654.634103.186390@o13g2000cwo.googlegroups.com> <1118170303.568984.242610@z14g2000cwz.googlegroups.com> <1118231393.450388.14570@o13g2000cwo.googlegroups.com> Message-ID: <1119351664.421593.40280@g47g2000cwa.googlegroups.com> Hi datacide, before, the good part...: thank you for your replay. Your suggestion has opened me a new worldl: an alternative method to get web resources. Now the bad part: your is an example of "guru's suggestion", that is a few words from which the poor newbye can't exctract much. It is much more useful is you give also some web directions to get the tool and install it (if it is not straightforwad...). Of course the top would be to give a short example of what you mean by "collect and sort code snippets and classes). My method is much ruder: to merge the various htmls and get rid of the spurious parts... (I am making the same mistake, that is ...few words, but I'm not a guru!). Bye. From rune.hansen at mac.com Thu Jun 16 02:55:28 2005 From: rune.hansen at mac.com (Rune Hansen) Date: Thu, 16 Jun 2005 08:55:28 +0200 Subject: Read System.out.println From Java Using popen ? In-Reply-To: <1118864756.680646.234400@f14g2000cwb.googlegroups.com> References: <1118864756.680646.234400@f14g2000cwb.googlegroups.com> Message-ID: Your Friend wrote: > result = os.popen( "%s/bin/java com.foo.service.JavaService %s" % ( > JAVA_HOME, FILE_TO_CREATE ) ) > > print > result.readlines() > I find that subprocess.Popen works _better_ for this kind of thing. import os from subprocess import Popen outfile = open("out.txt","w") errfile = open("err.txt","w") pid = Popen([os.environ["JAVA_HOME"]+/bin/java, "-classpath", ".", "MyJavaExecutable"], stdout=outfile, stderr=errfile) . . /rune From steve at REMOVETHIScyber.com.au Fri Jun 24 08:58:56 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 24 Jun 2005 22:58:56 +1000 Subject: Favorite non-python language trick? References: Message-ID: On Fri, 24 Jun 2005 00:55:38 -0600, Joseph Garvin wrote: > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? Long ago, I used to dabble in Forth. You could say, the entire Forth language was a trick :-) It was interesting to be able to define your own compiler commands, loop constructs and so forth. One of the things I liked in Pascal was the "with" keyword. You could write something like this: with colour do begin red := 0; blue := 255; green := 0; end; instead of: colour.red := 0; colour.blue := 255; colour.green := 0; Okay, so maybe it is more of a feature than a trick, but I miss it and it would be nice to have in Python. -- Steven From n.20.e5ke at spamgourmet.com Fri Jun 3 14:30:57 2005 From: n.20.e5ke at spamgourmet.com (Esben Pedersen) Date: Fri, 03 Jun 2005 20:30:57 +0200 Subject: Pressing A Webpage Button In-Reply-To: <6onne.27139$9A2.4091@edtnps89> References: <6onne.27139$9A2.4091@edtnps89> Message-ID: <42a0a23b$0$18648$14726298@news.sunsite.dk> J Correia wrote: > "Elliot Temple" wrote in message > news:mailman.335.1117645705.18027.python-list at python.org... > >>How do I make Python press a button on a webpage? I looked at >>urllib, but I only see how to open a URL with that. I searched >>google but no luck. >> >>For example, google has a button how would i make a script to press that button? >> >>Just for fun, is there any way to do the equivalent of typing into a >>text field like the google search field before hitting the button? >>(I don't actually need to do this.) > > > You don't say which OS... if you're running IE on Windows you > can use COM as follows... > > from win32com.client import Dispatch > from time import sleep > > ie = Dispatch("InternetExplorer.Application") > ie.Visible = 1 > ie.Navigate("http://www.google.com") > while ie.ReadyState != 4: # Wait for browser to finish loading. > sleep(1) > doc = ie.Document > doc.f.q.value = "qwerty" # form name is 'f'; search field name is 'q' > doc.f.btnG.click() # click on button 'btnG' How do i know which methods the ie object has? dir(ie) doesn't show Navigate. /Esben From kent37 at tds.net Wed Jun 8 14:26:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Jun 2005 14:26:23 -0400 Subject: optparse.py: FutureWarning error In-Reply-To: <42a10066$1_1@newspeer2.tds.net> References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> <42a02aba$1_3@newspeer2.tds.net> <42a10066$1_1@newspeer2.tds.net> Message-ID: <42a737fc$1_2@newspeer2.tds.net> Kent Johnson wrote: > Terry Reedy wrote: > >> "Kent Johnson" wrote in message >> news:42a02aba$1_3 at newspeer2.tds.net... >> >>> Terry Reedy wrote: >>> >>>> "kosuke" wrote in message >>>> news:1117765604.103092.154190 at g47g2000cwa.googlegroups.com... >>>> >>>> >>>>> man python --- >>>>> >>>>> COMMAND LINE OPTIONS >>>> >>>> >>>> >>>> This should REALLY be on the doc page of the Python site. >>> >>> >>> Hear, hear! I never even knew this existed! >>> >>> Where should it go in the docs? In the Language Reference or the >>> Tutorial or...? >> >> >> >> Since the Tutorial already has section 2. Using the Python Interpreter >> that discusses a few of the switches, I would add it as an appendix >> with a reference to the appendix at the end of the appropriate >> subsection. Perhaps I will submit a tracker item. > > > Sounds good to me. > > Kent I have submitted this as http://sourceforge.net/tracker/index.php?func=detail&aid=1217152&group_id=5470&atid=105470 Kent From kent37 at tds.net Tue Jun 14 10:53:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jun 2005 10:53:20 -0400 Subject: collect data using threads In-Reply-To: References: Message-ID: <42aeeef3$1_1@newspeer2.tds.net> Peter Hansen wrote: > Qiangning Hong wrote: > >> A class Collector, it spawns several threads to read from serial port. >> Collector.get_data() will get all the data they have read since last >> call. Who can tell me whether my implementation correct? > > [snip sample with a list] > >> I am not very sure about the get_data() method. Will it cause data lose >> if there is a thread is appending data to self.data at the same time? > > > That will not work, and you will get data loss, as Jeremy points out. > > Normally Python lists are safe, but your key problem (in this code) is > that you are rebinding self.data to a new list! If another thread calls > on_received() just after the line "x = self.data" executes, then the new > data will never be seen. Can you explain why not? self.data is still bound to the same list as x. At least if the execution sequence is x = self.data self.data.append(a_piece_of_data) self.data = [] ISTM it should work. I'm not arguing in favor of the original code, I'm just trying to understand your specific failure mode. Thanks, Kent From mblume at socha.net Sun Jun 19 07:36:17 2005 From: mblume at socha.net (Martin Blume) Date: Sun, 19 Jun 2005 13:36:17 +0200 Subject: oddness in super() References: <42B4B22F.1090204@lexicon.net> Message-ID: <42b558b1$0$1153$5402220f@news.sunrise.ch> "John Machin" schrieb > > [analysis of super() "oddness"] > A great analysis, but what's a "pogo stick" and where can I get one? Thanks Martin From bogus@does.not.exist.com Fri Jun 10 09:35:02 2005 From: bogus@does.not.exist.com () Date: Fri, 10 Jun 2005 13:35:02 -0000 Subject: No subject Message-ID: #! rnews 2612 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Generating HTML from python X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 70 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <67Xpe.2446$%j7.824 at newssvr11.news.prodigy.com> Mime-Version: 1.0 Date: Fri, 10 Jun 2005 13:16:36 GMT Xref: news.xs4all.nl comp.lang.python:381106 "Philippe C. Martin" writes: > PS: I am looking at the formatter module which seems to be related to HTML > somehow, but without any code sample I'm a bit lost As others have noted, if you need any computation at all, it is easier to write directly in python. I came to python from perl, where I used CGI.pm. To get that effect, I wrote my own CGIpm.py and used it for a while. http://www.seanet.com/~hgg9140/comp/index.html But (at the suggestion of others in this newsgroup), I then tried writing directly. The net effect is trivial html generation, with all the power of python at your fingertips. Note: To save even more time, I made a CGI template that includes this main: #============================ if __name__=="__main__": mystart() #cgi.print_environ_usage() #cgi.print_environ() form = cgi.FieldStorage() try: if len(form)==0: send_form1() else: form_name=form['form_name'].value if form_name=='form1': recv_form1() except StandardError, e: print "\n
ERROR: %s\n" % e myend() To support a stateless world: 1. Each form has a send_xyz and recv_xyz function. The end of each recv_xyz decides what send_xyz to do next. 2. mystart and myend handle opening and closing the http and html. They also handle state save/restore as needed (pickle or database). > > > Philippe C. Martin wrote: > > > Hi, > > > > I wish to use an easy way to generate reports from wxPython and feel > > wxHtmlEasyPrinting could be a good solution. > > > > I now need to generate the HTML wxHtmlEasyPrinting can print: I need to > > have a title followed by lines of text that do not look too ugly. If > > possible I would like to use an existing module. > > > > Q1) Is there such a module ? > > Q2) Is my approach fairly good ? > > > > Regards, > > > > Philippe > -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From gsakkis at rutgers.edu Fri Jun 24 19:43:53 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 24 Jun 2005 16:43:53 -0700 Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> Message-ID: <1119656633.459985.32280@z14g2000cwz.googlegroups.com> "Rocco Moretti" wrote: > Are you sure you need a dictionary? You may want to look at the Set > module instead, if the values aren't important. Set is the name of the type in the module sets, introduced in 2.3. Since 2.4 you can use the builtin set type. Here's the import snippet that works for 2.3 or later: try: set except NameError: from sets import Set as set George From jjl at pobox.com Fri Jun 3 14:50:06 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jun 2005 18:50:06 +0000 Subject: scripting browsers from Python References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> Message-ID: <87vf4v2s2p.fsf@pobox.com> [Michele Simionato] > > I would like to know what is available for scripting browsers from > > Python. [...] > > to do POST requests too. I don't want to use urllib to emulate a > > browser, I am > > interested in checking that browser X really works as intended with my > > application. Any suggestion? [...] [Stephen Thorne] > I use pbp, http://pbp.berlios.de/ [...] Again, that doesn't do what Michele wants. John From duncan.booth at invalid.invalid Tue Jun 7 09:09:16 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jun 2005 13:09:16 GMT Subject: file permissions on windows XP (home) References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> Message-ID: Peter Hansen wrote: >> >> Why is python returing True from os.access? >> Why isn't chmod doing anything? > > Check your results using os.stat() after doing that, perhaps? If it > shows the right values for the permissions, then clearly the problem has > nothing to do with Python per se, or your own code. > And also remember that in windows the mode in os.chmod and os.stat is only loosely related to the actual permissions on the file. In particular there is a 'readonly' flag which is separate from whether any particular user or group has write access. The only way to tell whether you have access to a file in windows really is to try to open it and handle the exception. Try using the properties panel, or the windows CACLS to display the security permissions on the file. If you start with a plain file, then you and administrators probably have full access (CACLS will display 'your username:F'). If you use Python to set an access mode, it simply tries to toggle the attributes on the file itself. If you use Cygwin's chmod it will mess about with the security permissions in an attempt to get as close to the Unix file mode as it can, so your nice simple 'F' mode might become something truly horrendous: Before: C:\temp>cacls testfile.txt C:\temp\testfile.txt BUILTIN\Administrators:F NT AUTHORITY\SYSTEM:F DELL5150\Duncan:F BUILTIN\Users:R C:\temp>\cygwin\bin\chmod 744 testfile.txt C:\temp>cacls testfile.txt C:\temp\testfile.txt DELL5150\Duncan:(special access:) STANDARD_RIGHTS_ALL DELETE READ_CONTROL WRITE_DAC WRITE_OWNER SYNCHRONIZE STANDARD_RIGHTS_REQUIRED FILE_GENERIC_READ FILE_GENERIC_WRITE FILE_GENERIC_EXECUTE FILE_READ_DATA FILE_WRITE_DATA FILE_APPEND_DATA FILE_READ_EA FILE_WRITE_EA FILE_EXECUTE FILE_READ_ATTRIBUTES FILE_WRITE_ATTRIBUTES DELL5150\None:(special access:) READ_CONTROL SYNCHRONIZE FILE_GENERIC_READ FILE_READ_DATA FILE_READ_EA FILE_READ_ATTRIBUTES Everyone:(special access:) READ_CONTROL SYNCHRONIZE FILE_GENERIC_READ FILE_READ_DATA FILE_READ_EA FILE_READ_ATTRIBUTES BUILTIN\Administrators:F NT AUTHORITY\SYSTEM:F BUILTIN\Users:R From abrown at CSREES.USDA.GOV Tue Jun 21 13:23:39 2005 From: abrown at CSREES.USDA.GOV (Brown, Alysia) Date: Tue, 21 Jun 2005 13:23:39 -0400 Subject: looking for beginner projects to help out with Message-ID: I'm new to the list. I work for a US Gov't agency & have been learning Python. I've been doing web development work for some years now & got involved with Python/Zope/Plone last fall. I've had formal Zope/Plone training. I've also been working my way through Deitel's "Python How to Program" book. I learned Java a couple of years ago so Python hasn't been too hard for me to learn. I am looking for some volunteer projects to work on for someone with beginner level skills in order to sharpen my Python programming skills. If anyone has any projects I could help out with, please let me know. Thanks! Alysia -------------- next part -------------- An HTML attachment was scrubbed... URL: From onurb at xiludom.gro Thu Jun 30 06:26:02 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 30 Jun 2005 12:26:02 +0200 Subject: script fichiers binaires lecture =?ISO-8859-1?Q?=E9criture?= In-Reply-To: <1120123333.646354.125080@z14g2000cwz.googlegroups.com> References: <1120122593.162554.71410@g14g2000cwa.googlegroups.com> <1120123333.646354.125080@z14g2000cwz.googlegroups.com> Message-ID: <42c3c8ba$0$23824$626a14ce@news.free.fr> Statesman wrote: > In English: > > I don't know much about python and I won't have much time to learn much > about it even if it seems powerful... > (snip code) > Here is an error I get trying to run this script: > > AttributeError: 'string' object has no attribute 'index' > > According to me, index() is a method of the string class but not an > attribute. So I don't understand the error message. In Python, functions are first class citizens (a function is an object you can bind to a variable, pass as an argument, return from another function etc...), so methods *are* actually attributes... > Be aware that I'm > using pyhton 1.5, Err... latest is 2.4.1, and the language has really, really changed. You should consider upgrading... > unfortunately... BTW, in 1.5.x, you can use the String module instead of string class methods: import String s = "allo" String.index(s, "a") but really, consider upgrading to a newer version... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hancock at anansispaceworks.com Mon Jun 13 12:50:37 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 11:50:37 -0500 Subject: What is different with Python ? In-Reply-To: <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> References: <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: <200506131150.38434.hancock@anansispaceworks.com> On Monday 13 June 2005 12:55 am, Andrea Griffini wrote: > On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: > > >How far down do you have to go? What makes bytes of memory, data busses, > >and CPUs the right level of abstraction? > > They're things that can be IMO genuinely accept > as "obvious". Hah! Try explaining them to my non-programmer mother or my 9-year-old son. On the other hand, telling them that Python attaches a label (or name) to an object (which can be "anything") was a cinch. Both want to program, but are currently still struggling with basic concepts. Interestingly, my son had no problem at all with the "name" versus "variable" distinction -- that seems to be a case where my C experience caused me problems, but it's a non-issue coming from a tabula rasa perspective. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From lkirsh at cs.ubc.ca Fri Jun 24 06:40:05 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Fri, 24 Jun 2005 03:40:05 -0700 Subject: printing indented html code In-Reply-To: References: Message-ID: Thanks. At a glance, that looks like it's what I'm looking for. Lowell TechBookReport wrote: > Lowell Kirsh wrote: > >> Is there a module or library anyone knows of that will print html code >> indented? What I'd like would be for a function or class which works >> like this: >> >> htmlIndent(sys.stdout, 'foobar...') >> >> and will print somethinkg like this to stdout: >> >> >> >> foobar >> >> ... >> >> My current way of doing this kind of stuff is less than ideal and will >> write such a function if it doesn't exist. >> >> Thanks, >> Lowell > > > There are lots of HTML pretty printers around, but for starters take a > look at this: http://www.oreilly.com/catalog/pythonsl/chapter/ch05.html > > HTH > ========================================================================== > TechBookReport - http://www.techbookreport.com From steve at holdenweb.com Mon Jun 13 21:45:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Jun 2005 21:45:40 -0400 Subject: searching for IDE In-Reply-To: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: alexrait1 wrote: > I need an IDE for python that has the ability to show the filds of a > class when I write "." > Just the way it works in eclipse/JBuilder with java or visual studio > with c++ > For now I treid eric3 and IDLE they don't do this... > Wing IDE gives you a completion drop-down whenever it can. You can try the tool out with a free download from www.wingware.com if you want, and both personal and full licenses are available. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From could.net at gmail.com Tue Jun 28 03:29:15 2005 From: could.net at gmail.com (could ildg) Date: Tue, 28 Jun 2005 15:29:15 +0800 Subject: How to compress a folder and all of its sub directories and files into a zip file? In-Reply-To: <311b5ce1050628002075da2e3@mail.gmail.com> References: <311b5ce105062723167e892833@mail.gmail.com> <42C188F3.7010704@rt.sk> <311b5ce1050628002075da2e3@mail.gmail.com> Message-ID: <311b5ce10506280029682b9366@mail.gmail.com> but the file is just stored, and not compressed. On 6/28/05, could ildg wrote: > Thank you, > it works~~ > > On 6/29/05, Peter Szinek wrote: > > Hi, > > > > What about this: > > > > import os,zipfile > > from os.path import join > > > > > > zip = zipfile.ZipFile("myzipfile.zip", 'w') > > for root, dirs, files in os.walk('.'): > > for fileName in files: > > zip.write(join(root,fileName)) > > zip.close() > > > > Maybe it zips also the myzipfile.zip ;-) > > Probably this is not needed, so an additional test (something like > > fileName != 'myfile.zip' would be needed. > > > > HTH, > > Peter > > > > could ildg wrote: > > > I want to compress a folder and all of its sub files including empty folders > > > into a zip file. what's the pythonic way to do this? > > > > > > Thanks in advance. > > > > > From hongli at gmail.com Mon Jun 20 14:11:46 2005 From: hongli at gmail.com (frost) Date: 20 Jun 2005 11:11:46 -0700 Subject: login website that using PHP In-Reply-To: <1119263917.054114.213120@g14g2000cwa.googlegroups.com> References: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> <1119263917.054114.213120@g14g2000cwa.googlegroups.com> Message-ID: <1119291106.566334.297470@g49g2000cwa.googlegroups.com> Thank you all for the help. This problem bothered me for 3 days, Now I get it!!!!! You are right, it is the session cookie, after I use the cookiejar and the opener, I got it!!! I am really glad I found this place. Thank you again!!!!! From rkern at ucsd.edu Thu Jun 2 04:57:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 02 Jun 2005 01:57:25 -0700 Subject: Software licenses and releasing Python programs for review In-Reply-To: <7xd5r55j85.fsf@ruckus.brouhaha.com> References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "poisondart" writes: >>Yes, what I ask may seem ridiculous, but I don't view it that way. >>Instead, I find that it is the implication of using a restrictive >>license such as I described to be ridiculous: if there is no monetary >>gain option in the license, then this implies that nobody (or very few) >>will be willing to do any work or "asking for something for nothing". >>It isn't for nothing if you value knowledge and learning. > > Well, long experience has shown that in practice, such clauses tend to > turn away users and developers. And for thoroughness, allow me to add "even if they have no intention or desire to profit monetarily." I can't explain exactly why this is the case, but it seems to be true in the overwhelming majority of cases. Academic projects with non-commercial clauses languish in obscurity while academic Open Source projects thrive. The contributors to the Open Source projects value knowledge and learning just as much as the lonely developers of the non-commercial-only projects, but for whatever reason, they don't contribute to those non-commercial-only projects. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From donn at u.washington.edu Fri Jun 3 17:27:08 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 03 Jun 2005 14:27:08 -0700 Subject: calling ksh script from python References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> <8lkhyu4ap59o$.84pfven4y3nv$.dlg@40tude.net> Message-ID: In article <8lkhyu4ap59o$.84pfven4y3nv$.dlg at 40tude.net>, Thorsten Kampe wrote: > * Cameron Laird (2005-06-02 18:08 +0100) > > In article , > > Donn Cave wrote: > >>Meanwhile, it might be worthwhile to reconsider the use > >>of ksh here, if you have any choice in the matter. Ksh > >>is fine for interactive use, but has some unfortunate > >>flaws as a programming shell, and due to proprietary issues > >>one commonly encounters an alternative implementation that's > >>even worse. On most modern platforms, sh will have a pretty > >>good programming feature set, and will be more reliable > >>(especially if it isn't just ksh by another name.) > > . > > Infidel. While I sure feel that way about csh(1), it > > surprises me you'd criticize ksh(1) so. 'Fact, 'mong > > all the *sh-s, I *recommend* ksh for programming. May- > > be the two of us see things differently. > > http://groups-beta.google.com/group/comp.unix.shell/msg/98578e8d95137a3c Well, that certainly must just about say it all. It's nice to see that the author knows rc and es, which are indeed a couple of very much better designed shells. I am not sure I agree with him so much on shell programming in general, but it depends on what his point really may be. For sure, it's good to be aware of those things, at any rate. Donn Cave, donn at u.washington.edu From david.van.mosselbeen at telenet.be Wed Jun 15 12:27:19 2005 From: david.van.mosselbeen at telenet.be (David Van Mosselbeen) Date: Wed, 15 Jun 2005 16:27:19 GMT Subject: Show current ip on Linux References: <3h83ugFddjmuU1@news.dfncis.de> Message-ID: Sibylle Koczian wrote: > David Van Mosselbeen schrieb: >> >> Thanks for support. >> I have read the refered page you show above. I try some piece of code >> that im have copy and paste it into a blank file that i give the name >> "ip_adress.py" to test it. >> >> >> THE SOURCE CODE : >> ----------------- >> >> import commands >> >> ifconfig = '/sbin/ifconfig' >> # name of ethernet interface >> iface = 'eth0' >> # text just before inet address in ifconfig output >> telltale = 'inet addr:' >> >> def my_addr(): >> cmd = '%s %s' % (ifconfig, iface) >> output = commands.getoutput(cmd) >> >> inet = output.find(telltale) >> if inet >= 0: >> start = inet + len(telltale) >> end = output.find(' ', start) >> addr = output[start:end] >> else: >> addr = '' >> >> return addr >> # End python code >> >> But now, it's fine to have some piece of code but this wil not work on my >> computer. I'm sure that y do somethings bad. >> To run the python script on a Linux machine. How to proceed it ? >> >> 1) I have open a terminal >> 2) then i type "python ip_adress.py" (to run the script) >> >> But nothings, i not view the current ip of my computer. >> What happend ? >> > > You have defined a function, but you never call this function. Running a > script won't do anything, if this script consists only of function (or > class) definitions. > > You can either > > - open the interactive python interpreter and type: > import ip_adress > ip_adress.my_addr() > > or, probably simpler, > > - add the following two lines to your script, after the definition of > your function: > > if __name__ == '__main__': > print my_addr() > > Then run your script just as you did before. Now you are calling the > function and printing the value it returns. > It's work now :-) Verry thanks to all peoples that work free ont participating on documentation and shares hers brain. -- David Van Mosselbeen - DVM http://dvm.zapto.org:3333 --- Fedora Core 3 User From kveretennicov at gmail.com Thu Jun 16 19:57:50 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Fri, 17 Jun 2005 01:57:50 +0200 Subject: which ports to use for SOAP? In-Reply-To: References: Message-ID: <4660fe30050616165722520cce@mail.gmail.com> On 6/17/05, Maurice LING wrote: > Hi, > > I'm writing something that specifies the use of SOAP. One requirement > that fumbles me is the port number(s) to use. (I assume you're talking about TCP ports, not SOAP ports.) > Is there any way to find > out which ports are not used by the system? Try binding to a port and you'll get an 'Address already in use error' if it's occupied :) > I've looked in the library > reference and doesn't seems to get anything. > > Is there a problem with say 2 programs using the same ports? AFAIK, even the same process can't bind to the same port twice: >>> import socket >>> s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s1.bind(('localhost', 8000)) >>> s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s2.bind(('localhost', 8000)) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in bind socket.error: (10048, 'Address already in use') - kv From lambacck at gmail.com Thu Jun 2 23:51:58 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Thu, 2 Jun 2005 23:51:58 -0400 Subject: [python-gtk] problem with multiple inheritance In-Reply-To: <3ga08nFb9gavU1@individual.net> References: <3ga08nFb9gavU1@individual.net> Message-ID: One way to get around this would be to omit the TreeSortable interface and use TreeModelSort to do the sorting instead. It doesn't look like GenericTreeModel is designed to also support the TreeSortable interface (you would need something like GenericTreeSortable since you would need some magic to allow gobject inheritance from python.) -Chris On 6/2/05, Greg Ewing wrote: > Taki Jeden wrote: > > > class view_tree_model(gtk.GenericTreeModel,gtk.TreeSortable): > > > > raises a "TypeError: multiple bases have instance lay-out conflict" > > Is this a bug in gtk, or python-gtk, or something? > > It's not a bug, it's a limitation of the way Python > handles inheritance from built-in types. You can only > inherit from more than one built-in type if they have > compatible C structures, and it appears that the two > you're trying to inherit from aren't compatible. > > You'll have to think of some way of doing whatever > you're trying to do without inheriting from multiple > gtk types. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From pwilkins at noaddress.org Fri Jun 24 22:12:29 2005 From: pwilkins at noaddress.org (pwilkins) Date: Fri, 24 Jun 2005 22:12:29 -0400 Subject: Newbie question: SOLVED (how to keep a socket listening), but still some questions References: Message-ID: On Fri, 24 Jun 2005 21:42:48 -0400, Jp Calderone wrote: > shutdown actually tears down the TCP connection; close releases the file > descriptor. > > If there is only one file descriptor referring to the TCP connection, > these are more or less the same. If there is more than one file > descriptor, though, the difference should be apparent. > > Jp Yes I think you are right. I checked with the "Socket Programming HOWTO" by Gordon McMillan @ http://www.python.org/doc/howto. Here's a quote: "Strictly speaking, you're supposed to use shutdown on a socket before you close it. The shutdown is an advisory to the socket at the other end. Depending on the argument you pass it, it can mean "I'm not going to send anymore, but I'll still listen", or "I'm not listening, good riddance!". Most socket libraries, however, are so used to programmers neglecting to use this piece of etiquette that normally a close is the same as shutdown(); close(). So in most situations, an explicit shutdown is not needed." However my first understanding from the python docs is quite different.. it was that like a unix pipe, a socket could be made to communicate in one direction only. Like a RD-only pipe a socket could be made RD-only and another socket WR-only...perhaps like ftp keeps the control channel open but transmits over a read only socket??? From max at alcyone.com Wed Jun 8 04:34:16 2005 From: max at alcyone.com (Erik Max Francis) Date: Wed, 08 Jun 2005 01:34:16 -0700 Subject: poker card game revisited (code included) In-Reply-To: References: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> Message-ID: flupke wrote: > Which projects are you talking about? I only found a library in c to > evaluat ranks but i didn't find the code to be very understandable. pokersource is the main was I was thinking about, yes. > With histogram do you mean something like this: > Card hand: 2 clubs, 3 diamonds, 10 of diamonds, 4 of hearts, 3 of hearts > > Histogram 1: list [2,3,4,10] > 2 --------------------- 14 > Histogram 2: list [1,2,1,0,0,0,0,0,1,0,0,0,0] > or > list [1,2,1,1] > so index 0 is count of rank at index 0 of Histogram 1 > index 1 is count of rank at index 1 of Histogram 1 Histograms usually involve putting things in bins and counting the number by bin. Here the bins are just the ranks of the cards, and so you're counting the frequency of the ranks. Once that's done, you want to arrange the frequencies into a mapping of its own, which points to the list of ranks that have that frequency. That way you can easily pick things off: If there is a hit in the four bin, you have quads. If there's a hit in the three bin and either another in the three or one in the two bin, you have a boat. If there's a hit in the three bin but _not_ another in three or two, then it's trips. And so on. > As for straights, if i understand correctly, you make all possible > straights of the cards in the hand and then see if one matches? Not quite. You break down the cards by what matters -- ranks and suits -- and then make sets based on these. Then, standing by, you have the sets of valid straights (by rank), and then to test for straights, you iterate through the straight sets and make intersections with the rank set for the hand in question. If the intersection is the same as the straight set, then it's a straight. (Do this by reverse order of the relative values of the straights, and stop when you find the first one, to get the highest straight.) The most efficient way to do this is with a bitmask, so that's how it's usually done. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Love is the wisdom of the fool and the folly of the wise. -- Samuel Johnson From thomas at thomas-lotze.de Mon Jun 13 07:59:16 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Mon, 13 Jun 2005 13:59:16 +0200 Subject: why python on debian without the module profile? References: Message-ID: kyo guan wrote: > ImportError: No module named profile They moved it to non-free because the module's license isn't DFSG compliant. -- Thomas From dave925 at earthlink.net Thu Jun 23 22:54:52 2005 From: dave925 at earthlink.net (Dave) Date: 23 Jun 2005 19:54:52 -0700 Subject: Idle.pyw doesn't start in 2.4.1 Message-ID: <1119581692.162494.216190@o13g2000cwo.googlegroups.com> Hi, I installed 2.4.1 on both my wife's & my computer. Her idle (pyw) starts fine, but mine doesn't. I have had previous versions on my computer as well as idlefork, but I removed them before installing 2.4.1. I tried uninstalling and reinstalling several times, and my idle.pyw file does not respond. When I click the idle.py file, it starts a console with the following error message printed 13 times: Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'test'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'test'. returning default value: '#000000' Then it boots a blank idle window with white menus. My wife's pull-down menus are gray. I don't know if the color is a clue to anything or not. Anyone else have this problem, know why it happened, or know how to solve it? Yes, I could just use the idle that boots with idle.py, but I'm just wondering why her install produced a clean working version and my install came with this bug? Thanks -Dave From maxm at mxm.dk Wed Jun 8 05:12:50 2005 From: maxm at mxm.dk (Max M) Date: Wed, 08 Jun 2005 11:12:50 +0200 Subject: how to export data from ZODB to text files In-Reply-To: References: Message-ID: <42a6b680$0$237$edfadb0f@dread12.news.tele.dk> ls wrote: > I'm experienced mostly in C, PHP, also with some backgrounds of CPP > and Java, but I'm totaly new in Python ... > > What do you suggest in this case? The simplest approach is to run Zope with the Data.fs file. If you have access to the zope instance you want to export from, you only need to write an external method in Zope to export the data you want. Its pretty easy that way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From calfdog at yahoo.com Thu Jun 23 00:03:16 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 22 Jun 2005 21:03:16 -0700 Subject: How to receive events (eg. user mouse clicks) from IE In-Reply-To: <42acd28f$1_1@spool9-west.superfeed.net> References: <1116476411.853695.235670@g14g2000cwa.googlegroups.com> <428c3cbe$1_1@spool9-west.superfeed.net> <1116529345.146032.91880@f14g2000cwb.googlegroups.com> <428cf5a9$1_1@spool9-west.superfeed.net> <1116537405.495521.252570@f14g2000cwb.googlegroups.com> <428f5882$1_2@spool9-west.superfeed.net> <428f8660$1_1@spool9-west.superfeed.net> <1116792093.323847.312700@g49g2000cwa.googlegroups.com> <42915ad9$1_1@spool9-west.superfeed.net> <1118544283.178003.277370@g47g2000cwa.googlegroups.com> <42acd28f$1_1@spool9-west.superfeed.net> Message-ID: <1119499396.624621.131140@f14g2000cwb.googlegroups.com> You also want to make sure the frame you want is loaded I use the following method: def _frameWait(self, frameName=None): thisCount = self._timeOut while self._ie.Busy: time.sleep(0.1) thisCount = thisCount - 1 if thisCount == 0: break # wait for user specified Document to load doc = self._ie.Document.frames[frameName].Document # Check results bresult = False thisCount = self._timeOut #reset the timeout counter while doc.ReadyState != 'complete': time.sleep(0.1) thisCount = thisCount - 1 if thisCount == 0: break if doc.ReadyState == 'complete': bresult = True if bresult == True: print "Using Frame: " ,frameName else: print " Loading . . ." Roger Upole wrote: > Each frame acts as a separate document. > You should be able catch document events > from a frame using something like > win32com.client.DispatchWithEvents(ie.Document.frames().document, ) > > Roger > > > wrote in message news:1118544283.178003.277370 at g47g2000cwa.googlegroups.com... > > Resurrecting an old thread.. > > It seems that this solution does not return events on objects within > > frames in webpages eg . if you go to www.andersondirect.com - the page > > is composed of three frames called as topFrame main and address. Now > > when I click on say 'Select a Vehicle' which is within main - I do not > > get any Onclick event. I also do not get an OnMousemove event if I move > > the mouse. However, I do get on Mousemove event on a tag called as > > frameset (which is part of the top page). > > How does one get events from the frames then? > > As always thanks a lot. > > > > Roger Upole wrote: > >> wrote in message > >> news:1116792093.323847.312700 at g49g2000cwa.googlegroups.com... > >> ... > >> > The problem is that msdn documentation says that in order to identify > >> > the element that was clicked - one has to query on IHTMLWindow2::event > >> > property on iHTMLWindow2 interface to get IEventOBj interface and then > >> > from there - use query interfce to get to the id of the element. > >> > > >> > How do I do this in python? ie. I have this code > >> > class Doc_Events(doc_mod.HTMLDocumentEvents): > >> > def Ononclick(self): > >> > print 'onClick fired ' > >> > and I see onClick being trapped. > >> > Now I need to go and get a reference to the iHTMLWindow2 interface. For > >> > this I need to get a reference to doc_mod (as far as I can see). How do > >> > I get that in the OnonClick method above. > >> > >> To get the IHTMLWindow2, you can just use self.parentWindow > >> inside the event hander, and then get the event from it. And then > >> the event's srcElement should be what you need. > >> > >> class Doc_Events(doc_mod.HTMLDocumentEvents): > >> def Ononclick(self): > >> print 'onclick' > >> ev=self.parentWindow.event > >> src=ev.srcElement > >> print 'tagName:',src.tagName,'name:',src.getAttribute('name') > >> > >> For clicking on google's input field, this yields > >> tagName: INPUT name: q > >> > >> > > >> > b) You had mentioned PumpWaitingMessages in the previous posting. I > >> > first encountered this on newsgroup postings. None of the standard > >> > books (python on win32 / python developer) seem to explain this in > >> > detail although this seems to be commonly used. Though I understand > >> > this now - my problem is that there seems to be a lack of cohesive > >> > explanation on how python ties up with COM (despite a good chapter 12 > >> > >> PumpWaitingMessages is just a way to ensure that normal message processing > >> (window messages, events, dde, etc) happens while python code is running. > >> Normally you don't need it, but every once in a while you hit a situation > >> where > >> blocking occurs. > >> > >> For how exactly python interacts with COM, the source is your best bet. > >> > >> Roger > >> > >> > >> > >> > >> > >> ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- > >> http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > >> ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- > > > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From martin at v.loewis.de Mon Jun 13 16:43:22 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Jun 2005 22:43:22 +0200 Subject: How to use 8bit character sets? In-Reply-To: <11aqrivp3834200@news.supernews.com> References: <42ad11a7$0$24953$9b622d9e@news.freenet.de> <11aqrivp3834200@news.supernews.com> Message-ID: <42ADEFEA.80007@v.loewis.de> John Roth wrote: >> That is the default. > > > As far as I can tell, there are actually two defaults, which tends > to confuse things. Notice that there are two defaults already in the operating system: Windows has the notion of the "ANSI code page" and the "OEM code page", which are used in different contexts. > One is used whenever a unicode to 8-bit > conversion is needed on output to stdout, stderr or similar; > that's usually Latin-1 (or whatever the installation has set up.) You mean, in Python? No, this is not how it works. On output of 8-bit strings to stdout, no conversion is ever performed: the byte strings are written to stdout as-is. > The other is used whenever the unicode to 8-bit conversion > doesn't have a context - that's usually Ascii-7. Again, you seem to be talking about Unicode conversions - it's not clear that the OP is actually interested in Unicode conversion in the first place. Regards, Martin From agriff at tin.it Fri Jun 17 07:51:37 2005 From: agriff at tin.it (Andrea Griffini) Date: Fri, 17 Jun 2005 11:51:37 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: On 17 Jun 2005 01:25:29 -0700, "Michele Simionato" wrote: >I don't think anything significant changed in the percentages. Then why starting from print "Hello world" that can't be explained (to say better it can't be *really* understood) without introducing a huge amount of magic and not from a simple 8 bit CPU instead ? What are the pluses of the start-from-high-level approach ? If one is to avoid bordeom I don't agree as assembler is all but boring (when you start), or at least this was what *I* experienced. If it's about the time it will take to get a rotating 3d torus with live video on it I know for sure that most of the programmers I know that started from high level will probably *never* reach that point. Surely if you start say from pull-down menus they'll be able to do pull down menus. And IMO there are good chances they'll stay there lifetime. So is python the good first programming language ? IMO not at all if you wanna become a programmer; it hides too much and that hidden stuff will bite back badly. Unless you know what is behind python it will be almost impossible for you to remember and avoid all the traps. Buf if you need to know what is behind it then it's better to learn that stuff first, because it's more concrete and simpler from a logical point of view; the constructions are complex but (because) the bricks are simpler. But it probably all boils down to what is a programmer. Is C++ a good first programming language ? BWHAHAHAHAHAHAHAHA :D But apparently some guru I greatly respect thinks so (I'm not kidding, http://www.spellen.org/youcandoit/). Andrea From kaka.hui at gmail.com Tue Jun 21 21:05:24 2005 From: kaka.hui at gmail.com (Cathy Hui) Date: 21 Jun 2005 18:05:24 -0700 Subject: Installing MySQL-Python Message-ID: <1119402324.019970.42590@g43g2000cwa.googlegroups.com> Do u know why do i get the following message when trying to build the MySql-Python (1.2.0) on my Solaris 8 system? (with mysql 4.0.21 and python 2.4). thanks! error mesg: ld: fatal: relocations remain against allocatable but non-writable sections collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 see below for the log ===================================================== # python setup.py build unknown> 0x5c8 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0x840 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0x84c /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0x9b4 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0x9bc /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0x9f8 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0xa04 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0xa98 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0xaac /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0xad0 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0xae0 /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) 0xb0c /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) . . . ld: fatal: relocations remain against allocatable but non-writable sections collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 From peter at somewhere.com Mon Jun 27 10:18:46 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 27 Jun 2005 16:18:46 +0200 Subject: Daten Kinderheilkunde Message-ID: Sehr geehrter Herr Wurm, vielen Dank f?r die Zusendung der Daten. Es handelt sich allerdings nicht um jpeg-Dateien, wie die Erweiterung nahelegt. Wir konnten sie nur mit dem PictureViewer auf einem Apple anzeigen. Sie werden unter MacOS als Adobe-Photoshop-Dokument angezeigt. K?nnen wir die Dateien als jpegs bekommen oder sollen wir sie selbst umwandeln? Mit freundlichen Gruessen, Peter Maas -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From grahamd at dscpl.com.au Wed Jun 22 01:10:15 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 21 Jun 2005 22:10:15 -0700 Subject: need help with mod_python in RH 9 In-Reply-To: References: Message-ID: <1119417015.364642.197730@f14g2000cwb.googlegroups.com> Oh, one minor thing. Your content type should be "text/plain" and not "text/html" as you aren't returning HTML This isn't going to be causing the problem you are seeing though. Graham From desertgarden at netscape.com Wed Jun 29 18:47:09 2005 From: desertgarden at netscape.com (Brian) Date: Wed, 29 Jun 2005 22:47:09 GMT Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: Steven, Very well written... I enjoyed reading your post! Brian --- Steven D'Aprano wrote: > On Tue, 28 Jun 2005 11:27:40 -0700, muldoon wrote: > > >>Americans consider having a "British accent" a sign of sophistication >>and high intelligence. Many companies hire salespersons from Britain to >>represent their products,etc. Question: When the British hear an >>"American accent," does it sound unsophisticated and dumb? > > > Which American accent? > > Texan? Georgian cracker or Maine fisherman? New York taxi driver? Bill > Clinton or Jesse Jackson or George W Bush? California Valley girl, > Arkansas redneck or boyz from th' hood? Paris Hilton or Queen Latifah? > > >>Be blunt. We Americans need to know. Should we try to change the way we >>speak? Are there certain words that sound particularly goofy? Please >>help us with your advice on this awkward matter. > > > Speaking as an Australia, the typical "film voice" (eg Harrison > Ford, Tom Cruise, etc) doesn't sound unsophisticated. In fact, when we > hear it, it doesn't sound like an accent at all, such is the influence of > Hollywood. (Which is linguistically impossible, of course, since *every* > way of speaking is by definition an accent.) The Hollywood voice is a > mixture of West Coast and very light mid-Western. > > But as for the rest of you, yes, you sound -- strange. It depends on the > specific regional accent. At best, just different. At worst, dumber than a > box of hammers. Which is of course unfair: there is no connection between > accent and intelligence. But by gum, some accents just sound dumber than > others. My fiancee, from Ireland, has worked and lived in the USA for half > her life, and to her you all sound like Kermit the Frog and Miss Piggy. > > Lest anyone gets offended, I should point out that every English-speaking > country have accents which are considered by others to mark the speaker as > a thick yokel. In Ireland, they look down on Kerrymen. In England, even > Yorkshiremen look down on Summerset, Devon and Dorset accents. And there > is nothing as thick-sounding as a broad Ocker Aussie accent. > > But don't worry, there is one thing we all agree on throughout the > English-speaking world: you Americans don't speak English. > > There are a few things that you can do to help: > > Herb starts with H, not E. It isn't "ouse" or "ospital" or "istory". It > isn't "erb" either. You just sound like tossers when you try to pronounce > herb in the original French. And the same with homage. > > Taking of herbs, there is no BAY in basil. And oregano sounds like Ray > Romano, not oh-reg-ano. > > And please, fillet of fish only has a silent T if you are speaking French. > > Aluminium is al-u-min-ium, not alum-i-num. > > Scientists work in a la-bor-atory, not a lab-rat-ory, even if they have > lab rats in the laboratory. > > Fans of the X-Men movies and comics will remember Professor Charles > Xavier. Unless you are Spanish (Kh-avier), the X sounds like a Z: Zaviour. > But never never never Xecks-Aviour or Eggs-Savior. > > Nuclear. Say no more. > > From deetsNOSPAM at web.de Thu Jun 2 08:20:15 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 02 Jun 2005 14:20:15 +0200 Subject: using builtin array References: <1117641183.057537.118020@z14g2000cwz.googlegroups.com> <1117656339.288904.23360@f14g2000cwb.googlegroups.com> Message-ID: > Arrays are homogenous. No chance concatenating them. This should of course read "No chance concatenating arrays of different typecodes". -- Regards, Diez B. Roggisch From listserver at tdw.net Tue Jun 7 05:01:31 2005 From: listserver at tdw.net (Tim Williams) Date: Tue, 7 Jun 2005 10:01:31 +0100 Subject: SMTP help please References: <000901c56b3e$b1be99d0$ccbefea9@twilliams> Message-ID: <001201c56b3f$864f41e0$ccbefea9@twilliams> ----- Original Message ----- From: "Tim Williams" > > try: > s.close() > except > pass Typo!! That should be s.quit() not s.close() :) From gregpinero at gmail.com Thu Jun 23 14:38:15 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 23 Jun 2005 14:38:15 -0400 Subject: os.system(cmd) isn't working In-Reply-To: <1119546272.468604.245950@z14g2000cwz.googlegroups.com> References: <1119546272.468604.245950@z14g2000cwz.googlegroups.com> Message-ID: <312cfe2b05062311384cd5f8bb@mail.gmail.com> Thanks to everyone for all the help! After careful consideration I decided to go with os.startfile(url) It works just great! Here's my program in case anyone's interested. 5 points if you can guess what it does ;-) """Take a filepath from stdin and translate to the corresponding url and open up browser and show it.""" import sys import os myhtmlroot='C:\\Documents and Settings\\Gregory\\My Documents\\blendedtechnologies\\trunk' htmlroot='http://www.blendedtechnologies.com' filepath=sys.argv[1] filename=os.path.basename(filepath) filedir=os.path.dirname(filepath).replace(myhtmlroot,'').replace('\\','/') url=htmlroot+'/'+filedir+'/'+filename os.startfile(url) -Greg On 23 Jun 2005 10:04:32 -0700, drobinow at gmail.com wrote: > If firefox is not your default browser, > os.system(r'"cd c:\Program Files\Mozilla Firefox & firefox "' + > '"www.blendertechnologies.com "') > > works for me. > > -- > http://mail.python.org/mailman/listinfo/python-list > From peter at engcorp.com Thu Jun 9 14:40:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 14:40:31 -0400 Subject: Any way to not create .pyc files? In-Reply-To: References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: Peter Hansen blathered [about whether a .pyc will be regenerated if the path encoded in it changes]: > I take it back... that could be the reason. I just checked and the path > to the .py file is encoded in the .pyc. I don't know if it's actually > used in the decision whether to recompile the .pyc or not (it could just > be for use in showing tracebacks with source), but it's a possibility... > pretty easy to test too. Well, it doesn't look like that's the case. I have a system happily importing (without regenerating it) a .pyc file that has a now-nonexistent path encoded in it. Even shows tracebacks properly... (now I'm curious what the embedded path is actually used for). -Peter From bogus@does.not.exist.com Mon Jun 20 16:35:02 2005 From: bogus@does.not.exist.com () Date: Mon, 20 Jun 2005 20:35:02 -0000 Subject: No subject Message-ID: #! rnews 902 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Couple functions I need, assuming they exist? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 15 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Mon, 20 Jun 2005 20:12:51 GMT Xref: news.xs4all.nl comp.lang.python:382593 Charles Krug writes: [snip] > The target of the problems (my daughter) ... [snip] That sounds familiar :-). See: http://www.seanet.com/~hgg9140/math/index.html http://www.seanet.com/~hgg9140/math/k6.html -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From lee_cullens at mac.com Wed Jun 8 00:52:06 2005 From: lee_cullens at mac.com (Lee Cullens) Date: Wed, 8 Jun 2005 00:52:06 -0400 Subject: OO re-factoring (was Pythonese/Efficiency/Generalese critique [on Tutor]) Message-ID: In my original post I noted my recent exposure to Python and put up a little utility to my iDisk asking for a Pythonese/Efficiency/ Generalese critique. Javier, Kent and Liam were gracious enough to offer comments, which were greatly appreciated. To follow through with the learning exercise, I incorporated their comments (at least the ones there were no conflicting opinions on :~) and put up the new version as: http://homepage.mac.com/lee_cullens/DirTreeToCSV.zip I was thinking of extending the learning exercise by re-factoring it as an OO approach, since it would contain a minimum altered method. Being new to OOP also though, I'm confusing myself with how that would be best accomplished. My thinking is that class/subclass method instances would replace the recursive functions approach, but have as yet not formed the coding in my mind. I've read a lot on OOP, but seem to have a problem with the practical use of such in this utility. I'm undoubtedly creating a mountain of an ant hill in my mind, so any thoughts would be appreciated. Thanks, Lee C From jmdeschamps at cvm.qc.ca Tue Jun 14 09:29:27 2005 From: jmdeschamps at cvm.qc.ca (jean-marc) Date: 14 Jun 2005 06:29:27 -0700 Subject: Python as CGI on IIS and Windows 2003 Server In-Reply-To: <1118395325.128822.178110@g44g2000cwa.googlegroups.com> References: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> <1118338442.024062.24150@o13g2000cwo.googlegroups.com> <1118376702.458747.309710@g14g2000cwa.googlegroups.com> <1118395325.128822.178110@g44g2000cwa.googlegroups.com> Message-ID: <1118755767.945105.110680@z14g2000cwz.googlegroups.com> lothar.sch at gmx.de wrote: > jean-marc schrieb: > > Some bits are coming back to me: the problems stemmed from adresses - > > getting the root of IIS was different so accessing files didn't work > > the same way. > > thanks for that. > you are right, IIS versions are different. > Wich kind of adresses do you mean, http-adresses or paths in file > systems to root of IIS or to pythonscripts below IIS' root? > > Unfortunately I couldn't find a way to solve the problem. > > > regards > Lothar I think it was due to the way of getting a reference to the IIS's root - I think that all adresses in html (wheter from static documents or those generated by python) need to use relative adresses (double dot slash, or dot slash type of adresses). If it still doesn't work maybe posting some culprit code could help figure it out...! Jean-Marc May From eurleif at ecritters.biz Wed Jun 15 23:21:38 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 16 Jun 2005 03:21:38 GMT Subject: Called function conditional testing (if) of form variables problem In-Reply-To: References: Message-ID: <6f6se.128$Q75.38358@newshog.newsread.com> Eduardo Biano wrote: > def foo(request): > ans01 = request.get_form_var("ans01") > if ans01 == 4: > ans_1 = 1 > return ans_1 ans01 will be a string ("4"), not an int (4). From timr at probo.com Sun Jun 19 02:36:08 2005 From: timr at probo.com (Tim Roberts) Date: Sat, 18 Jun 2005 23:36:08 -0700 Subject: Help implementing an idea References: Message-ID: Nicholas.Vaidyanathan at asu.edu wrote: > >Well, I'm a total python n00b, but I was playing around with exception handling >yesterday, and was stricken by how incredibly easy it is to use the op system >to create nice scripts... I did the following: > >import sys >lines = sys.stdin.readlines() >lines.sort() >for stuff in lines: > print stuff , Or sys.stdout.writelines( lines ). >just to copy stuff from one file to another, and was quite impressed with the >results. Now, I was thinking today, I'd really like to create a program that >can go to a specific directory and upload all the files in the directory to a >specific url for backup purposes, and I have the feeling that the python >implementation would be ruthlessly small and efficient, like the >above....anyone who could point me in the right direction as to how to actually >do it? How do you want to do the upload? FTP? That's easy. Check ftplib.py. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From eric_brunel at despammed.com Fri Jun 24 11:57:30 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 24 Jun 2005 17:57:30 +0200 Subject: Frame widget (title and geometry) References: Message-ID: On Fri, 24 Jun 2005 10:21:01 -0400, Shankar Iyer (siyer at Princeton.EDU) wrote: > Hi, > > I am still new to Python and Tkinter, so I apologize in advance if I do not > word my question optimally. I am trying to use a frame widget as the parent > for other widgets. There is a class with the header "class classtitle(Frame):" > in a script called classtitle.py. Having imported classtitle, I create a Frame > widget within my gui using the command "w = Frame(self)." Then, I grid this > widget and issue the command "classinstance = classtitle.classtitle(w)." When > I attempt to execute this code, I receive an error claiming that w lacks > geometry and title attributes that the code in classtitle.py attempts to access. > Does this mean that I cannot use a Frame widget as w in this situation? Thanks > for your help. Please post a short script showing the behavior you get. Without this, we cannot help you much. The only thing I can tell you right now is that you obviously don't need to create a Frame via "w = Frame(self)": since you defined your classtitle class as a sub-class of frame, every instance of classtitle is also an instance of Frame, so you can use it as such: >>> from Tkinter import * >>>root = Tk() >>> class MyClass(Frame): ... pass ... >>> o = MyClass(root) >>> o.grid() just works. If you have to add anything in the constructor, do not forget to call the constructor for Frame in it, as in: >>> class MyClass(Frame): ... def __init__(self, *args, **options): ... Frame.__init__(self, *args, **options) ... ## Other stuff... ... If you do that, everything should be OK. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From ods at strana.ru Sat Jun 18 11:52:20 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Sat, 18 Jun 2005 19:52:20 +0400 Subject: Static (why?) PyDateTimeAPI and SIP Message-ID: <20050618195220.1a5db406@ods.pravda.rfn.ru> I use datetime C API in extension module generated with SIP. But SIP break the code into several .cpp files compiled separately and PyDateTimeAPI used by all macros constituting public interface is declared static. The current solution is to define my own functions in main module as workaround: %ModuleHeaderCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs); %End %ModuleCode PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int seconds, int usecs) { return PyDateTime_FromDateAndTime(year, month, day, hour, minute, seconds, usecs); } // and so on for each macro used %End %PostInitialisationCode PyDateTime_IMPORT; %End But I wonder why PyDateTimeAPI is declared static, and is the a better solution? -- Denis S. Otkidach http://www.python.ru/ [ru] From roy at panix.com Tue Jun 14 08:59:06 2005 From: roy at panix.com (Roy Smith) Date: Tue, 14 Jun 2005 08:59:06 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > High and low tides aren't caused by the moon. They're not??? From pdemb at gazeta.pl Sun Jun 12 17:51:24 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 12 Jun 2005 23:51:24 +0200 Subject: python bytecode grammar References: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> <874qc3inla.fsf@hector.domek> Message-ID: <87mzpv9rc3.fsf@hector.domek> "Terry Reedy" writes: > "Peter Dembinski" wrote in message > news:874qc3inla.fsf at hector.domek... >> "Terry Reedy" writes: >>> I believe the top-level production is something like >>> BYTECODE := (OPCODE ARGS)* >> >> ROTFL :) > > Glad to make your day ;-) You are welcome. "Asking stupid questions is the best way to get quick answers" :> From ajikoe at gmail.com Sun Jun 19 14:26:42 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 19 Jun 2005 11:26:42 -0700 Subject: tab 2 into tab 4 ? Message-ID: <1119205602.922944.204990@g44g2000cwa.googlegroups.com> Hello, I have python code which use tab=2. Recently I would like to change it into tab=4. Anyone has suggestion to convert easily and safely ? pujo From thomas.weholt at gmail.com Thu Jun 9 13:11:19 2005 From: thomas.weholt at gmail.com (Thomas W) Date: 9 Jun 2005 10:11:19 -0700 Subject: cx_freeze error : LookupError: no codec search functions registered: can't find encoding Message-ID: <1118337079.095493.117690@g43g2000cwa.googlegroups.com> I get this error when I try to run a freezed exe on my ubuntu 5.04 running Python 2.4 : LookupError: no codec search functions registered: can't find encoding I've tried to use --include-modules encodings,codecs when freezing without luck. Any hints? Regards, Thomas From venkatasubramanian at gmail.com Mon Jun 6 12:17:52 2005 From: venkatasubramanian at gmail.com (venkata subramanian) Date: Mon, 6 Jun 2005 21:47:52 +0530 Subject: maybe a bug in python In-Reply-To: References: Message-ID: If you have any doubts, try to remeber this when creating tuples, if a tuple is to have 0 elements, then it must be given as a=() in other words, the ( and the ) are essential if it has one element, then a comma after that element is essential a=1, or alternatively a=(1,) in other words, an end comma is essential but the parentheses are not if it has more than one element, comma between the elements is only essential a=1,2 or alternatively a=1,2, or alternatively a=(1,2) i might have made some silly mistake.... so wait till some one points it out (if the mistakes are there) :) flyaflya wrote: > > > > >>> a = {1: ("a")} > > >>> a[1] > > 'a' > > why not ('a')? when > > >>> a = {1: ((("a")))} > > >>> a[1] > > 'a' > > the result is 'a' too,not ((("a"))).but when use["a"] or ("a","b"),the > > tuple is longer than 1, it's no problem. > > > > > > > > To define a tuple literal with one member, you must place a comma > after the first element like this: > > a = {1: ("a",)} > > I read this somewhere in the python docs, so I know its there > somewhere. > > The comma eliminates ambiguity as to the meaning of the brackets, > which without the comma are simply enclosing and precedence > controlling brackets. > > Steve From hotdoc at despammed.com Tue Jun 28 11:29:02 2005 From: hotdoc at despammed.com (Andreas Heiss) Date: Tue, 28 Jun 2005 17:29:02 +0200 Subject: building python 2.4.1 Message-ID: Hi ! I am trying to build python 2.4.1 from source on a Linux system. Everything seems fine, but tkinter seems not to work. The file _tkinter.pyd is missing. How can tell configure to build all necessary components ? Thanks Andreas From gijs at globaltrack.com Thu Jun 2 10:33:53 2005 From: gijs at globaltrack.com (Gijs Korremans) Date: Thu, 2 Jun 2005 16:33:53 +0200 Subject: return pramater in com object function Message-ID: <200506021437.j52Ebrbo004397@rrba-146-94-166.telkomadsl.co.za> Hi, One of the functions in the com object I need to use has a pointer in one of it's functions (object.function(string input, struct * output)) (I've created the struct with win32com.client.Record("structure", object)) I've tried to use the id() function but then Python gives me a message that it's an int, not a tructure and when I just give the object without a pointer, the object is still empty afterwards. In the mailinglist archive I saw this message from Mark Hammond: "Well, their IDL is at fault, and it clearly should be marked as [in,out]. All we should need to do is to get the makepy generated code for this function, and change the last "type tuple" for this function. It will be a tuple of, eg (pythoncom.VT_OBJECT, pythoncom.PARAMFLAG_FIN). Telling Python it is really _FIN | _FOUT should do the trick" So I opened the by genPy generated file and tried to change the last tuple from _ApplyTypes_ but it was already 2 (PARAMFLAG_FOUT): return self._ApplyTypes_(1, 1, (24, 0), ((8, 1), (36, 2)), 'SetIDString', None,inID, outID) Does anyone know how to solve this? Kind regards, Gijs -- This message has been scanned for viruses and dangerous content by Network Sentry, and is believed to be clean. http://www.networksentry.co.za From http Wed Jun 29 00:09:12 2005 From: http (Paul Rubin) Date: 28 Jun 2005 21:09:12 -0700 Subject: How to find Windows "Application data" directory?? References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> <1120017647.696243.154880@f14g2000cwb.googlegroups.com> Message-ID: <7xbr5pkdnb.fsf@ruckus.brouhaha.com> "Rune Strand" writes: > You have the environment variable APPDATA. You can access it with > os.environ(). Thanks!!!!!! Wow, I'd been hacking away at much messier approaches than that. It's actually os.environ['APPDATA'] ;-) From knight at baldmt.com Thu Jun 9 06:35:22 2005 From: knight at baldmt.com (Steven Knight) Date: Thu, 9 Jun 2005 06:35:22 -0400 (EDT) Subject: identifying 64-bit Windows from 2.3.5? In-Reply-To: References: Message-ID: Hi Ivan-- >> If I have installed 2.3.5 from the python.org Windows installer, can >> any one point me to a run-time way to identify whether I'm running on >> a 32-bit vs. 64-bit version of Windows XP, given that Python itself was >> built on/for a 32-bit system? > > I really don't think it matters too much which one you have, I have 64 bit > and it works fine. Yes, the same Python executable and code works just fine on both systems, but I need to do different things (in this case, invoke a different compiler with a different set of compiler options) based on whether or not I'm building on a 32-bit or 64-bit system. Thanks, --SK From hancock at anansispaceworks.com Thu Jun 23 15:01:48 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 23 Jun 2005 14:01:48 -0500 Subject: os.system(cmd) isn't working In-Reply-To: <3hv2j3Fit96kU1@individual.net> References: <3hv2j3Fit96kU1@individual.net> Message-ID: <200506231401.48261.hancock@anansispaceworks.com> On Thursday 23 June 2005 01:19 am, Paul Watson wrote: > "Gregory Pi?ero" wrote in message > news:mailman.787.1119499378.10512.python-list at python.org... > os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' > "www.blendedtechnologies.com"') > > The goal is to have firefox open to that website. You don't have any spaces between the command and the argument, I would assume they'd be necessary. I also notice you are quoting the quotes here, so I presume you actually need them (maybe this is because you have an embedded space in the filename?). Need I mention that using filenames with spaces is a great evil? ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From newsgroups at jhrothjr.com Fri Jun 3 11:06:52 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 3 Jun 2005 09:06:52 -0600 Subject: Python 2.4 and BLT References: Message-ID: <11a0sghptpisj7b@news.supernews.com> Could you please expand the BLT acronym. For the life of me, the only thing I associate it with is a Bacon, Lettuce and Tomato sandwich, and I'm sure that's not what you meant. John Roth "Lyddall's" wrote in message news:mailman.417.1117744335.18027.python-list at python.org... > Hello. > > I am new to this list, but wondered if anyone could help me. I have had > Python set up with PMW and BLT on two machines previous to my current > laptop, but I can't seem to get them all to work together on this machine. > It may be the version of python (2.4, with TCL 8.4) that I have installed > since I had older version on the other machines. > > Anyway - can anyone give me suggestions of how to get BLT to work? > (versions: python 2.4, Tcl 8.4, BLT 2.4) I have run the BLT installer, > copied the dlls into the tcl/bin directory and added that directory to my > path. Still the demos don't recognize BLT as being installed. > > Alternatively - what would be the best graphics extension to learn in > place of BLT if, as it seems, BLT is not supported by anyone any longer. > > thank you, > Ali > > From rgacote at AppropriateSolutions.com Wed Jun 22 15:14:51 2005 From: rgacote at AppropriateSolutions.com (Ray Cote) Date: Wed, 22 Jun 2005 15:14:51 -0400 Subject: Database recommendations for Windows app In-Reply-To: <42b97240$0$24467$da0feed9@news.zen.co.uk> References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: At 3:14 PM +0100 6/22/05, Will McGugan wrote: >Hi, > >I'd like to write a windows app that accesses a locally stored database. >There are a number of tables, the largest of which has 455,905 records. > >Can anyone recommend a database that runs on Windows, is fast / >efficient and can be shipped without restrictions or extra downloads? > >I have googled and found plenty of information on databases, its just >that I dont have enough experience with databases to know which one is >best for my task! > > >Thanks in advance, > >Will McGugan We use Firebird for that. --Ray -- Raymond Cote Appropriate Solutions, Inc. PO Box 458 ~ Peterborough, NH 03458-0458 Phone: 603.924.6079 ~ Fax: 603.924.8668 rgacote(at)AppropriateSolutions.com www.AppropriateSolutions.com From gsakkis at rutgers.edu Sat Jun 18 18:06:03 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 18 Jun 2005 15:06:03 -0700 Subject: Why is there no instancemethod builtin? References: Message-ID: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> "Steven Bethard" wrote: > John Reese wrote: > > I now do: > > > > if isinstance(x, list): > > > > It is my understanding that this is what people do nowadays. > > I wouldn't go that far. I don't have an isinstance check for lists > anywhere in my entire codebase. Why do you think you need to check to > see if something is of type list? Why don't you just use it as needed, > and find out, e.g.: > > try: > itr = iter(x) > except TypeError: > # do whatever you need to do if it's not iterable > else: > # do whatever you need to do if it *is* iterable A class of cases I've found necessary to do explicit type checking is when a different action is taken for different types, but where duck typing can't distinguish between them. For example, a function that returns a string representation of an S-expression, represented as a list of nested lists: def s_expr(obj): if isinstance(obj, list): return "(%s)" % ' '.join(map(s_expr,obj)) else: return str(obj) >>> s_expr([1, [2,3], [4,5], "foo"]) >>> '(1 (2 3) (4 5) foo)' Here duck typing doesn't help because the function should take the if branch only for lists and not other iterables (e.g. strings). George From devlai at gmail.com Thu Jun 30 17:01:47 2005 From: devlai at gmail.com (Devan L) Date: 30 Jun 2005 14:01:47 -0700 Subject: Python for everything? In-Reply-To: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: <1120165307.633163.260820@g44g2000cwa.googlegroups.com> Python for everything except things that need to be ridiculously optimized for speed. Thats what C embedded in Python and Psyco enhanced Python code is for. Oh wait, thats still all Python... From simonwittber at gmail.com Sun Jun 19 02:06:45 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 18 Jun 2005 23:06:45 -0700 Subject: pickle alternative In-Reply-To: <7x4qchwh7a.fsf@ruckus.brouhaha.com> References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> Message-ID: <1119161205.327572.136150@g44g2000cwa.googlegroups.com> > I think you should implement it as a C extension and/or write a PEP. > This has been an unfilled need in Python for a while (SF RFE 467384). I've submitted a proto PEP to python-dev. It coming up against many of the same objections to the RFE. Sw. From peter at engcorp.com Sat Jun 18 12:05:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:05:59 -0400 Subject: extreme newbie In-Reply-To: <1119106093.097295.320940@g44g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> Message-ID: cpunerd4 wrote: > even so, > crackers have a harder time getting into compiled programs rather than > intepreted languages. I know hiding the code won't stop all crackers > but it will stop some of the casual theifs won't it? It's not so much > that they could steal code, it's that they could alter it and release > it somewere else and make their own money off it. Roughly speaking, if your code is so valuable, there's very little you can do to stop if from being used in this way, except for keeping it inside a secured "network appliance" which prevents all access (though even then the box itself can be stolen, so you have to allow access only through the internet in that case). Furthermore, protecting you from someone else making money off a copy of your program is basically what licenses are for, and if you have noticed they don't protect even Microsoft (see, for example, entire governments like the Indonesian government, which has mass-pirated Microsoft software for a long time). On the other hand, while a license isn't a guarantee of much, it does make it easier to go after violators in a court and sue them for damages. And if you think your software is really worth the efforts you are envisioning to protect it, you should be prepared to go after people in court when they violate your license, not trying to prevent them from copying it in the first place (which is basically impossible, except see my first point again ;-). My main suggestion to you is this. Many people with several decades more experience than you used to feel exactly as you do (I did!), and have now, after years of developing and selling commercial software, changed their view of the whole issue drastically. Learn from others' mistakes and don't waste your time worrying about this "stealing code" thing... put your efforts into developing really useful, valuable software, and the world will beat a path to your door to give you money (see Google, for example), and while a few people might be trying to profit from your efforts without your permission, you'll either be in a good position to ignore them or sue them, as you will.... -Peter From bronger at physik.rwth-aachen.de Sat Jun 18 13:15:54 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 18 Jun 2005 19:15:54 +0200 Subject: Unbound names in __del__ References: <87mzpnmwpg.fsf@wilson.rwth-aachen.de> Message-ID: <87is0bmvqt.fsf@wilson.rwth-aachen.de> Hall?chen! Peter Hansen writes: > Torsten Bronger wrote: > >> keithley = GpibInstrument(14) >> keithley.write("*IDN?") >> print keithley.read() >> >> A keithley.close() would be a wart in my opinion; instead I want >> to hide the whole session thing from the programmer. Besides, I >> haven't yet given up the hope that the issues with __del__ can be >> tackled. > > At least one alternative comes to mind. Have the GpibInstrument > class (or its module) register an atexit() method, and have the > constructor for that class track all instances. On shutdown, the > atexit method goes through all instruments that are still open and > issues the .close() requests, or whatever you do in the __del__ > now. However, this doesn't close sessions while the program is running. If the programmer has the above code in a function which is called repeatedly, he may run into trouble. IIRC my current VISA DLL has only 256 session slots. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From drewdious at gmail.com Mon Jun 6 11:23:27 2005 From: drewdious at gmail.com (d) Date: 6 Jun 2005 08:23:27 -0700 Subject: Using IDLE for checking versions In-Reply-To: <1118069612.942511.228720@g44g2000cwa.googlegroups.com> References: <1118069612.942511.228720@g44g2000cwa.googlegroups.com> Message-ID: <1118071407.047786.8870@g44g2000cwa.googlegroups.com> nvm, i found the wxPython directory with __version__.py which told me everything i need to know. From darkpaladin79 at hotmail.com Thu Jun 9 13:22:08 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 13:22:08 -0400 Subject: cx_freeze error : LookupError: no codec search functions registered:can't find encoding In-Reply-To: <1118337079.095493.117690@g43g2000cwa.googlegroups.com> Message-ID: >From: "Thomas W" >To: python-list at python.org >Subject: cx_freeze error : LookupError: no codec search functions >registered:can't find encoding >Date: 9 Jun 2005 10:11:19 -0700 > >I get this error when I try to run a freezed exe on my ubuntu 5.04 >running Python 2.4 : > >LookupError: no codec search functions registered: can't find encoding > >I've tried to use --include-modules encodings,codecs when freezing >without luck. > >Any hints? > >Regards, >Thomas -- Did you freeze the script/program yourself? If so, do the version of Freeze you used and the version of Python match? Also, which freeze did you use, the one off the internet or the one included with Python. I may be able to help you. -Ivan _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From hancock at anansispaceworks.com Fri Jun 10 23:13:36 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Jun 2005 22:13:36 -0500 Subject: Dealing with marketing types... In-Reply-To: <1118431497.113944.261450@z14g2000cwz.googlegroups.com> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118431497.113944.261450@z14g2000cwz.googlegroups.com> Message-ID: <200506102213.36068.hancock@anansispaceworks.com> On Friday 10 June 2005 03:06 pm, Kay Schluehr wrote: > Python projects are submarines. You have to care not to go up to soon. Ooh, I like that. I'm going to file that under "useful excuses". Could come in handy! ;-D Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From fuzzyman at gmail.com Fri Jun 24 08:07:54 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jun 2005 05:07:54 -0700 Subject: Sorting part of a list In-Reply-To: <3i29tfFjgph8U1@news.dfncis.de> References: <3i29tfFjgph8U1@news.dfncis.de> Message-ID: <1119614874.396629.236570@g49g2000cwa.googlegroups.com> You can assign to a slice in place, but referencing a slice creates a copy. I think you understand it quite well :-) a = ll[2:] a.sort() ll[2:] = a To do a partial sort, in place, you'll have to subclass list - but you'll still end up doing something similar unless you delve into C or write your own sort algorithm in Python. Neither are recommended. Best Regards, Fuzzy http://wwww.voidspace.org.uk/python (back online hurrah) From jurgenex at hotmail.com Sat Jun 18 09:47:41 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sat, 18 Jun 2005 13:47:41 GMT Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Message-ID: <1CVse.19082$lb5.13764@trnddc04> Xah Lee wrote: > Python documentation, > [...] Python Reference Manual for more information. > [...] python doc wasted my time. [...] python coders. > [...] use python doc > python community [...] coding in python. [Sexual explicatives deleted] And this outburst has exactly _what_ to do with Perl (see list of NGs)? jue From arazavi at swen.uwaterloo.ca Mon Jun 13 12:18:31 2005 From: arazavi at swen.uwaterloo.ca (Ali Razavi) Date: Mon, 13 Jun 2005 12:18:31 -0400 Subject: implicit variable declaration and access Message-ID: Is there any reflective facility in python that I can use to define a variable with a name stored in another variable ? like I have : x = "myVarName" what can I do to declare a new variable with the name of the string stored in x. And how can I access that implicitly later ? From greg at cosc.canterbury.ac.nz Wed Jun 8 22:57:16 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 14:57:16 +1200 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: <7r-dnd4Q5rThYDvfRVn-pA@powergate.ca> References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> <7r-dnd4Q5rThYDvfRVn-pA@powergate.ca> Message-ID: <3gppgoFdlj6dU1@individual.net> Peter Hansen wrote: > (I don't believe there's a "wU" and conceptually it's sort > of meaningless anyway, If we ever get quantum computers, presumably "wU" will write the newlines in all possible formats simultaneously... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From mwm at idiom.com Wed Jun 22 08:44:29 2005 From: mwm at idiom.com (Mike Meyer) Date: 22 Jun 2005 05:44:29 -0700 Subject: Getting/Saving email attachments w/ poplib and email modules References: <1119394743.478968.278290@g49g2000cwa.googlegroups.com> Message-ID: <5jpsue4l3m.fsf@idiom.com> brettk at gmail.com writes: > Hello All, > > Here's what I'm trying to do: > > I need to connect to a pop3 server, download all messages, and copy all > of the attachments into a specific directory. The actual email message > is unimportant. Now, I've found plenty of examples that strip the > attachments from an email message, but most (if not all) of them take a > file parameter. My question is this: > > How can i retrieve an email message via poplib and pass it to > email.message_from_string()? A quick look at the poplib documentation shows the retr method, which gets a message by number, and returns a list: ['response', ['line', ...], octets]. So to get a string, you'd do: from poplib import POP3 from sys import exit p = POP3('example.com') # authentication, etc. msg_list = p.list() if not msg_list.startswith('+OK'): # Handle error in listings exit(1) for msg in msg_list[1]: msg_num, _ = msg.split() resp = p.retr(msg_num) if resp.startswith('+OK'): email.message_from_string('\n'.join(resp[1])) else: # Deal with error retrieving message. This is untested code, but the details of dealing with poplib should be right. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From __peter__ at web.de Tue Jun 28 09:41:27 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Jun 2005 15:41:27 +0200 Subject: Python 2.1 / 2.3: xreadlines not working with codecs.open References: Message-ID: Eric Brunel wrote: > I just found a problem in the xreadlines method/module when used with > codecs.open: the codec specified in the open does not seem to be taken > into account by xreadlines which also returns byte-strings instead of > unicode strings. > So f.xreadlines does not work, but xreadlines.xreadlines(f) does. And this > happens in Python 2.3, but also in Python 2.1, where the implementation > for f.xreadlines() calls xreadlines.xreadlines(f) (?!?). Something's > escaping me here... Reading the source didn't help. codecs.StreamReaderWriter seems to delegate everything it doesn't implement itself to the underlying file instance which is ignorant of the encoding. The culprit: def __getattr__(self, name, getattr=getattr): """ Inherit all other methods from the underlying stream. """ return getattr(self.stream, name) > At least, it does provide a workaround... Note that the xreadlines module hasn't made it into Python 2.4. Peter From claudio.grondi at freenet.de Tue Jun 14 11:58:36 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 14 Jun 2005 15:58:36 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> Message-ID: <3h868eFfedqoU1@individual.net> > > High and low tides aren't caused by the moon. > They're not??? I suppose, that the trick here is to state, that not the moon, but the earth rotation relative to the moon causes it, so putting the moon at cause is considered wrong, because its existance alone were not the cause for high and low tides in case both rotations were at synch. It is probably a much more complicated thingy where also the sun and maybe even the planets must be considered if going into the details, but this is another chapter. I experienced once a girl who pointing me to the visible straight beams from earth to sky one can see as result of sunlight coming through the clouds said: "look, along this visible beams the water from the lake wents upwards and builds the clouds". She was very convinced it's true, because she learned it at school, so I had no chance to go the details explaining, that there is no need for the visible straight light beams coming through the holes in the clouds for it. I can imagine, that many believe that the moon is orbiting each day around the earth even if they know, that earth rotates around its own axle and around the sun. Its not that important for them to ask for details, so that is the mechanism how the "lies" are born - caused by lack of the necessity or the laziness to achieve deeper understanding. Claudio "Roy Smith" schrieb im Newsbeitrag news:roy-4CB4D1.08590614062005 at reader1.panix.com... > Steven D'Aprano wrote: > > High and low tides aren't caused by the moon. > > They're not??? From richardlewis at fastmail.co.uk Tue Jun 14 05:09:30 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Tue, 14 Jun 2005 10:09:30 +0100 Subject: Resume after exception Message-ID: <1118740170.9602.236315256@webmail.messagingengine.com> Hi there, Is it possible to have an 'except' case which passes control back to the point after the exception occurred? e.g. # a function to open the file # raises FileLockedException is file contains 'locked' information def open_file(file_name): f = file(file_name, 'r') {read first line for file lock info} if first_line == "FILE LOCKED": raise FileLockedException(lock_user, lock_timestamp) {read remainder of file} return True # elsewhere in a user interface module def open_command(): try: open_file("foo.bar") except FileLockException, X: ans = tkMessageBox.askyesno(title="File Locked", message="File locked by '" + X.user + "' on " + X.time_stamp + "\nContinue anyway?") if ans == tkMessageBox.YES: # return control to the remainder of the open_file function. How? else: return False Any ideas? Cheers, Richard From skip at pobox.com Sat Jun 4 16:14:50 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 4 Jun 2005 15:14:50 -0500 Subject: Looking for help with a python-mode/pdbtrack/gdb patch Message-ID: <17058.3002.992164.256805@montanaro.dyndns.org> Can someone who uses Emacs's python-mode, pdbtrack and gdb take a look at this simple but ancient patch: http://sourceforge.net/tracker/index.php?func=detail&aid=785816&group_id=86916&atid=581351 As you'll see from the discussion, Barry had problems with it from XEmacs and was thinking of rejecting it way back when. I'd like to resolve it one way or the other, but I've never used pdb, let alone pdbtrack. Thanks, Skip From olivier.favre-simon at club-internet.fr Wed Jun 1 00:45:03 2005 From: olivier.favre-simon at club-internet.fr (Olivier Favre-Simon) Date: Wed, 01 Jun 2005 06:45:03 +0200 Subject: scripting browsers from Python References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> Message-ID: On Tue, 31 May 2005 00:52:33 -0700, Michele Simionato wrote: > I would like to know what is available for scripting browsers from > Python. > For instance, webbrowser.open let me to perform GET requests, but I > would like > to do POST requests too. I don't want to use urllib to emulate a > browser, I am > interested in checking that browser X really works as intended with my > application. Any suggestion? > > Michele Simionato ClientForm http://wwwsearch.sourceforge.net/ClientForm/ I use it for automation of POSTs of entire image directories to imagevenue.com/imagehigh.com/etc hosts. Works above urllib2. You access forms by name or indice, then you access HTML elements as a dict attribute of the form. Support file upload within POST. The only drawback I've found are: - does not support nested forms (since forms are returned in a list) - does not like ill-formed HTML (Uses HTMLParser as the underlying parser. you may pass a parser class as parameter (say SGMLParser for greater acceptance of stupid HTML code) but it's tricky because there is no well defined parser interface) Hope this helps. From ptmcg at austin.rr.com Sat Jun 25 14:22:07 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Jun 2005 11:22:07 -0700 Subject: regex question References: <3i59q5Fjm0hsU1@individual.net> Message-ID: <1119723727.510034.226120@o13g2000cwo.googlegroups.com> Here's a pyparsing version of this, that may be easier to maintain long term (although if you have your heart set on learning regexp's, they will certainly do the job). Note that in pyparsing, you don't have to spell out where the whitespace goes - pyparsing's default logic assumes that whitespace may be found between any grammar elements, and if found, it is ignored. (I believe regexp has a special magic symbol that will do the same thing.) Download pyparsing at http://pyparsing.sourceforge.net. -- Paul import pyparsing as pp testString = ' 1 2 3' integer = pp.Word(pp.nums) lineData = pp.OneOrMore( integer ) results = lineData.parseString( testString ) print results will print: ['1', '2', '3'] From mahs at telcopartners.com Wed Jun 1 17:25:17 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 01 Jun 2005 14:25:17 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> Message-ID: ironfroggy wrote: > Hoping this isn't seeming too confusing, but I need to create a > metaclass and a class using that metaclass, such that one of the bases > of the metaclass is the class created with that metaclass. I can't > figure out a way to do this, even after trying to add the class as a > base after the classes have been created. > > Is there some way I can get this to work properly? > What do you have, and how doesn't it work? I get: >>> class meta(type): pass ... >>> class cls(object): ... __metaclass__ = meta ... def __repr__(cls): ... return "I'm %s, an instance of %s" % (cls.__name__, type(cls)) ... >>> meta.__bases__ = (cls,)+meta.__bases__ >>> cls I'm cls, an instance of >>> assert type(cls) in cls.__subclasses__() >>> Of course, re-assigning meta.__bases__ comes too late to affect the construction sequence of cls. Michael From merkosh at hadiko.de Wed Jun 1 08:19:58 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Wed, 01 Jun 2005 14:19:58 +0200 Subject: AM_PATH_PYTHON - version problem Message-ID: Hi, I use the GNU autotools for packaging my python applications. My problem is that as I have both python2.3 and python2.4 installed the automake macros always detects the newest version and sets it path variables accordingly. How can I package the program for different versions of Python? (i.e. for generating binary packages) Any ideas? Thanks, Ciao Uwe From scrimp212 at yahoo.com Fri Jun 10 14:17:33 2005 From: scrimp212 at yahoo.com (scrimp) Date: 10 Jun 2005 11:17:33 -0700 Subject: Using PAMIE to upload and download files...is it possible? In-Reply-To: <1118256512.379934.292780@z14g2000cwz.googlegroups.com> References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> <1118256512.379934.292780@z14g2000cwz.googlegroups.com> Message-ID: <1118427453.108199.135860@g14g2000cwa.googlegroups.com> Thank you. I will try to come up with something I will post more if I have any other questions. Thanks From bogus@does.not.exist.com Mon Jun 20 10:35:02 2005 From: bogus@does.not.exist.com () Date: Mon, 20 Jun 2005 14:35:02 -0000 Subject: No subject Message-ID: #! rnews 4339 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Multiple instances of a python program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 83 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1118947630.385547.231370 at g43g2000cwa.googlegroups.com> <1119043472.013942.233980 at f14g2000cwb.googlegroups.com> Mime-Version: 1.0 Date: Mon, 20 Jun 2005 14:14:24 GMT Xref: news.xs4all.nl comp.lang.python:382535 "Rahul" writes: > Steven D'Aprano wrote: > > On Thu, 16 Jun 2005 11:47:10 -0700, Rahul wrote: > > > > > Hi. > > > I am part of a group in my univ where we organize a programming > > > contest. In this contest we have a UDP based server. The server > > > simulates a game and each contestant is to develop a team of virtual > > > players. Each team is composed of 75 similar bots...i.e. governed by > > > the same logic. Thus the contestant submits a single copy of the client > > > and we instantiate the same program 75 times at the same time. > > > The problem is that while executables from C source files are small and > > > we can make 75 processes but we dont know what to do with python. > > > > > > If you have a python script and you want that 75 copies of the script > > > be run simultaneously how will you do it? Is there anyway to do so > > > without running 75 copies of the python interpreter simultaneously? > > > > Have you actually tested the performance of 75 instances of Python > > running? Do you know that it will be too slow for your server, or are you > > trying to optimize before testing? > > > > I wrote a short Python script, then launched 115 instances of Python > > executing the script. There was no detectable slowdown of my system, which > > is far from a high-end PC. > > > > The details of the script aren't important. It may even be that what I > > tested is not even close to the load your server needs to deal with. But > > you may be surprised at just how easily even a low-end PC copes 75 > > instances of Python. Or perhaps not -- but the only way to tell is to try. > > Well...i havent tried (yes i hear "Premature optimization is evil evil > evil i say") but the point was that if we can find a solution consuming > less memory than we can even increase the number from 75 to lets say > 200. as for hardware we have machines with 1.7 Ghz P4 and 128 mb ram. > and i cant run them right now...since i am currently not in my > univ...but asked now since we are planning right now and wanted to see > which languages we can support. Probably c,c++,python and lisp using > clisp...and java if we can find a way to avoid running 75 jvms...this > year we supported c,c++,java and actually ran 75 jvms using 3 machines > and it was horrible so we are looking for better ways for the 2006 > contest. And we may port our server from java to python too but it > seems not many people had python installed but most had java installed. > > rahul > As others have said, start by testing. Given 1.7 MHz and 128MB, I'm guessing your performance problems are coming from swapping. Simply getting more RAM in the box would help. A quick check on process load just for the instances themselves can be done by gradually increasing max_processes (see below) until you swap. On a box with 256MB total, 150MB free, I was getting over 150 children before swap was noticeable. By watching "top" I found each child was using about 3MB, of which about 2MB is "shared" (basically, the python library). In other words, each instance was costing 1MB. Of course, your actual apps will require more RAM than this little test program. ---main program--- max_processes=10 progname="child.py" for i in xrange(max_processes): os.spawnv(os.P_NOWAIT,progname,[progname,str(i)]) ---child program--- def msg(txt): sys.stdout.write(txt) sys.stdout.flush() .... #get childnum from comline parameters .... for i in xrange(10): msg('%i ' % childnum) time.sleep(1) -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From tdw at tdw.net Mon Jun 20 17:38:57 2005 From: tdw at tdw.net (Tim Williams) Date: Mon, 20 Jun 2005 22:38:57 +0100 Subject: reading a list from a file References: <223874235.UzX6FoQtyG@teancum> Message-ID: <000601c575e0$783cc5e0$ccbefea9@twilliams> ----- Original Message ----- From: "David Bear" > I have a file that contains lists -- python lists. sadly, these are not > pickled. These are lists that were made using a simple print list > statement. > > Is there an easy way to read this file into a list again? I'm thinking I > would have to > > > I was hoping there was a pythonic way of doing this.. > a = '[1,2,3,4,5]' >>> b = eval(a) >>> b [1, 2, 3, 4, 5] >>> b[2] 3 HTH :) From roy at panix.com Thu Jun 30 08:22:07 2005 From: roy at panix.com (Roy Smith) Date: Thu, 30 Jun 2005 08:22:07 -0400 Subject: Add methods to string objects. References: <2fdabf19.0506300201.5fb56b59@posting.google.com> Message-ID: negroup at gmail.com (Negroup) wrote: > I was just asking if it is possible to "extend" string objects' > behaviour so that it becomes possible to invoke something like > 'anystring'.my_method(). You can't quite do that, but you can get close. You can define your own class which inherits from str, and then create objects of that class. For example: class myString (str): def __init__ (self, value): self.value = value def plural (self): if self.value[-1] in "sz": return self.value + "es"; else: return self.value + "s"; foo = myString("foo") bar = myString("bar") baz = myString("baz") print foo.plural(), bar.plural(), baz.plural() # my defined method print foo.capitalize() # inherited from base class From chinook.nr at tds.net Sat Jun 18 02:17:32 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 18 Jun 2005 02:17:32 -0400 Subject: OO approach to decision sequence? Message-ID: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> OO approach to decision sequence? --------------------------------- In a recent thread (Cause for using objects?), Chris Smith replied with (in part): > If your table of photo data has several types of photos, and you find > yourself saying > > if is_mugshot: > #something > elif is_freehand: > #something > else: > #something > > then OOP will help organize your code. This struck a chord because I'm trying to refactor a top-down approach to an OO approach. The reason I am doing such is to try and get my mind wrapped around OO design, not because the particular module will benefit from an OO approach (it's a simple top-down recursive tree utility). In fact it's probably ill suited for OO and that is why I chose it. I've used an OO approach where I built up record (instance) content in a variable record file, but here I'm trying to come at it from the opposite direction as variable record mapping (deconstructing) would be to such. Anyway, a tree node can be any of seven types where: if node_type_1: # recurse elif node_type_2: # terminus - do something elif node_type_3: # terminus - do something else ... else: # terminus - catch all, do yet something else return #to parent So, where is the magic :~) Seriously, how might OO help me organize this type of problem (alleviate the conventional lengthy if structure)? I've looked at the cookbook, class interface techniques, factory functions and metaclasses till my head is swimming. Am I missing a bolt in the machinery somewhere, or simply trying to find magic that doesn't exist for a straightforward decision sequence? Thank you, Lee C From http Mon Jun 20 12:59:26 2005 From: http (Paul Rubin) Date: 20 Jun 2005 09:59:26 -0700 Subject: Python choice of database References: Message-ID: <7xll55ynf5.fsf@ruckus.brouhaha.com> "Philippe C. Martin" writes: > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K You don't mention whether multiple running programs need to use it concurrently. That's usually done with client/server db's but it can be done standalone. From rupole at hotmail.com Mon Jun 6 22:57:17 2005 From: rupole at hotmail.com (Roger Upole) Date: Mon, 6 Jun 2005 22:57:17 -0400 Subject: Using PAMIE to upload and download files...is it possible? References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> Message-ID: <42a50df7$1_2@spool9-west.superfeed.net> As I understand it, newer versions of IE have uploading and downloading via script disabled as a security measure. You might be able to do some low-level API calls to deal with the download window. Roger "scrimp" wrote in message news:1118077246.115120.25220 at g44g2000cwa.googlegroups.com... > Ive been using PAMIE 1.4 to try to automate web page processes. The one > thing I cannot do with it is upload files and download files. > > With uploading files, the file input box does not allow PAMIE to enter > in a path to a file. > > With downloading files, I can click on the link to download the file, > but thats where I get stuck at. It brings up that download window and > then it brings up the where to save window. > > Theres no errors that I encounter when I get stuck at these spots it > justs sits there not knowing what to do. > > If anyone has had success in both uploading or downloading or even some > insight, I would greatly appreciate your help. Thanks! > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From fairwinds at eastlink.ca Sun Jun 5 13:57:56 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Sun, 05 Jun 2005 14:57:56 -0300 Subject: Iterate through a list calling functions In-Reply-To: <42a33011$1_1@newspeer2.tds.net> Message-ID: <58B0F1D2-D5EB-11D9-BFBC-000A27B3B070@eastlink.ca> Hi Kent. Thank you for your reply. I gave this a go but get the following traceback: ... result = validator(name, value) TypeError: 'str' object is not callable Have put validators in list and iterate over it as in following: validator_list = [isContainedIn,isDate,isDecimal,isEmail,isEmpty,isInteger... more validators....] results={} for validator in validators_list: result = validator(name, value) if type (result) in StringTypes: # do some stuff... return results Regards, David On Sunday, June 5, 2005, at 02:03 PM, Kent Johnson wrote: > David Pratt wrote: >> Hi. I am creating methods for form validation. Each validator has its >> own method and there quite a number of these. For each field, I want >> to >> evaluate errors using one or more validators so I want to execute the >> appropriate validator methods from those available. I am iterating >> over >> each validator using validateField method to gather my results. It >> works >> but it ugly and inefficient. Can someone advise whether there is a >> better way of doing this. I realize that the validator variable in my >> iteration is only a string so question is how can I make the validator >> string reference a function so I may be able to shorten validateField >> to >> something similar to this (instead of my long list of ifs which I am >> not >> very happy with): >> >> for validator in validators_list: >> result = validator(name, value) >> if type (result) in StringTypes: >> results[name] = result > > Actually you can do exactly that by putting references to the > validator functions in your list instead of (string) name. For example > if you have > validators = [ 'isDecimal', 'isFoo', 'isBar' ] > > just change it to > validators = [ isDecimal, isFoo, isBar ] > > and your loop above will work. > > Python makes data-driven programming easy :-) > Kent > >> >> Many thanks >> David >> >> My current situation below: >> >> # A large list of validators >> def isDecimal(name, value): >> """ Test whether numeric value is a decimal """ >> result = validateRegex(name, >> value, >> r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', >> errmsg='is not a decimal number.', >> ignore=None) >> return result >> >> def isZipCode(name, value): >> """ Tests if field value is a US Zip Code """ >> result = validateRegex(name, >> value, >> r'^(\d{5}|\d{9})$', >> errmsg='is not a valid zip code.', >> ignore=None) >> return result >> >> ... more validators >> >> # Iterating over validators to gather field errors >> def validateField(name, value, validators_list, range=None, >> valid_values=None): >> """ Validates field input """ >> results={} >> for validator in validators_list: >> if validator == 'isContainedIn': >> result = isContainedIn(name, value) >> if type (result) in StringTypes: >> more... >> if validator == 'isDate': >> result = isDate(name, value) >> if type (result) in StringTypes: >> more... >> if validator == 'isDecimal': >> result = isDecimal(name, value) >> if type (result) in StringTypes: >> more... >> >> more validators ... >> > -- > http://mail.python.org/mailman/listinfo/python-list > From chrisconnett at gmail.com Mon Jun 27 18:47:15 2005 From: chrisconnett at gmail.com (Chris Connett) Date: 27 Jun 2005 15:47:15 -0700 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> Message-ID: <1119912435.355603.129150@g49g2000cwa.googlegroups.com> pyparsing is the far and away the easiest general purpose parser out there that I've encountered; BNF-style grammar parsing is a *pleasure* with pyparsing. And it all comes in a single pure python module to boot. From lode_leroy at hotmail.com Fri Jun 24 09:52:17 2005 From: lode_leroy at hotmail.com (lode leroy) Date: Fri, 24 Jun 2005 15:52:17 +0200 Subject: autoconfigure vss python question Message-ID: Hi folks, I'm trying to build a python module using MINGW on MSYS the "configure" script is determining where python is installed as follows: python.exe -c 'import sys; print sys.prefix' c:\Python24 which is good on native windows (i.e. when invoked from CMD.EXE) Is there a way to configure something in python or in the environment so that when invoked from MSYS, it would behave as follows: (note the '/' vss '\') python.exe -c 'import sys; print sys.prefix' c:/Python24 thanks. From szport at fromru.com Wed Jun 29 11:22:00 2005 From: szport at fromru.com (szport at fromru.com) Date: 29 Jun 2005 08:22:00 -0700 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: <1120058520.067711.232740@o13g2000cwo.googlegroups.com> Yes, I mean this thing. From grante at visi.com Thu Jun 23 09:36:35 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Jun 2005 13:36:35 -0000 Subject: Allowing only one instance of a script? References: Message-ID: <11blen3dogr9t96@corp.supernews.com> On 2005-06-23, Tim Golden wrote: > [Ali] >| >| I have a script which I double-click to run. If i double-click it >| again, it will launch another instance of the script. >| >| Is there a way to allow only one instance of a script, so that if >| another instance of the script is launched, it will just >| return with an >| error. > > If you're on Windows, have a look at this recent thread: > > http://groups-beta.google.com/group/comp.lang.python/msg/2a4fadfd3d6e3d4b?hl=en If you're on Unix/Linux, the usual way to do this is with a lockfile. -- Grant Edwards grante Yow! I'd like MY data-base at JULIENNED and stir-fried! visi.com From cam.ac.uk at mh391.invalid Mon Jun 20 17:56:31 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 20 Jun 2005 22:56:31 +0100 Subject: Using print with format to stdout generates unwanted space In-Reply-To: <3ho63fFi1o93U1@individual.net> References: <3hmt4rFhnn89U1@individual.net> <42b6bc99@news.highway1.com.au> <3ho63fFi1o93U1@individual.net> Message-ID: Paul Watson wrote: > While printf() does tightly control formatting in C, it does not in > Python. There is no printf() in Python. You should not think of print as being a Python version of printf. -- Michael Hoffman From Andreas.Ames at comergo.com Wed Jun 1 08:49:39 2005 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Wed, 1 Jun 2005 14:49:39 +0200 Subject: Another source of time for the logging package? Message-ID: Skip Montanaro wrote: > Before I get out my scalpel, has anyone found a non-invasive way to > do this (or already done the surgery and would be willing to share > it)? While I'm not sure you would call the following 'non-invasive' I've used it in a similar situation: class MyLogRecord(logging.LogRecord): def __init__(*args, **kwargs): logging.LogRecord.__init__(self, *args, **kwargs) self.created = time_warp() # get the time you need class MyLogger(logging.Logger): def makeRecord(self, *args, **kwargs): return MyLogRecord(*args, **kwargs) Then I call logging.setLoggerClass(MyLogger) before the relevant loggers are created. HTH, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | andreas . ames AT comergo . com From peter at engcorp.com Thu Jun 30 13:09:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 30 Jun 2005 13:09:02 -0400 Subject: Programmers Contest: Fit pictures on a page In-Reply-To: <42c41ef2@usenet01.boi.hp.com> References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> <42c41ef2@usenet01.boi.hp.com> Message-ID: Don wrote: > I was thinking maybe you could use a genetic algorithm, where the fitness > function would caluclate the amount of waste. I'm not very familar with how > to implement this sort of thing, though. This problem is well suited to the abilities of genetic algorithms, and this would probably be an excellent way to learn more about them, even if you don't get the best solution. -Peter From degoor_python at dir.bg Fri Jun 10 12:53:39 2005 From: degoor_python at dir.bg (degoor_python at dir.bg) Date: Fri, 10 Jun 2005 19:53:39 +0300 Subject: How to overcome automatic cyrillic-to-/hex convert Message-ID: Hi friends, I am really sorry to bother you with such a simple stupid question but today it's my second day spent in searching manuals, mail-archives (I downloaded over 100MB from "python-list"), etc., and I could not find anything that can solve the matter. I am from Bulgaria and I use Python (+wxPython+Boa Constructor) as a front-end to database processing with Firebird. I use Python 2.4.1 over Windows 98 SE. My keyboard is set as default Bulgarian keyboard (keybg) so I can write in Bulgarian using win32 application as well in MS DOS prompt. That should correspond to 'cp1251' (win32) and 'cp855' (DOS console) encodings. But when I enter some Bulgarian (actually cyrillic) text as a string, it seems that Python automatically converts it to '\x00..\x00 ' and once converted that way I can't get it back into its original look. The only way to get it right is using print : >>> a = '????' # 'Mam' in Bulgarian >>> print a '????' but >>> a '\xcc\xe0\xec\xe0' It is not such a great problem that the string enters or gets out of the database in that look as long as the user doesn't see it. But when it comes to data visualization I can't expect the user to know what '\xcc\xe0\xec\xe0' mean, neither can I use (at least as much as I know) 'print' for that job. To visualize data in the base I use table views created with wxGrid. In the grid instead of '????' I am getting '\xcc\xe0\xec\xe0'. To set the value of a particular cell in the grid I use wxGrid::SetCellValue : self.grid1.SetCellValue(row, column, string) In one of O'Reilly's Python books (Learning Python, chapter 8.3.2)there is a hint that it is possible to redirect the standard output to a user-defined object but it is not quite clear how that can be achived and if that is applicable in my case at all. Your help is of great need and would be truely appreciated! Thank you very much! degoor From nospam at nandj.freeserve.co.uk Tue Jun 21 17:17:05 2005 From: nospam at nandj.freeserve.co.uk (Nick Atty) Date: Tue, 21 Jun 2005 22:17:05 +0100 Subject: sudoku dictionary attack References: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> <1119287197.993599.160240@g47g2000cwa.googlegroups.com> Message-ID: On Mon, 20 Jun 2005 23:30:27 +0200, Oliver Albrecht <55028344773 at t-online.de> wrote: >Has some one an sodoku-task-generator? >Here another solutions-ways: >http://www.python-forum.de/viewtopic.php?t=3378 It's presumably easy to turn a solver into a generator. Start with a random grid, and remove squares at random, and then solve it. Once solving it reaches a certain level of difficulty, then there's your problem. -- On-line canal route planner: http://www.canalplan.org.uk (Waterways World site of the month, April 2001) From dalke at dalkescientific.com Sun Jun 12 12:02:25 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 12 Jun 2005 16:02:25 GMT Subject: ElementTree Namespace Prefixes References: Message-ID: On Sun, 12 Jun 2005 15:06:18 +0000, Chris Spencer wrote: > Does anyone know how to make ElementTree preserve namespace prefixes in > parsed xml files? See the recent c.l.python thread titled "ElemenTree and namespaces" and started "May 16 2:03pm". One archive is at http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/31b2e9f4a8f7338c/363f46513fb8de04?&rnum=3&hl=en Andrew dalke at dalkescientific.com From ken at perfect-image.com Wed Jun 8 11:03:27 2005 From: ken at perfect-image.com (Ken Godee) Date: Wed, 08 Jun 2005 08:03:27 -0700 Subject: Garbage collection with QT In-Reply-To: <42a683b0$1@news.vo.lu> References: <42a683b0$1@news.vo.lu> Message-ID: <42A708BF.9010804@perfect-image.com> > Is there a way, to find out all references to the QMainWindow or its > hosted QTable, for having a mechanism to destroy them? > Yes, of coarse, the docs are your friend :) QObject::children() QObject::removeChild() QObject::parent() To find all the children for an instance you can create a loop. An example of a dialog window function that cleans it self up .... ================================================ def xdialog(self,vparent,info): vlogin = dialogwindow(parent=vparent,modal=1) while 1: vlogin.exec_loop() if vlogin.result() == 0: vparent.removeChild(vlogin) del vlogin break ================================================ From dirgesh at gmail.com Thu Jun 9 01:06:40 2005 From: dirgesh at gmail.com (GujuBoy) Date: 8 Jun 2005 22:06:40 -0700 Subject: appending an array to a list in BOOST / Python Message-ID: <1118293600.959877.178800@g14g2000cwa.googlegroups.com> i have an array in C++ (array[100]) and i want to append that to the list can i just say list1.append(array) without actually traversing through the entire array and appending... how can i do this in BOOST Python please help From chinook.nr at tds.net Tue Jun 28 13:19:42 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 13:19:42 -0400 Subject: OO refactoring trial ?? References: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> Message-ID: <0001HW.BEE6FEEE000C427BF0407550@news.gmane.org> On Tue, 28 Jun 2005 10:22:59 -0400, Paul McGuire wrote (in article <1119968579.049502.68280 at g43g2000cwa.googlegroups.com>): > Lee, > > Interesting idea, but I think the technique of "inherit from MF to > automatically add class to the test chain" is a gimmick that wont > scale. > > Here are some things to consider: > > - I'm not keen on the coupling of forcing your A,B,etc. classes to > inherit from MF. Especially in a duck-typing language like Python, it > adds no value, the subclasses receive no default behavior from their > superclass, and I'm not keen on using the inheritance hierarchy to > register test classes. What is the order of classes returned from > __subclasses__()? Will you always want this order? Will you always > want all subclasses? If this is part of a library that others will > use, you may not be able to anticipate what subclasses someone else may > stick on to your MF class. Even though this is an exercise, it is a learning exercise and your points are taken as pertinent considerations in "real-world" adaptation. So basically I'm coming from a if:elif:...else: test sequence where the order of the tests is critical (could be multiple hits and the first should be taken). My first trial was just to move the "if" sequence to a factory method. My second trial was to initially create an ordered list of classes to be tested as in: >>> class A(object): ... def foo(self): ... print "I'm A.foo" ... >>> class B(object): ... def foo(self): ... print "I'm B.foo" ... >>> co = [A(), B()] >>> co[1].foo() I'm B.foo >>> My third trial is what you are responding to. So in the "real-world" I could only suggest how someone else might add a test, but just as in the top-down "if" sequence I could impose no discipline. Even adding a weighting/priority to test cases (and going through all) is a halfway measure (though possibly a more explicit one). I think that the consideration of how a test case might be added in the future is very important - having dug my way through many other programs. BTW: Is duck-typing a variation on duct-taping? > > - The list of items should be dynamic in the calling code, not built > statically by your class structure. There's no way to anticipate what > various sequences you will want to evaluate. I was also playing with another exercise involving dynamic test cases where I thought the ordered list (second trial) would be a potential approach? > > - Let's call the MF class "MultiEvaluator". There are several ways to > evaluate among several alternatives: > . short-circuit, take first match what I was shooting for in this exercise > . best-fit, evaluate all and take best score (assuming the testit > routines return a double or int, as opposed to a bool) like my weighted/priority thought? > > For short-circuiting, say you have a case that will match A, you want > to avoid any processing related to B,C,etc. as possible at test/do > runtime. You *might* be able to do extra work at list construction > time. Consider these two alternative designs: > > class MultiEvaluator(object): > def __init__(self, *classes): > self.testClasses = classes[:] > > def findit(self, *args): > for C in self.testClasses: > testobj = C() > if testobj.testit(args[0]): > testobj.doit() > > MultiEvaluator(A,B).findit("relates to A") my only drawback on such would be ME(A,B,...Z).findit(test_data) Explicit but cumbersome maybe, though no where near as cumbersome as a lengthy "if" sequence. > > vs. > > class MultiEvaluator(object): > def __init__(self, *classes): > self.testClasses = [ C() for C in classes ] > > def findit(self, *args): > for testobj in self.testClasses: > if testobj.testit(args[0]): > testobj.doit() > > MultiEvaluator(A,B).findit("relates to B") > > In the first case, no B class is ever constructed, so if test object > construction is expensive, you might go this route. In the second, A() > and B() are built ahead of time, so the run-time processing is the > fastest - you might choose this if the construction time can be done up > front. The second option may cause problems for multi-threadedness or > re-entrancy with a shared MultiEvaluator, though. > > This style of constructing the MultiEvaluator also makes more explicit > (which I hear is better than implicit) what classes you are testing > when creating your MultiEvaluator. > > - To make your testit() and doit() code more flexible and more > powerful, I'd pass (*args) to each, as in: The testit() methods do in the full-fledged exercise. The doit() methods return code objects (but I'm rethinking that). > > class MultiEvaluator(object): > def __init__(self, *classes): > self.testClasses = classes[:] > > def findit(self, *args): > for C in self.testClasses: > testobj = C() > if testobj.testit(args): > testobj.doit(args) As in my ordered list approach (and what I thought my "cleverly" generated list would also do before giving it more thought), the idea in this exercise is to have one list (created once) that all levels of recursion would use. Your forcing me to use my head :~) > > - In the interests of flogging OO-ness, you could make MultiEvaluator > into a function object, by changing "findit" to "__call__". Then your > invocation of it would change from: > > getObj = MultiEvaluator(A,B) > getObj.findit("relates to B") > > to: > > getObj = MultiEvaluator(A,B) > getObj("relates to B") > > Although some might claim this is *less* explicit. The purpose of this > is that you could then pass getObj to functional routines like map > (although you could also pass getObj.findit). > Good point, but my objective is an OO learning exercise. My mind isn't as flexible as it was back in the 60s :~) so it takes more effort to get a handle on something new (to me). > > > Those are my comments off the top of my head. Let us know what you > come up with. > > -- Paul > > Thank you very much for taking the time to consider and respond, Lee C From 55028344773 at t-online.de Mon Jun 20 17:30:27 2005 From: 55028344773 at t-online.de (Oliver Albrecht) Date: Mon, 20 Jun 2005 23:30:27 +0200 Subject: sudoku dictionary attack In-Reply-To: <1119287197.993599.160240@g47g2000cwa.googlegroups.com> References: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> <1119287197.993599.160240@g47g2000cwa.googlegroups.com> Message-ID: Has some one an sodoku-task-generator? Here another solutions-ways: http://www.python-forum.de/viewtopic.php?t=3378 -- input From chinook.nr at tds.net Sat Jun 25 16:35:16 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 25 Jun 2005 16:35:16 -0400 Subject: Excellent Site for Developers References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: <0001HW.BEE338440003060FF0407550@news.gmane.org> On Sat, 25 Jun 2005 15:36:06 -0400, Philippe C. Martin wrote (in article ): > Hi, > > Not being from anglo-saxon heritage, I keep wondering why spammers always > (or very often) get called 'trolls' ? > > I mean fantasy fiction has brought us many hugly beasts (goblin, warlock, > orc, dark elf ....) > > The trolls, as I recall, grow back their limns once those have been cut by > the nice folks. > > Is that the reason ? > > Regards, > > Philippe > > > > > Do Re Mi chel La Si Do wrote: > >> >> rather... super troll > > Actually there are many understandings, but many stem from a "something ugly" sense as in the old Norse legend. In the context of the internet, the meaning is usually: > To "troll" means to allure, to fish, to entice or to bait. An internet troll > is someone who fishes for people's confidence and, once found, exploits it. > Internet deception relies on exploiting trust and building confidence, and > the rewards can be financial or psychological. As you can see, though, the context could be any communication, from anyone from the common criminal to the established political, religious, or business leader :~) Lee C "God save us from those that would save us." -- my grandmother c1945 From nephish at xit.net Sat Jun 11 15:03:49 2005 From: nephish at xit.net (nephish at xit.net) Date: 11 Jun 2005 12:03:49 -0700 Subject: cgi script runs under Opera, but not firefox In-Reply-To: <6d8ma1lvfer5itr6ukomg095uprnp30ujd@4ax.com> References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> <1118501642.065924.83560@z14g2000cwz.googlegroups.com> <1118505371.230328.231880@o13g2000cwo.googlegroups.com> <6d8ma1lvfer5itr6ukomg095uprnp30ujd@4ax.com> Message-ID: <1118516629.651991.134730@g47g2000cwa.googlegroups.com> fixed, thanks for all of your help. i am pouring over python texts and the problem is html... duh.... looking for a more efficient way to jerk all of the hair outta my head. thanks a whole lot. your awesome From dongar37 at gmail.com Sun Jun 5 16:41:17 2005 From: dongar37 at gmail.com (Don Garrett) Date: 5 Jun 2005 13:41:17 -0700 Subject: Killing threads during development. Message-ID: <1118004077.454383.246450@g43g2000cwa.googlegroups.com> I've been developing with external multi-threaded libraries recently. I find it difficult to use the Python prompt to experiment with these libraries because there isn't any way to just shutdown all threads and try things again. If I try to exit the prompt with background threads running, then Python hangs and I have to kill the process to exit. Ctrl C won't do it. Is there some way to brutally kill all background threads? Just for development purposes? Note: This isn't an insurmountable problem. If I write test scripts and run them from the command line I can still kill them easily. I just find it frustrating not be to able to explore interactively while working with a new library. From grante at visi.com Thu Jun 30 18:45:39 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 30 Jun 2005 22:45:39 -0000 Subject: When someone from Britain speaks, Americans hear a "Britishaccent"... References: Message-ID: <11c8tgjju7ljvd4@corp.supernews.com> On 2005-06-30, Delaney, Timothy (Tim) wrote: > Tom Anderson wrote: > >> How about carrier? > > Ends in an "a" (Australian ;) Right, but due to some wierd property requiring conservation of consonants, when speaking Strine you've got to take the r's removed from words like "carrier" and "order", and add them to the ends of other words like Amanda. -- Grant Edwards grante Yow! There's a SALE on at STRETCH SOCKS down at the visi.com "7-11"!! From greg_miller at nexpress.com Wed Jun 29 08:49:06 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 29 Jun 2005 05:49:06 -0700 Subject: COM problem .py versus .exe In-Reply-To: References: Message-ID: <1120049346.591931.166610@g47g2000cwa.googlegroups.com> line 157 is in fact where the traceback says the failure is: File "autoStart.py", line 241, in test File "wmib.pyc", line 157, in ? File "win32com\client\__init__.pyc", line 73, in GetObject File "win32com\client\__init__.pyc", line 88, in Moniker com_error: (-2147221020, 'Invalid syntax', None, None ) From philippe at philippecmartin.com Sat Jun 11 19:17:18 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 11 Jun 2005 23:17:18 GMT Subject: What is different with Python ? References: Message-ID: <2iKqe.2580$I14.375@newssvr12.news.prodigy.com> > PS: http://jove.prohosting.com/~zahlman/cpp.html So you're saying they only use perl in Taiwan ;-) Tom Anderson wrote: > On Sat, 11 Jun 2005, Philippe C. Martin wrote: > >> Yet for the first time I get (most) of my questions answered by a >> language I did not know 1 year ago. > > Amazing, isn't it? Rest assured that you're not alone in feeling this way. > I don't know quite why, but python is just makes writing programs > immensely easier than any other language i've ever used; i think it's the > very minimal amount of boilerplate it requires, the clean and powerful set > of builtin types and functions and, for me, the higher-order functions. I > can do in a few lines of python what would have taken me pages and pages > of java. > > tom > > PS: http://jove.prohosting.com/~zahlman/cpp.html > From ralph at inputplus.co.uk Thu Jun 16 12:09:57 2005 From: ralph at inputplus.co.uk (Ralph Corderoy) Date: Thu, 16 Jun 2005 17:09:57 +0100 Subject: 1980's Home Computer-style Package. In-Reply-To: <17073.38505.710868.660784@montanaro.dyndns.org> Message-ID: <200506161609.j5GG9vk01340@blake.inputplus.co.uk> Hi Skip, > > Some years ago I saw a Python package or program that gave a > > programming environment similar to the BASICs of 1980's home > > computers. You got a cursor-addressable screen, e.g. PRINT TAB(10, > > 20) "Hello", and some simple pixel-setting functions, e.g. RECTANGLE > > FILL 0, 10, 20, 30. It probably used SDL to provide the `screen'. > > It's intended use was to widen the range interesting things a child > > learning Python could do. > > Wild-ass guess, but you might try googling for "turtle python". OK, I've done that but it didn't help; it wasn't tied in with Turtle graphics, with which I'm familiar. BTW, in case my post didn't make it clear, I gave examples of BASIC; I'm not suggesting the Python module accepted scripts in that format, just that it provided the functionality. Thanks anyway, Ralph. From tjreedy at udel.edu Mon Jun 13 13:23:05 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Jun 2005 13:23:05 -0400 Subject: Controlling assignation References: <73cd19a37027b3d16c44d04ea560ee32@upf.edu> Message-ID: "harold fellermann" wrote in message news:73cd19a37027b3d16c44d04ea560ee32 at upf.edu... >if you write > >>> a=A() >an instance of class A is created and bound to the local identifier 'a'. I think it perhaps better to think of the label 'a' being bound to the object rather than vice versa. For one, a label can only be bound (stuck to, like a stick note) to one object at a time while one object can have many labels (and other references) stuck to it. > If you later write > >>> a=5 > the object 5 is reassigned to the same identifier, Or one could say that the label 'a' is removed from the A() object and reassigned to the 5 object. Since the 5 object may have numerous other connections, and since those connections are unaffected by the new connection to 'a', whereas the previous assignment of 'a' is broken, I think it better to say that 'a' is being reassigned, not 5. > deleting whatever value was stored there before. In memory-oriented languages, such as C, names refer to chunks of memory where values are stored and deleted. Assigning a new value to a variable puts a new value in that chunk of memory, necessarily overwriting the old. In object-oriented Python, objects have values and possibly multiple associations with names and slots. If, but only if, 'a' was the last association of its last assigned-to object, then that object is eligible for deletion. > In other words: identifiers don't have types. This and the following I agree with. Terry J. Reedy From listserver at tdw.net Thu Jun 16 05:40:45 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 16 Jun 2005 10:40:45 +0100 Subject: help with sending mail in Program References: Message-ID: <009e01c57257$786cbac0$ccbefea9@twilliams> ----- Original Message ----- From: "Ivan Shevanski" > > if __name__ == '__main__': > body = 'x is',x,'y is',y,'.Lets hope that works!' > subject = 'Neo' > sendToMe(subject, body) > > I really have no idea whats going on. . .help? > > -Ivan Ivan, you need to pass the body as a string, you have constructed it as a tuple. >>> x = 'X' >>> y = 'Y' >>> body = 'x is',x,'y is',y,'.Lets hope that works!' >>> body ('x is', 'X', 'y is', 'Y', '.Lets hope that works!') >>> type(body) But you can't do the following >>> str(body) "('x is', 'X', 'y is', 'Y', '.Lets hope that works!')" So you have the option of things like this >>> 'x is ' + x +' y is ' + y + ' .Lets hope that works!' x is X y is Y .Lets hope that works! but that gets messy the large the the amount of items you have, these are better. >>> ' '.join(body) # there is a space between the ' ' 'x is X y is Y .Lets hope that works!' eg >>> body = ' '.join('x is',x,'y is',y,'.Lets hope that works!') or >>> "x is %s y is %s .Lets hope that works!" % (x, y) 'x is X y is Y .Lets hope that works!' eg >>> body = "x is %s y is %s .Lets hope that works!" % (x, y) You can use '\n' or '\r\n' to insert a line feed (new-line) anywhere in the body text in any of the examples above. HTH :) From bvande at po-box.mcgill.ca Sat Jun 25 15:20:19 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 25 Jun 2005 15:20:19 -0400 Subject: Excellent Site for Developers In-Reply-To: References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: <42BDAE73.1010003@po-box.mcgill.ca> Brian said unto the world upon 25/06/2005 10:50: > Do Re Mi chel La Si Do wrote: > >> rather... super troll > > > 100% Agreed. > > Can anyone say, "This looks like spam... Feels like spam... and is about > as useful here in the Python forums as spam -- therfore my conclusion is > that his VB message probably IS SPAM." :-D > > Brian > --- What would settle it is finding out if it floats :-) Brian vdB From marco.colombo at gmail.com Tue Jun 28 11:22:20 2005 From: marco.colombo at gmail.com (Marco) Date: 28 Jun 2005 08:22:20 -0700 Subject: noob question References: Message-ID: Steven D'Aprano wrote in message news:... > Can anyone think of some good, easy to understand examples of where > Python's name/object model differs from the variable/value model? a = b = [ 1 ] a and b are _not_ two variables, each with [ 1 ] as value, but just two names for the same object (a list). In other variable-based languages, the above is equivalent to: a = [ 1 ] b = [ 1 ] in Python it is not. .TM. From ajikoe at gmail.com Fri Jun 24 15:15:00 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 24 Jun 2005 12:15:00 -0700 Subject: what list comprehension can't In-Reply-To: <20050624210415.48f5dace.no.spam@box> References: <1119638714.090433.130520@z14g2000cwz.googlegroups.com> <20050624210415.48f5dace.no.spam@box> Message-ID: <1119640500.320918.11750@g47g2000cwa.googlegroups.com> Thank you pujo From hancock at anansispaceworks.com Thu Jun 23 14:31:44 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 23 Jun 2005 13:31:44 -0500 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: <1119474582.891149.32740@g14g2000cwa.googlegroups.com> References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: <200506231331.44796.hancock@anansispaceworks.com> On Wednesday 22 June 2005 04:09 pm, Eloff wrote: > Hi Paul, > >You're doing what every serious database implementation needs to do ... > >Are you sure you don't want to just use an RDBMS? > > It was considered, but we decided that abstracting the data into tables > to be manipulated with SQL queries is substantially more complex for > the programmer and way too expensive to the system since the average > action would require 20-100 queries. I realize you've probably already made a decision on this, but this sounds like a classic argument for using an *object DBMS*, such as ZODB: It certainly does support transactions, and "abstracting the data into tables" is a non-issue as ZODB stores Python objects more or less directly (you only have to worry about ensuring that objects are of "persistent" types -- meaning either immutable, or providing persistence support explicitly). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From wookiz at hotmail.com Fri Jun 10 07:52:12 2005 From: wookiz at hotmail.com (wooks) Date: 10 Jun 2005 04:52:12 -0700 Subject: Python Developers Handbook In-Reply-To: <1118399995.306455.161220@o13g2000cwo.googlegroups.com> References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <1118399995.306455.161220@o13g2000cwo.googlegroups.com> Message-ID: <1118404332.349662.82650@g44g2000cwa.googlegroups.com> beliavsky at aol.com wrote: > wooks wrote: > > I thought that posting a link that contained the word ebay and a > > subject title of Python Developers Handbook conveyed all the relevant > > information and didn't want to patronise the NG. > > > > I have had 110 hits on the item but seem to have upset 3 people. > > This statement shows a misunderstanding of Usenet. Maybe the majority > of comp.lang.python readers agree with Terry Reedy but did not want to > clog the newsgroup with ditto messages. Your understanding of Usenet is that a post has to "appeal" (for the want of a better word) to the majority of the NG readership. Look over a hundred people took a look (and the hits are steadily going up whether despite or because of this thread). I am not going to posit either way as to whether that amounts to vindication but it does suggsest that I have not comitted the heinous crime against netiquette that some people are making out. From fredrik at pythonware.com Tue Jun 14 02:06:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 08:06:06 +0200 Subject: Tiff Image Reader/writer References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com><1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> Message-ID: "PyPK" wrote: > nothing fancy. I just want to be able to read a tiff image, get pixel > values, write back to a tiff file. so why doesn't PIL or ImageMagick work for you? here's a minimal PIL version: from PIL import Image im = Image.open("myfile.tiff") value = im.getpixel((12, 34)) im.save("other.tiff") From sjmachin at lexicon.net Sat Jun 18 03:52:57 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Jun 2005 17:52:57 +1000 Subject: OO approach to decision sequence? In-Reply-To: <1119079963.742936.56500@g49g2000cwa.googlegroups.com> References: <1119079963.742936.56500@g49g2000cwa.googlegroups.com> Message-ID: <42B3D2D9.20802@lexicon.net> Jordan Rastrick wrote: > I've coded some simple recursive tree data structures using OO before > (unfortunately not in Python though). It's not nessecarily an > ill-suited approach to the task, although it depends on the specific > details of what you're doing. What's the the piece of code from which > your if...elif fragment is taken actually supposed to do? > > Without knowing more about your problem, I think the most obvious OO > approach would be to write a seperate (simple) class for each of > node_type_1, node_type_2, etc. Make sure each one provides the same > interface, i.e. defines the same set of methods. Then put the different > decision branches as implementations of a certain method in each class. > > class Node_Type_1(object): > def recurse(self): > # do stuff here > etc etc and perhaps if you found by the time you got to Node_Type_2 that its opensesame() method was identical to the opensesame() method for Node_Type_1, you might decide that having separate simple classes could be improved on by having a Node class, which you would subclass for each Node_Type_n ... From davecook at nowhere.net Sun Jun 19 12:29:28 2005 From: davecook at nowhere.net (Dave Cook) Date: Sun, 19 Jun 2005 16:29:28 GMT Subject: pysqlite - Checking the existance of a table References: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> Message-ID: On 2005-06-17, rh0dium wrote: > I am starting to play with pysqlite, and would like to know if there is > a function to determine if a table exists or not. sqlite_master has already been mentioned, so I'll point out some useful pragmas (under "Pragmas to query the database schema"): http://sqlite.org/pragma.html Dave Cook From sjmachin at lexicon.net Fri Jun 17 17:49:27 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Jun 2005 07:49:27 +1000 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <1119015959.5960.5.camel@athop1.ath.vt.edu> References: <42ae3411@news.eftel.com> <1118928457.18452.13.camel@athop1.ath.vt.edu> <42B23670.70103@lexicon.net> <1119012614.4268.18.camel@athop1.ath.vt.edu> <6sudnWgJw6l7UC_fRVn-iQ@powergate.ca> <1119015959.5960.5.camel@athop1.ath.vt.edu> Message-ID: <42B34567.20605@lexicon.net> rbt wrote: > On Fri, 2005-06-17 at 09:18 -0400, Peter Hansen wrote: > >>rbt wrote: >> >>>The script is too long to post in its entirety. In short, I open the >>>files, do a binary read (in 1MB chunks for ease of memory usage) on them *ONE* MB? What are the higher-ups constraining you to run this on? My reference points: (1) An off-the-shelf office desktop PC from HP/Dell/whoever with 512MB of memory is standard fare. Motherboards with 4 memory slots (supporting up to 4GB) are common. (2) Reading files in 1MB chunks seemed appropriate when I was running an 8Mb 486 using Win 3.11. Are you able to run your script on the network server itself? And what is the server setup? Windows/Novell/Samba/??? What version of Python are you running? Have you considered mmap? >>>before placing that read into a variable and that in turn into a list >>>that I then apply the following re to In the following code, which is "variable" (chunk?) and which is the "list" to which you apply the re? The only list I see is the confusingly named "search" which is the *result* of applying re.findall. >>> >>>ss = re.compile(r'\b\d{3}-\d{2}-\d{4}\b') Users never use spaces or other punctuation (or no punctuation) instead of dashes? False positives? E.g. """ Dear X, Pls rush us qty 20 heart pacemaker alarm trigger circuits, part number 123-456-78-9012, as discussed. """ >>> >>>like this: >>> >>>for chunk in whole_file: >>> search = ss.findall(chunk) You will need the offset to update, so better get used to using something like finditer now. You may well find that "validate" may want to check some context on either side, even if it's just one character -- \b may turn out to be inappropriate. >>> if search: >>> validate(search) >> >>This seems so obvious that I hesitate to ask, but is the above really a >>simplification of the real code, which actually handles the case of SSNs >>that lie over the boundary between chunks? In other words, what happens >>if the first chunk has only the first four digits of the SSN, and the >>rest lies in the second chunk? >> >>-Peter > > > No, that's a good question. As of now, there is nothing to handle the > scenario that you bring up. I have considered this possibility (rare but > possible). I have not written a solution for it. It's a very good point > though. How rare? What is the average size of file? What is the average frequency of SSNs per file? What is the maximum file size (you did mention mostly MS Word and Excel, so can't be very big)? N.B. Using mmap just blows this problem away. Using bigger memory chunks diminishes it. And what percentage of files contain no SSNs at all? Are you updating in-situ, or must your script copy the files, changing SSNs as it goes? Do you have a choice between the two methods? Are you allowed to constrain the list of input files so that you don't update binaries (e.g.) exe files? > > Is that not why proper software is engineered? Anyone can build a go > cart (write a program), but it takes a team of engineers and much > testing to build a car, no? Which woulu you rather be riding in during a > crash? I wish upper mgt had a better understanding of this ;) > Don't we all so wish? Meanwhile, back in the real world, ... From donn at u.washington.edu Fri Jun 24 13:40:38 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 24 Jun 2005 10:40:38 -0700 Subject: trouble subclassing str References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> <1119619726.756391.175800@z14g2000cwz.googlegroups.com> Message-ID: In article <1119619726.756391.175800 at z14g2000cwz.googlegroups.com>, "Paul McGuire" wrote: [ ... lots of interesting discussion removed ... ] > Most often, I see "is-a" confused with "is-implemented-using-a". A > developer decides that there is some benefit (reduced storage, perhaps) > of modeling a zip code using an integer, and feels the need to define > some class like: > > class ZipCode(int): > def lookupState(self): > ... > > But zip codes *aren't* integers, they just happen to be numeric - there > is no sense in supporting zip code arithmetic, nor in using zip codes > as slice indices, etc. And there are other warts, such as printing zip > codes with leading zeroes (like they have in Maine). I agree, but I'm not sure how easily this kind of reasoning can be applied more generally to objects we write. Take for example an indexed data structure, that's generally similar to a dictionary but may compute some values. I think it's common practice in Python to implement this just as I'm sure you would propose, with composition. But is that because it fails your "is-a" test? What is-a dictionary, or is-not-a dictionary? If you ask me, there isn't any obvious principle, it's just a question of how we arrive at a sound implementation -- and that almost always militates against inheritance, because of liabilities you mentioned elsewhere in your post, but in the end it depends on the details of the implementation. Donn Cave, donn at u.washinton.edu From mart.franklin at gmail.com Wed Jun 1 04:04:11 2005 From: mart.franklin at gmail.com (Martin Franklin) Date: Wed, 01 Jun 2005 09:04:11 +0100 Subject: running tkinter In-Reply-To: References: Message-ID: Jim Anderson wrote: > I have just installed Fedora Core 3 on my pc. Python runs > fine, but when I try to run tkinter the tkinter library is > not found. I tried installing python 2.4.1 and could not get > tkinter to run there either. > > When I look through the build directories for 2.4.1, I find > a lib-tk, but I do not find anything for tcl. In past releases, > my recollection is that tcl/tk were part of the release and > that if TCL_LIBRARY and TK_LIBRARY environment variables were > set right, then tkinter would work. > > Are tcl/tk still supposed to be an intergrated part of the > python release? > > Do I have to download, configure, make, install tcl and tk > packages to get tkinter running? > > Thanks for any suggestions in advance. > > Jim Anderson On fedora tkinter is a separate package. just do this (as root) and all will be well:- yum install tkinter Cheers, Martin. From gregpinero at gmail.com Wed Jun 29 10:00:58 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 29 Jun 2005 10:00:58 -0400 Subject: Python syntax high-lighting and preservation on web In-Reply-To: References: Message-ID: <312cfe2b05062907006283b3ef@mail.gmail.com> This is perfect! Thanks! On 6/29/05, Daniel Dittmar wrote: > Gregory Pi?ero wrote: > > Hey guys, > > > > Does anyone know where I can pick up a style sheet (css) and/or other > > files/programs I might need to display python code on my website with > > tab preservation(or replace with spaces) and colored syntax? I want > > something similar to the python code on a page like this: > > see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 > > css only won't help you as someone has to insert the span tags so that > the style sheet has something to match. > > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list > From linux4bene at telenet.be Wed Jun 22 19:52:49 2005 From: linux4bene at telenet.be (Benedict Verheyen) Date: Wed, 22 Jun 2005 23:52:49 GMT Subject: importing a package In-Reply-To: <42b9a8e3_2@x-privat.org> References: <42b968a8_1@x-privat.org> <7ofue.127090$E62.7014438@phobos.telenet-ops.be> <42b9a8e3_2@x-privat.org> Message-ID: Damjan wrote: >>Indeed, when i do this, then it works >>import sys >>sys.path.append('package') >> >>However, why is it that package isn't added automatically to the pad? > > > When you execute a python program the directory where the program is is > automatically added to sys.path. No other directory is added to the default > builtin sys.path. > > In you case (the second case), you can import package.dir2.file2. OK, thanks for the info Regards, Benedict -- Benedict Verheyen Debian User http://www.heimdallit.be Public Key 0x712CBB8D From theller at python.net Thu Jun 23 11:20:39 2005 From: theller at python.net (Thomas Heller) Date: Thu, 23 Jun 2005 17:20:39 +0200 Subject: PEP 304 - is anyone really interested? References: Message-ID: Thomas Guettler writes: > Am Wed, 22 Jun 2005 18:01:51 -0500 schrieb Skip Montanaro: > >> >> I wrote PEP 304, "Controlling Generation of Bytecode Files": >> >> http://www.python.org/peps/pep-0304.html >> > > ... > > Hi, > > I am interested in a small subset: I want to import a file without > a '.pyc' being generated. > > Background: I sometimes missuse python for config files. For example Although I was not interested originally, I think that's a use case I also have. Optional config files, which should not be compiled to .pyc or .pyo. Only removing the .py file doesn't have the expected effect if a .pyc and/or .pyo if is left. I don't think the PEP supports such a use case. BTW: While I'me reading the PEP to check the above, I encountered this: Add a new environment variable, PYTHONBYTECODEBASE, to the mix of environment variables which Python understands. PYTHONBYTECODEBASE is interpreted as follows: If not defined, Python bytecode is generated in exactly the same way as is currently done. sys.bytecodebase is set to the root directory (either / on Unix and Mac OSX or the root directory of the startup (installation???) drive -- typically C:\ -- on Windows). If defined and it refers to an existing directory to which the user has write permission, sys.bytecodebase is set to that directory and bytecode files are written into a directory structure rooted at that location. If defined but empty, sys.bytecodebase is set to None and generation of bytecode files is suppressed altogether. AFAIK, it is not possible to define empty env vars on Windows. c:\>set PYTHONCODEBASE= would remove this env var instead of setting it to an empty value. Thomas From siona at chiark.greenend.org.uk Thu Jun 30 07:53:44 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Jun 2005 12:53:44 +0100 (BST) Subject: Inheriting from object References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >Fuzzyman a ?crit : >> *Should* I in fact write : >> >> class foo(object): >> def __init__(self, *args, **kwargs): >> object.__init__(self) >> >> ? >Nope. And if you were to do so, surely: class foo(object): def __init__(self, *args, **kwargs): super(foo, self).__init__(self) would be the preferred way to go? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From mdoukidis at gmail.com Wed Jun 1 22:51:47 2005 From: mdoukidis at gmail.com (mdoukidis at gmail.com) Date: 1 Jun 2005 19:51:47 -0700 Subject: pickle alternative In-Reply-To: <3g6ql1FatsshU1@individual.net> References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <1117524878.988878.181820@g44g2000cwa.googlegroups.com> <1117527950.319411.193030@g44g2000cwa.googlegroups.com> <1117606128.506536.234690@g14g2000cwa.googlegroups.com> <1117615222.581838.226820@g49g2000cwa.googlegroups.com> <3g6ql1FatsshU1@individual.net> Message-ID: <1117680707.772236.31150@f14g2000cwb.googlegroups.com> Running stest.py produced these results for me: marshal enc T: 12.5195908977 marshal dec T: 0.134508715493 sencode enc T: 3.75118904777 sencode dec T: 5.86602012267 11.9369997978 0.109000205994 True Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Notice the slow "marshal enc"oding. Overall this recipe is faster than marshall for me. Mark From jepler at unpythonic.net Tue Jun 21 14:35:02 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 21 Jun 2005 13:35:02 -0500 Subject: utf8 silly question In-Reply-To: <1374382022.20050621191607@bounce-software.com> References: <1374382022.20050621191607@bounce-software.com> Message-ID: <20050621183502.GC13744@unpythonic.net> If you want to work with unicode, then write us = u"\N{COPYRIGHT SIGN} some text" You can also write this as us = unichr(169) + u" some text" When you have a Unicode string, you can convert it to a particular encoding stored in a byte string with bs = us.encode("utf-8") It's generally a mistake to use the .encode() method on a byte string, but that's what code like bs = "\xa9 some text" bs = bs.encode("utf-8") does. It can lull you into believing it works, if the test data only has US ASCII contents, then break when you go into production and have non-ASCII strings. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rune.strand at gmail.com Tue Jun 14 09:45:21 2005 From: rune.strand at gmail.com (Rune Strand) Date: 14 Jun 2005 06:45:21 -0700 Subject: windows directory In-Reply-To: References: Message-ID: <1118756721.463740.24880@g43g2000cwa.googlegroups.com> On XP at least you have the environment variable "ProgramFiles". You can fetch the path it holds through os.environ From __peter__ at web.de Tue Jun 28 15:45:52 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Jun 2005 21:45:52 +0200 Subject: tkinter radiobutton References: <1ygwe.532$Ox3.193@newssvr12.news.prodigy.com> Message-ID: William Gill wrote: > I thought the problem was practical, not philosophical, but what do I > know I'm the one asking for help. What follows looks more like a spec than a question. > columns can have 0 or 1 selection > rows can have 0,1,2,3, or 4 selections. > Loop through the 4 intVars 4 times; compare their value to the value for > the row being processed; if they are the same bitor a value to a > rowVariable i.e. convert the column information (intVar values) to row > information. Here's my implementation: import Tkinter as tk class Radiogrid(tk.Frame): def __init__(self, master, columns, trace_write=None): tk.Frame.__init__(self) self.variables = [] self.buttons = [] for x, column in enumerate(columns): var = tk.IntVar() if trace_write: var.trace_variable("w", trace_write) self.variables.append(var) self.buttons.append([]) for y, text in enumerate(column): rbn = tk.Radiobutton(self, text=text, variable=var, value=y) rbn.grid(column=x, row=y) self.buttons[-1].append(rbn) def get_row_state(self, row): return tuple(row == var.get() for var in self.variables) if __name__ == "__main__": root = tk.Tk() def show_state(*args): for i in range(3): print "row", i, rg.get_row_state(i) print rg = Radiogrid(root, ["alpha beta gamma".split(), "one two three".split(), "guido van rossum".split()], show_state ) rg.pack() root.mainloop() I hope this will move further discussion from the abstract to the concrete :-) Peter From peter at somewhere.com Wed Jun 22 12:23:30 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 22 Jun 2005 18:23:30 +0200 Subject: Python API to manipulate CAB files. In-Reply-To: <1119447992.300154@hqnntp01.autodesk.com> References: <1119447992.300154@hqnntp01.autodesk.com> Message-ID: Isaac Rodriguez schrieb: > Does anyone know of a Python API to manipulate CAB files? If there is a Windows API you can probybly call it from Python using Mark Hammond's Win32 extensions. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From xah at xahlee.org Mon Jun 20 04:39:26 2005 From: xah at xahlee.org (Xah Lee) Date: 20 Jun 2005 01:39:26 -0700 Subject: functions with unlimited variable arguments... In-Reply-To: References: Message-ID: <1119256766.008772.62930@g43g2000cwa.googlegroups.com> Dear Chinook Lee, Thank you very much. That seems a godsend. I'd like to also thank its author Richard Gruet. Xah xah at xahlee.org ? http://xahlee.org/ Chinook wrote: > ... > I don't get to the reference docs much. Mostly I use the quick reference > guide and it's noted there in an easy to find manner. If you have not > checked it out then see: > > http://rgruet.free.fr/#QuickRef > > Lee C From vincent at visualtrans.de Tue Jun 7 15:17:07 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 7 Jun 2005 21:17:07 +0200 Subject: DB API 2.0 and transactions References: Message-ID: "Christopher J. Bottaro" schrieb im Newsbeitrag news:mailman.92.1118167102.10512.python-list at python.org... | Hi, | Why is there no support for explicit transactions in the DB API? I mean | like transaction() to start the trans and commit() and rollback() would end | the trans or something. | | The reason why I ask is because I wrote a daemon that interacts with a | Postgres DB. The value of CURRENT_TIMESTAMP according to Postgres is NOT | the actual walltime, but the walltime when the current transaction started. | | This gets weird when using the Python DB API to interact with Postgres | because a transaction gets started in 3 places: connection, commit, | rollback. | | So consider the daemon: | | [pseudo code] | connect # begin trans at 12:00 | sleep waiting # lets say 15 mins | wake up | put entry in db using CURRENT_TIMESTAMP # oops | [/code] | | Oops, the CURRENT_TIMESTAMP evaluates to 12:00, not 12:15. | | Now I know there are ways around this... | 1) In Postgres, you can get the walltime and cast it to a timestamp. | 2) In Python, you can just do an empty commit in order to "manually" start | a new transaction. | | I just think its a bit weird because this bit me in the butt for quite a | while and this didn't happen when doing the same thing in other langs. | | Anyone have any opinions on this? The described behavior seems to be totally in synch with expectations (both in accordance with PostgreSQL docs and the DB-API.) These "other languages" *must* be doing something wrong! ;) ( Auto-commit set to "on" perhaps? ) Regards, - Vincent Wehren | From hancock at anansispaceworks.com Fri Jun 10 23:18:14 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Jun 2005 22:18:14 -0500 Subject: without shell In-Reply-To: References: Message-ID: <200506102218.14085.hancock@anansispaceworks.com> On Friday 10 June 2005 05:30 am, Tomasz Rola wrote: > On Sun, 12 Jun 2005, km wrote: > > > hi all, > > > > can any linux command be invoked/ executed without using shell (bash) ? > > what abt security concerns ? > > Ops, I missed the word "command" when reading your mail for the first > time, and this changes some parts of my previous answer and makes it > shorter: > > There is an execve system call. You don't need neither sh, nor the libc to > run programs. It's described in section 2 of manpages. The rest of the > answer you can get from my previous post. I haven't used it, but according to the Python 2.4 documentation, the subprocess module does not use any shell. Or the shell is python, as it were. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From chinook.nr at tds.net Tue Jun 28 22:36:48 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 22:36:48 -0400 Subject: OO refactoring trial ?? References: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> <0001HW.BEE6FEEE000C427BF0407550@news.gmane.org> Message-ID: <0001HW.BEE781800014716FF0407550@news.gmane.org> Paul, Going back over various material led to another question regarding your comments. > - I'm not keen on the coupling of forcing your A,B,etc. classes to > inherit from MF. Especially in a duck-typing language like Python, it > adds no value, the subclasses receive no default behavior from their > superclass, and I'm not keen on using the inheritance hierarchy to > register test classes. The latter (__subclasses__() bit) I picked up on as a convenience (courtesy of a suggestion by STeVe) and I understand your point about more explicit ordering. However, the former seems to take issue with examples like: http://jamesthornton.com/eckel/TIPython/html/Sect08.htm or indirectly as a show stopper (using inheritance) as in: http://www.unc.edu/~mconway/mt_static/archives/odds_and_ends/ which is more in line with your comments. Anything more to this than individual preferences? Might it not be more explicit at least? Anyone? Thanks, Lee C From and-google at doxdesk.com Wed Jun 1 14:36:43 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 1 Jun 2005 11:36:43 -0700 Subject: Elementtree and CDATA handling References: <1117631202.723453.20060@z14g2000cwz.googlegroups.com> Message-ID: <1117651003.858779.274950@g43g2000cwa.googlegroups.com> Alain wrote: > I would expect a piece of XML to be read, parsed and written back > without corruption [...]. It isn't however the case when it comes > to CDATA handling. This is not corruption, exactly. For most intents and purposes, CDATA sections should behave identically to normal character data. In a real XML-based browser (such as Mozilla in application/xhtml+xml mode), this line of script would actually work fine: > if (a < b && a > 0) { The problem is you're (presumably) producing output that you want to be understood by things that are not XML parsers, namely legacy-HTML web browsers, which have special exceptions-to-the-rule like " """ from elementtree import ElementTree tree = ElementTree.fromstring(text) ElementTree.dump(tree) Running the above piece of code yields the following: Document There are two problems: the // and && have been replaced by their equivalent entities (CDATA should have prevented that). I am no XML/HMTL expert, so i might be doing something wrong... Thank you for helping Alain From guy.lateurNNOOSSPPAAMM at pandora.be Tue Jun 28 14:06:17 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Tue, 28 Jun 2005 18:06:17 GMT Subject: Office COM automatisation - calling python from VBA References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: Just an update: I've succeeded in writing a COM server, exposing wxPy funtcionality. I've also used this object from within Outlook - 2 lines of VBA: dispatch COM object & call method. If anyone is interested, I could post the source. A few days ago, I honestly didn't think I'd already be this far by now (it took about half a day). Especially the chapter of the book by Mark Hammond (my copy of which is being dispatched as we speak) was very helpful. 8) g From tim.golden at viacom-outdoor.co.uk Tue Jun 14 09:42:42 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Jun 2005 14:42:42 +0100 Subject: Where is Word? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8D2@vogbs009.gb.vo.local> [Guy Lateur] | I want to make a temporary file (directory listing), open it | in Word to let | the user edit, layout and print it, and then delete the temp file | afterwards. I don't think we'll be able to fully automate it, | though. The | user should be able to set her own fonts and stuff. Haven't tried the technique myself, but this post http://groups-beta.google.com/group/comp.lang.python/msg/4ea1a92c2c3a4664 looks like it might do what you're after. In essence, you use CreateProcess to run Word (which is a bit messier than the other techniques described, but gives you a bit more control), and then you use the handle that passes back to determine when it's finished. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From chad.hughes at pnl.gov Fri Jun 17 14:50:20 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Fri, 17 Jun 2005 11:50:20 -0700 Subject: how to operate the excel by python? Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B619B@pnlmse27.pnl.gov> I have posed a more complete answer to your question, however, it is quite a large and It is awaiting approval. For now, xlRight = -4152. You can find this out by opening up Excel and typing the ALT-F11 combination. From there use the ObjectBrowser. For example if you type in the word "xlRight" you will see that it is equal to -4152. Chad -----Original Message----- From: Kevin P. Coffey [mailto:kevin.coffey at ism-corp.us] Sent: Friday, June 17, 2005 11:28 AM To: python-list at python.org Subject: how to operate the excel by python? Question please: In the post, "How to operate the excel by python," where did you find the codes for HorizontalAlignment and VerticalAlignment (Center = -4108 and Bottom = -4107)? I need the code for HorizontalAlignment = xlRight. Is there a table somewhere that shows these codes? Thanks kevin.coffey at ism-corp.us -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at zoran.com Mon Jun 20 07:38:17 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 20 Jun 2005 14:38:17 +0300 Subject: Embedding Python - How to create a class instance In-Reply-To: <20050620115323.6d2e256c@ods.pravda.rfn.ru> References: <20050619072953.GJ908@zoran.com> <20050620115323.6d2e256c@ods.pravda.rfn.ru> Message-ID: <20050620113816.GD1236@zoran.com> Hello Denis, >> I'm trying to embed Python in a C application. >> What I didn't find is how to create an instance once I have a class object. > > Class is a callable object. Just call it to create instance. > ... > obj = PyObject_CallObject(A, NULL); Thanks. After grepping the Python sources I've found about obj = PyInstance_New(A, NULL, NULL) which worked for me. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From skromta at gmail.com Sun Jun 12 09:56:35 2005 From: skromta at gmail.com (Kalle Anke) Date: Sun, 12 Jun 2005 15:56:35 +0200 Subject: How to get/set class attributes in Python References: <42ac0c6d$0$10102$626a14ce@news.free.fr> <42AC3A13.9020503@lexicon.net> Message-ID: <0001HW.BED20BB3002E462AF0407550@news.gmane.org> On Sun, 12 Jun 2005 15:35:15 +0200, John Machin wrote (in article <42AC3A13.9020503 at lexicon.net>): > OTOH, I beseech you to consider an attitude transplant :-) ;-) > I.e. put your effort into writing code that allows people to do useful > things, rather than opaque guff full of __blahblah__ that stops them > from doing dopey or evil things they're usually smart enough or > righteous enough not to do anyway. I'm just trying to protect myself from myself :-) No, I'm playing around with different ways of doing things, trying to learn Python and how do things in a proper "pythonic" way. In this case I'm going to have a class with some properties that are going to be stored in a database, I don't want to read all the properties everytime I recreate the object from the database but I still want to give the impression that the attributes exists and is available. So my idea was to "hide" the actual database stuff ... > BTW, what do you think of this: > > sys.maxint = -12345 I don't really understand what you're meaning. jem From fairwinds at eastlink.ca Sun Jun 5 12:32:05 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Sun, 05 Jun 2005 13:32:05 -0300 Subject: Iterate through a list calling functions In-Reply-To: Message-ID: <5A3E19AC-D5DF-11D9-BFBC-000A27B3B070@eastlink.ca> Hi. I am creating methods for form validation. Each validator has its own method and there quite a number of these. For each field, I want to evaluate errors using one or more validators so I want to execute the appropriate validator methods from those available. I am iterating over each validator using validateField method to gather my results. It works but it ugly and inefficient. Can someone advise whether there is a better way of doing this. I realize that the validator variable in my iteration is only a string so question is how can I make the validator string reference a function so I may be able to shorten validateField to something similar to this (instead of my long list of ifs which I am not very happy with): for validator in validators_list: result = validator(name, value) if type (result) in StringTypes: results[name] = result Many thanks David My current situation below: # A large list of validators def isDecimal(name, value): """ Test whether numeric value is a decimal """ result = validateRegex(name, value, r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', errmsg='is not a decimal number.', ignore=None) return result def isZipCode(name, value): """ Tests if field value is a US Zip Code """ result = validateRegex(name, value, r'^(\d{5}|\d{9})$', errmsg='is not a valid zip code.', ignore=None) return result ... more validators # Iterating over validators to gather field errors def validateField(name, value, validators_list, range=None, valid_values=None): """ Validates field input """ results={} for validator in validators_list: if validator == 'isContainedIn': result = isContainedIn(name, value) if type (result) in StringTypes: more... if validator == 'isDate': result = isDate(name, value) if type (result) in StringTypes: more... if validator == 'isDecimal': result = isDecimal(name, value) if type (result) in StringTypes: more... more validators ... From p at ulmcnett.com Wed Jun 15 19:14:04 2005 From: p at ulmcnett.com (Paul McNett) Date: Wed, 15 Jun 2005 16:14:04 -0700 Subject: splitting delimited strings In-Reply-To: References: Message-ID: <42B0B63C.1010800@ulmcnett.com> Mark Harrison wrote: > What is the best way to process a text file of delimited strings? > I've got a file where strings are quoted with at-signs, @like this at . > At-signs in the string are represented as doubled @@. Have you taken a look at the csv module yet? No guarantees, but it may just work. You'd have to set delimiter to ' ' and quotechar to '@'. You may need to manually handle the double-@ thing, but why don't you see how close you can get with csv? > @rv@ 2 @db.locks@ @//depot/hello.txt@ @mh@ @mh@ 1 1 44 > @pv@ 0 @db.changex@ 44 44 @mh@ @mh@ 1118875308 0 @ :@@: :@@@@: @ > > (this is from a perforce journal file, btw) -- Paul McNett http://paulmcnett.com From peter at engcorp.com Fri Jun 24 21:29:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 21:29:05 -0400 Subject: a dictionary from a list In-Reply-To: References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: Dave Cook wrote: > On 2005-06-24, infidel wrote: > > >>dict((x, None) for x in alist) > > Whoa, I thought dictionary comprehensions were still planned feature. I > guess I gotta start paying closer attention. Added in Python 2.4, it's actually a generator expression as the sole argument to a generic dict() constructor. Think of the generator expression as sort of like the list comprehension that it resembles, minus the square brackets, but which doesn't have to create the entire list before the dict() constructor starts to consume the elements. -Peter From kent37 at tds.net Wed Jun 22 11:42:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Jun 2005 11:42:06 -0400 Subject: a comprehensive Tkinter document? In-Reply-To: References: Message-ID: <42b98634_2@newspeer2.tds.net> William Gill wrote: > I know a major problem I am having is that I am finding lots of Tkinter > information in 'fragments' of various , sometimes conflicting vintages. > For example the python reference I was using didn't show the '%%' as an > escape sequence, I posted asking how to escape the '%' and after several > helpful responses voila I found a more complete table of escape > sequences. Is there a comprehensive document or book that I can get > that is relatively current? Maybe not comprehensive but I think reasonably current: http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ Kent From listserver at tdw.net Tue Jun 7 04:55:46 2005 From: listserver at tdw.net (Tim Williams) Date: Tue, 7 Jun 2005 09:55:46 +0100 Subject: SMTP help please References: Message-ID: <000901c56b3e$b1be99d0$ccbefea9@twilliams> ----- Original Message ----- From: "Martin Franklin" > server.sendmail(fromaddr, toaddrs, msg) You can use this if you don't need to worry about whether the email was successfully sent to all recipients. Otherwise, you need something like this (untested and partly copied from an earlier post of mine). ------------------------------------------------ import smtplib try: s = smtplib.SMTP(outgoing_server) failed = s.sendmail(fromaddr, toaddrs, msg) except smtplib.SMTPRecipientsRefused, x : # All failed do something # for recip in x.recipients: info = x.recipients[recip] except smtplib.SMTPDataError, x: # email failed after data stage do something # x[0], x[1] except smtplib.SMTPSenderRefused, x : # the sender was refused do something # x.sender, x.smtp_code, x.smtp_error except: do something try: s.close() except pass for recip in failed: do something -------------------------------------------------- (failed contains a list of failed recipients if *some* but not all failed, if all failed then use : except smtplib.SMTPRecipientsRefused, x :) From irmen.NOSPAM at xs4all.nl Wed Jun 1 13:53:49 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 01 Jun 2005 19:53:49 +0200 Subject: Seti-like program In-Reply-To: References: Message-ID: <429df62e$0$29162$e4fe514c@news.xs4all.nl> Magnus Lycka wrote: > Both CORBA implementations and simpler things like PYRO could help, but > these systems are more aimed at enabling communication between programs > running in a distributed fashion, and I don't think they target tasks > such as job queues, starting and stopping jobs, or load balancing etc. Indeed, not directly. But it would be possible to create such a thing. And the latest Pyro (3.5 beta, at the moment) contains an interesting example that automatically partitions a computation task, distributes the parts among available 'processor' objects, and aggregates the result. I have supplied a sorting task and a md5 'cracking' task. It is perhaps not really what was asked, but I think it is at least a bit relevant to this topic. --Irmen From desertgarden at netscape.com Sat Jun 25 10:50:48 2005 From: desertgarden at netscape.com (Brian) Date: Sat, 25 Jun 2005 14:50:48 GMT Subject: Excellent Site for Developers In-Reply-To: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: Do Re Mi chel La Si Do wrote: > rather... super troll 100% Agreed. Can anyone say, "This looks like spam... Feels like spam... and is about as useful here in the Python forums as spam -- therfore my conclusion is that his VB message probably IS SPAM." :-D Brian --- From deets at web.de Thu Jun 9 08:20:16 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 09 Jun 2005 14:20:16 +0200 Subject: XML + SOAP + Webservices In-Reply-To: References: Message-ID: Johan Segern?s wrote: > I'm put on building a system in Python and I haven't used either webservices, > SOAP or Python so I'm a bit lost. > > This system will require callback functions, should I use Python thru Apache > for this or build my own listening daemon? Use module for Apache or do I make > some kind of CGI script in Python? > > Where do I start? What lib do I use for XML? SOAP? Webservices? > > Is there any nice project/tutorial for this so I can give it a taste and try > to estimate how much time I need and stuff. For first tries, you could go and check SimpleXMLRPCServer - it's in the docs. Then there is twisted, and some others I believe. Running throgh an apache doesn't buy you much AFAIK - so just skip it for now for the additional complexity it involves. Callbacks aren't supported by any xml-based RPC I'm aware of - which doesn't mean you can't do it, but _how_ to do it is up to you: You need a way to pass a server the necessary callback information. It basically consists of the url to talk to. That by the way is no limitation of python, but of xmlrpc, soap and whatever. And last but not least I found that whenever I tried to make python SOAP implementations work with more than trivial WSDLs I (or the implementations...) failed - maybe you can tweak it into working by handtayloring the calls and proxies - but that is tedious, errorprone and certainly not the road somone want's to go. I personally always used apache axis in conjunction with jython to fulfill my SOAP needs in python. But then again, it's not python anymore - at least not when you need some cpython-only lib s. regarding the .NET stuff - don't expect much. Just because it uses a wire-protocol that is well known doesn't mean that the infrastructure build on top of it is easy to grasp - and it's not integrated in anything but itself. That's true for the JAVA-world either, btw. Sooo - concluding remarks could be: - soap and python - not so good - if you can, use some other RPC to interface .NET - like IPython, or win32, or even corba if you can. Regards, Diez From philippe at philippecmartin.com Sat Jun 11 18:49:35 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 11 Jun 2005 22:49:35 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> Message-ID: <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> I agree '...choice for the very beginners ...': a hundred year ago I was a Pascal TA, and although I like the language, I find/found people stuggled as much with the language as with the algorithm they were supposed to implement. "...mostly variants of Basic..." What I truly liked going from Basic (which has greatly evolved) to Pascal was the fact I found a definite risk not having to declare variable/ or rather I understood the lack of danger in doing so: The one (so I thought) glitch with Python that almost made me stop playing with was that very fact. yet I agree a complete beginner would simply the approach most meaningful "why should I write int i = 1 since I know 1 is an int". Since the "dangers" of old basic are gone from Python (can't do i=y if y has not ever been initialized). I must agree with that too. I'm actually pushing the few CS professors I know to use Python for CS 101. Yet, many issues that a future software engineer should know are mostly hidden by Python (ex: memory management) and that could be detrimental. Regards, Philippe Claudio Grondi wrote: >> 4) Yes I agree a mix ("... well spiced soup ...") >> seems to be the answer but >> my brain somehow wants to formalize it. > > Here one further suggestion trying to point out, that > it probably can't generally be formalized, because > the experience one developes after going through > the story of "assembly, basic, cobol, lisp, > JAVA, c, c++, perl, Tcl, Java, JavaCard" has > in my opinion a vital impact on shortcuts one uses > and the way of doing things. I mean, that the concept > of Python has raised from such experience, so anyone > who went through all this, will get the core ideas > implemented in Python without any effort, because > they were already there as a kind of meta-language > used in thinking, unconsciously looking for the > chance of beeing expressed in formalized form > as a new programming language. > To support my thesis I can mention here, that > from my experience, Python seems not to be > the language of choice for the very beginners, > who prefere another approaches which are > mostly variants of Basic. > > Claudio > > "Philippe C. Martin" schrieb im Newsbeitrag > news:GhIqe.3677$%j7.513 at newssvr11.news.prodigy.com... >> Thanks , >> I have gotten many answers already, some not posted. >> >> 1) Typing is not the issue - even with RT-Kernels, people use C++ >> 2) Yes I find dynamic binding very nice >> 3) "... you didn't give many examples of what you did for the >> last 18 years (except that that also included RT kernels). ...." assembly >> (losts) , basic, cobol, lisp, JAVA, c, c++, perl, Tcl, Java, JavaCard > ..... >> >> I know the "interactive" aspect helps also, the runtime error/exception >> checking, the many libraries/tools, the responsiveness of the people on >> this newsgroup, the "introspectiveness" of the system, the cross-platform >> it deals with, the way it "pushes" people to code in a clean way, the GUI >> support, the stability, the extensibility (in and out) .... I'm sure > you'll >> agree none of that can explain why after 1 week of playing with, I was > more >> productive in Python than C/C++ just as I know my product (I will not >> describe it here as I am not marketing) would not exist today were it not >> for Python. >> 4) Yes I agree a mix ("... well spiced soup ...") seems to be the answer > but >> my brain somehow wants to formalize it. >> >> Regards, >> >> Philippe >> >> >> >> >> >> Philippe C. Martin wrote: >> >> > I apologize in advance for launching this post but I might get > enlightment >> > somehow (PS: I am _very_ agnostic ;-). >> > >> > - 1) I do not consider my intelligence/education above average >> > - 2) I am very pragmatic >> > - 3) I usually move forward when I get the gut feeling I am correct >> > - 4) Most likely because of 1), I usually do not manage to fully >> > explain 3) when it comes true. >> > - 5) I have developed for many years (>18) in many different > environments, >> > languages, and O/S's (including realtime kernels) . >> > >> > >> > Yet for the first time I get (most) of my questions answered by a > language >> > I did not know 1 year ago. >> > >> > As I do try to understand concepts when I'm able to, I wish to try and >> > find out why Python seems different. >> > >> > Having followed this newsgroup for sometimes, I now have the gut >> > feeling (see 3)) other people have that feeling too. >> > >> > >> > Quid ? >> > >> > Regards, >> > >> > Philippe >> From richardlewis at fastmail.co.uk Mon Jun 20 07:44:16 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Mon, 20 Jun 2005 12:44:16 +0100 Subject: utf8 and ftplib In-Reply-To: <1119267462.32655.236736750@webmail.messagingengine.com> References: <1119267462.32655.236736750@webmail.messagingengine.com> Message-ID: <1119267856.583.236737784@webmail.messagingengine.com> On Mon, 20 Jun 2005 12:37:42 +0100, "Richard Lewis" said: > [SNIP] Just add to this: my input document was written using character references rather than literal characters (as was the sample output document). However, I've just noticed that my mail client (or maybe something else?) has converted the character references to literal characters. From noah at noah.org Wed Jun 29 15:08:24 2005 From: noah at noah.org (Noah) Date: 29 Jun 2005 12:08:24 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: <1120072104.541014.166820@o13g2000cwo.googlegroups.com> unzip() -- Not really a module, but a standard library function. Why isn't it in the standard library? It seems like I'm always adding it to my code. I think I once heard an argument against it, but I forget what it was. And yet I still find myself wanting unzip. def unzip(list): if len(list) == 0: return () l = [] for t in range(len(list[0])): l.append(map( lambda x,t=t: x[t], list )) return tuple(l) Yours, Noah Reinhold Birkenfeld wrote: > Hello, > > at the moment python-dev is discussing including Jason Orendorff's path module > into the standard library. > > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? > > For my part, ctypes seems like a suggestion to start with. > > Reinhold From eloff777 at yahoo.com Wed Jun 22 17:09:42 2005 From: eloff777 at yahoo.com (Eloff) Date: 22 Jun 2005 14:09:42 -0700 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: <7xhdfqgmsz.fsf@ruckus.brouhaha.com> References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> Message-ID: <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Hi Paul, >Do you mean a few records of 20+ MB each, or millions of records of a >few dozen bytes, or what? Well they're objects with lists and dictionaries and data members and other objects inside of them. Some are very large, maybe bigger than 20MB, while others are very numerous and small (a hundred thousand tiny objects in a large list). Some of the large objects could have many locks inside of them to allow simultaneous access to different parts, while others would need to be accessed as a unit. >If the 100 threads are blocked waiting for the lock, they shouldn't >get awakened until the lock is released. So this approach is >reasonable if you can minimize the lock time for each transaction. Now that is interesting, because if 100 clients have to go through the system in a second, the server clearly is capable of sending 100 clients through in a second, and it doesn't matter if they all go through "at once" or one at a time so long as nobody gets stuck waiting for much longer than a few seconds. It would be very simple and painless for me to send them all through one at a time. It is also possible that certain objects are never accessed in the same action, and those could have seperate locks as an optimization (this would require carefull analysis of the different actions.) >You're doing what every serious database implementation needs to do ... >Are you sure you don't want to just use an RDBMS? It was considered, but we decided that abstracting the data into tables to be manipulated with SQL queries is substantially more complex for the programmer and way too expensive to the system since the average action would require 20-100 queries. Thanks, -Dan From michele.simionato at gmail.com Tue Jun 21 07:58:29 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 21 Jun 2005 04:58:29 -0700 Subject: Create our own python source repository In-Reply-To: <1118170303.568984.242610@z14g2000cwz.googlegroups.com> References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> <1118156654.634103.186390@o13g2000cwo.googlegroups.com> <1118170303.568984.242610@z14g2000cwz.googlegroups.com> Message-ID: <1119355109.640882.74380@g47g2000cwa.googlegroups.com> qwwee: > for a certain argument I'd prefer an application fully >explained (also if not covering all the features) to a more general >tutorial with only brief and unrelated code snippets. >Unfortunately, that's not the way things are normally done, because it >is much harder to build a useful application and fully comment it A part the Cookbook, I know of at least two Python books taking the approach you describe: 1. Dive into Python (Pilgrim) 2. Programming Python (Lutz) Dive into Python is free (and even translated in Italian on www.python.it, IIRC) Michele Simionato From rex.eastbourne at gmail.com Thu Jun 23 18:34:22 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 23 Jun 2005 15:34:22 -0700 Subject: Running Python interpreter in Emacs Message-ID: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> Hi, I'm interested in running a Python interpreter in Emacs. I have Python extensions for Emacs, and my python menu lists "C-c !" as the command to run the interpreter. Yet when I run it I get the message "Spawning Child Process: invalid argument." What do I need to do/download to fix this? I read in a post in this group from a while back where someone had the following lines in his .emacs file: (setq interpreter-mode-alist (cons '("python" . python-mode) interpreter-mode-alist)) Does that have something to do with it? Do I have to set my load-path to my python interpreter? Thanks, Rex From robin at reportlab.com Wed Jun 15 10:03:40 2005 From: robin at reportlab.com (Robin Becker) Date: Wed, 15 Jun 2005 15:03:40 +0100 Subject: non OO behaviour of file Message-ID: <42B0353C.3030603@chamonix.reportlab.co.uk> I recently tried to create a line flushing version of sys.stdout using class LineFlusherFile(file): def write(self,s): file.write(self,s) if '\n' in s: self.flush() but it seems that an 'optimization' prevents the overriden write method from being used. I had thought python was more regular than it appears to be. Is there a better way to accomplish the intention of the above than class LineFlusherFile: def __init__(self,*args): self._f = open(*args) def __getattr__(self,a): return getattr(self._f,a) def write(self,s): self._f.write(s) if '\n' in s: self._f.flush() I wondered if I could make a file subclass somehow fail the PyFile_Check which allows the optimization. -- Robin Becker From ptmcg at austin.rr.com Sun Jun 26 17:14:50 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Jun 2005 14:14:50 -0700 Subject: OO approach to decision sequence? References: Message-ID: <1119820490.656027.249730@g14g2000cwa.googlegroups.com> Lee C - Here is a technique for avoiding the if-elseif-elseif...-else method for building objects. It is a modified form of ChainOfResponsibility pattern, in which you have a collection of factory methods that all have a common signature, or a collection of Factory classes that all implement a "makeObject" method. These common methods probably take a string, and return a generic object. Fortunately, such type flexibility is *very* easy in Python. :) Example: I want to convert individual strings to native data types. I want to detect integers, reals, complex numbers, and booleans (indicated by 'True' or 'False'). This is kind of similar to a parsing problem, but it could also be used for deserializing or unpickling data of an unknown original type. Note the special treatment I have to go through with boolean values - I needed to write a special makeBool routine, since Python will take any non-empty string to be True, when what I want is 'True' to yield true and 'False' to yield false. Hope this gives you some alternative ideas to your cascading if's. -- Paul def makeBool(s): if s in ('True','False'): return s == 'True' raise ValueError converters = [ int, float, complex, makeBool, str ] def makeObject(stringVar): for conv in converters: try: val = conv(stringVar) except Exception: continue else: break; return val def test(s): val = makeObject(s) print s, val, type(val) test('1') test('1.0') test('1+2j') test('1+0j') test('True') test('False') test('A') prints: 1 1 1.0 1.0 1+2j (1+2j) 1+0j (1+0j) True True False False A A From nospam at here.com Wed Jun 1 12:35:17 2005 From: nospam at here.com (Matt Feinstein) Date: Wed, 01 Jun 2005 12:35:17 -0400 Subject: Unhappy with numarray docs References: <429dc954$1@nntp0.pdx.net> <1dlr911ln6omm7nov1amaqtbikdvp51p7n@4ax.com> Message-ID: On Wed, 01 Jun 2005 09:55:14 -0600, Fernando Perez wrote: >Just a suggestion: post your message on the numeric discussion list (where >numarray is also discussed). Most of the num* developers only check c.l.py on >occasion, so it's very easy that your message will be simply missed by the >appropriate people, which would be a shame. They are generally very >responsive to user requests and constructive criticism. Done. Thanks for the suggestion. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From deets at web.de Sun Jun 26 07:07:53 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 26 Jun 2005 13:07:53 +0200 Subject: accessing object attribute as parameter In-Reply-To: <1119782637.483529.101890@g43g2000cwa.googlegroups.com> References: <1119782637.483529.101890@g43g2000cwa.googlegroups.com> Message-ID: <3i7gk9Fjr5buU1@uni-berlin.de> ajikoe at gmail.com wrote: > Hello, > > I would like to access object parameter / variable from a function. > > For example : > class A: > def __init__(self, x,y): > self.x = x > self.y = y > > in the main program, I have a list of obj A: > L = [A(1,2), A(2,3)] > > Now I need to access the value of x or y from a function: > def GetSomething(seqObj, ?): > return [obj.? from seqObj] > > > How can I access x or y through this function ? Use getattr: def GetSomething(seqObj, name): return [getattr(obj, name) for obj in seqObj] Diez From hancock at anansispaceworks.com Wed Jun 15 14:40:27 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 15 Jun 2005 13:40:27 -0500 Subject: FAQ: __str__ vs __repr__ In-Reply-To: <1118840774.643768.218300@o13g2000cwo.googlegroups.com> References: <42b021ba$1@griseus.its.uu.se> <1118840774.643768.218300@o13g2000cwo.googlegroups.com> Message-ID: <200506151340.27215.hancock@anansispaceworks.com> On Wednesday 15 June 2005 08:06 am, S?bastien Boisg?rault wrote: > Jan Danielsson a ?crit : > > However, I don't understand what __repr__ should be. > It is an *exact* (if possible) description of the object's content, > nicely packaged into a string. However, this is often not the case. Frequently __repr__ will return something like this: >>> import re >>> r = re.compile('\w+\d*') >>> r <_sre.SRE_Pattern object at 0x401a89b0> >>> str(r) '<_sre.SRE_Pattern object at 0x401a89b0>' >>> repr(r) '<_sre.SRE_Pattern object at 0x401a89b0>' So don't obsess over it. For many objects it isn't worth the trouble, and for others, str() and repr() are sensibly the same thing, but for some, the distinction is useful. That's all. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From singletoned at gmail.com Thu Jun 23 11:31:59 2005 From: singletoned at gmail.com (Singletoned) Date: 23 Jun 2005 08:31:59 -0700 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: <1119540719.150128.66470@g14g2000cwa.googlegroups.com> Rocco Moretti wrote: > Steven D'Aprano wrote: > > That's the joys of a mostly self-taught programming knowledge: you miss > > out on all the buzzwords. > > Being mostly self taught myself, I have a tendancy to use infrequently > encountered terms in related but technically inappropriate contexts, > confusing the better informed people I deal with. ;-) Indeed. I find I use even more buzzwords because I can just make up as many as I want. From Nicholas.Vaidyanathan at aps.com Tue Jun 14 17:22:40 2005 From: Nicholas.Vaidyanathan at aps.com (Nicholas.Vaidyanathan at aps.com) Date: Tue, 14 Jun 2005 14:22:40 -0700 Subject: Tkinter question Message-ID: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> I'm sure there must be a way to do this, but I can't figure it out for the life of me... I'm writing a program where I would like to use a button's text field as part of an if statement. I set up my button like this: i = [ "7", "8","9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"] t = 0 #iterator through the sequence for x in range(4): for y in range(4): self.buttonx = Button(self, text = "%s" %i[t] , width=10, command = self.pressed) self.buttonx.grid( row=x+1, column = y, sticky = W+E+S) t+=1 What I would like to do is is check which buttons' text values are digits, and if the text is, I would like to append the number to a label. But: if(self.buttonx.title.isdigit): Doesn't work. How do I access the button's text field? Thanks! "MMS " made the following annotations. ------------------------------------------------------------------------------ --- NOTICE --- This message is for the designated recipient only and may contain confidential, privileged or proprietary information. If you have received it in error, please notify the sender immediately and delete the original and any copy or printout. Unintended recipients are prohibited from making any other use of this e-mail. Although we have taken reasonable precautions to ensure no viruses are present in this e-mail, we accept no liability for any loss or damage arising from the use of this e-mail or attachments, or for any delay or errors or omissions in the contents which result from e-mail transmission. ============================================================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: From richardlewis at fastmail.co.uk Tue Jun 14 09:26:16 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Tue, 14 Jun 2005 14:26:16 +0100 Subject: Resume after exception In-Reply-To: <1118740170.9602.236315256@webmail.messagingengine.com> References: <1118740170.9602.236315256@webmail.messagingengine.com> Message-ID: <1118755577.31146.236330824@webmail.messagingengine.com> On Tue, 14 Jun 2005 10:09:30 +0100, "Richard Lewis" said: > Hi there, > > Is it possible to have an 'except' case which passes control back to the > point after the exception occurred? > > e.g. > > # a function to open the file > # raises FileLockedException is file contains 'locked' information > def open_file(file_name): > f = file(file_name, 'r') > {read first line for file lock info} > if first_line == "FILE LOCKED": > raise FileLockedException(lock_user, lock_timestamp) > {read remainder of file} > return True > > # elsewhere in a user interface module > def open_command(): > try: > open_file("foo.bar") > except FileLockException, X: > ans = tkMessageBox.askyesno(title="File Locked", message="File > locked by '" + X.user + "' on " + X.time_stamp + "\nContinue > anyway?") > if ans == tkMessageBox.YES: > # return control to the remainder of the open_file function. > How? > else: > return False > Thanks for your suggestions. I've gone with the passing an 'ignore_lock' option to the open_file function: def open_file(self, ignore_lock=False): "Retrieves content file from FTP server and parses it into local DOM tree." ftp = ftplib.FTP(self.host) ftp.login(self.login, self.passwd) content_file = file(self.local_content_file_name, 'w+b') ftp.retrbinary("RETR " + self.path, content_file.write) ftp.quit() content_file.close() self.document = parse(self.local_content_file_name) root = self.document.documentElement if not(ignore_lock) and root.getAttribute("locked") == "1": raise ContentLocked(root.getAttribute("user"), root.getAttribute("time-stamp")) self.set_file_lock() self.opened = True return True #..... elsewhere ..... def open_command(self): "Command to handle 'open' actions." try: self.site.load_from_server('user','host.name','login','passwd','path/to/content.xml', False) except ContentLocked, e: ans = QMessageBox.question("Content Locked", "The content file is locked!\n\nIt seems that the user '" + e.user + "' is already working on the website. They left the time stamp:\n" + e.time_stamp + "\n\nChoose 'Yes' to carry on working on the website and risk losing another user's changes, or 'No' to quit.", "Yes", "No", "Cancel") if ans == "Yes": self.site.load_from_server('user','host.name','login','passwd','path/to/content.xml', True) else: qApp.quit() except Exception, e: #... I don't know why I put return False in my original open_command function, it was supposed to be a quit call. This solution allows me to keep my exception mechanism (which passes the lock information [user and timestamp] out of the open_file function) because it is dependent on ignore_lock being false. Cheers, Richard From davecook at nowhere.net Wed Jun 22 11:50:03 2005 From: davecook at nowhere.net (Dave Cook) Date: Wed, 22 Jun 2005 15:50:03 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: On 2005-06-22, Will McGugan wrote: > I'd like to write a windows app that accesses a locally stored database. > There are a number of tables, the largest of which has 455,905 records. > > Can anyone recommend a database that runs on Windows, is fast / > efficient and can be shipped without restrictions or extra downloads? http://pysqlite.org Dave Cook From eric_brunel at despammed.com Mon Jun 27 02:49:33 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 27 Jun 2005 08:49:33 +0200 Subject: tkinter radiobutton References: Message-ID: On Sat, 25 Jun 2005 19:34:50 GMT, William Gill wrote: > I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep > references to them in a 2 dimensional list ( rBtns[r][c] ). It works > fine, and I can even make it so only one button per column can be > selected, by assigning each column to an intVar. In many languages a > radiobutton has a property that can be directly read to see if it is > selected on unselected. Tkinter radiobuttons don't seem to have any > such property. Is there any way to look (via the script not the screen) > to determine if it is selected?, or can this only be achieved via > control variables? The value and variable options for a radiobutton seem to be what you're looking for. Here is an example showing how to use them: ---------------------------------------------------------------- from Tkinter import * root = Tk() v = StringVar() Radiobutton(root, text='foo', value='foo', variable=v).pack() Radiobutton(root, text='bar', value='bar', variable=v).pack() def p(): print v.get() Button(root, command=p, text='Print').pack() root.mainloop() ---------------------------------------------------------------- HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From newsgroups at jhrothjr.com Mon Jun 13 07:30:35 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 13 Jun 2005 05:30:35 -0600 Subject: How to use 8bit character sets? References: <42ad11a7$0$24953$9b622d9e@news.freenet.de> Message-ID: <11aqrivp3834200@news.supernews.com> ""Martin v. L?wis"" wrote in message news:42ad11a7$0$24953$9b622d9e at news.freenet.de... > copx wrote: >> For some reason Python (on Windows) doesn't use the system's default >> character set and that's a serious problem for me. > > I very much doubt this statement: Python does "use" the system's default > character set on Windows. What makes you think it doesn't? > >> Is it possible to tell Python to use an 8bit charset (latin-1 in my case) >> for textfile and string processing by default? > > That is the default. As far as I can tell, there are actually two defaults, which tends to confuse things. One is used whenever a unicode to 8-bit conversion is needed on output to stdout, stderr or similar; that's usually Latin-1 (or whatever the installation has set up.) The other is used whenever the unicode to 8-bit conversion doesn't have a context - that's usually Ascii-7. John Roth > > Regards, > Martin From p at ulmcnett.com Thu Jun 9 18:40:10 2005 From: p at ulmcnett.com (Paul McNett) Date: Thu, 09 Jun 2005 15:40:10 -0700 Subject: Start application & continue after app exits In-Reply-To: <86u0k75hgd.fsf@guru.mired.org> References: <86u0k75hgd.fsf@guru.mired.org> Message-ID: <42A8C54A.4020209@ulmcnett.com> Mike Meyer wrote: > "guy lateur" writes: > > >>>>Also note that this method of creating tempfiles is technically unsafe, >>>>as it is theoretically possible that another process would create a file >>>>of the same name in the same directory and then try to use it, resulting >>>>in a race condition between the two processes. This is practically >>>>unlikely, however, and I'm a pragmatist. >> >>I see what you mean, but wouldn't a call to open(fn, 'w') on a filename >>that's in use (for reading or writing) result in an error condition or >>something? I'm a noob, btw. > > > Not necessarily - it depends on the OS. Unix is quite happy to let > multiple processes read/write a file at the same time. > > FWIW, this also means that the methodology as outlined is > insecure. Some other program can read the temporary file as it exists > on the disk, thus disclosing it's contents to unauthorized readers. Right. So we are all adults here and if that matters to your application you've got to find a different way, perhaps by using tmpFile = tempfile.NamedTemporaryFile() instead of tmpFile = tempfile.mktemp() and os.spawnlp(os.P_WAIT, "winword.exe", "winword.exe", tmpFile.name) instead of os.system("winword.exe %s" % tmpFile) but I don't think all (if any) versions of Windows can handle opening that file while we are holding it open already. And I guess it still doesn't make it secure because the file exists on disk and can be read. So I stand by my prior, simpler solution, that will work portably and reliably for all practical purposes, purposeful maliciousness excepted. If you are worried about security, you would't be saving the file to the temp directory in plain text anyway. If there is a portable, reliable, secure, and simple solution that I've overlooked, however, I'm all ears. :) Now, if the OP's requirement is specifically for winword on Windows, a more specific approach could be used that doesn't involve saving any temporary files at all, such as by using COM automation to build the document. But I hate nonportable solutions! :) -- Paul McNett http://paulmcnett.com From sameer_deshpande at hotmail.com Sun Jun 26 10:39:53 2005 From: sameer_deshpande at hotmail.com (sameer_deshpande) Date: 26 Jun 2005 07:39:53 -0700 Subject: Documentation How-to's for cx_Oracle Message-ID: <1119796793.413221.291800@f14g2000cwb.googlegroups.com> Hello, Does anybody have how-to's or good enough detail documentation for cx_Oracle module? Thanks Sameer From skip at pobox.com Mon Jun 13 13:47:10 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 13 Jun 2005 12:47:10 -0500 Subject: case/switch statement? In-Reply-To: <200506131204.40950.hancock@anansispaceworks.com> References: <200506131204.40950.hancock@anansispaceworks.com> Message-ID: <17069.50846.950702.558343@montanaro.dyndns.org> Terry> Yeah, and I find this even more so: Terry> case = { Terry> 5: do_this, Terry> 6: do_that, Terry> } Terry> case.get(x, do_default)() Terry> Which is looking pretty close to a case statement, anyway. Sure, modulo namespace issues. Skip From ptmcg at austin.rr.com Thu Jun 23 15:25:58 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jun 2005 12:25:58 -0700 Subject: trouble subclassing str In-Reply-To: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> Message-ID: <1119554758.513632.87240@z14g2000cwz.googlegroups.com> My first thought is "make sure that subclassing str is really what you want to do." Here is a place where I have a subclass of str that really is a special kind of str: class PaddedStr(str): def __new__(cls,s,l,padc=' '): if l > len(s): s2 = "%s%s" % (s,padc*(l-len(s))) return str.__new__(str,s2) else: return str.__new__(str,s) print ">%s<" % PaddedStr("aaa",10) print ">%s<" % PaddedStr("aaa",8,".") (When subclassing str, you have to call str.__new__ from your subclass's __new__ method, since str's are immutable. Don't forget that __new__ requires a first parameter which is the input class. I think the rest of my example is pretty self-explanatory.) But if you are subclassing str just so that you can easily print your objects, look at implementing the __str__ instance method on your class. Reserve inheritance for true "is-a" relationships. Often, inheritance is misapplied when the designer really means "has-a" or "is-implemented-using-a", and in these cases, the supposed superclass is better referenced using a member variable, and delegating to it. -- Paul From Scott.Daniels at Acm.Org Wed Jun 22 14:44:20 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Jun 2005 11:44:20 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <11bja5bienakv68@corp.supernews.com> References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> Message-ID: <42b9aa1e@nntp0.pdx.net> Grant Edwards wrote: > I'm working on it. I should have said it's trivial if you have > access to the platforms to be supported. I've tested a fix > that supports pickle streams generated under Win32 and glibc. > That's using the "native" string representation of a NaN or > Inf. Several issues: (1) The number of distinct NaNs varies among platforms. There are quiet and signaling NaNs, negative 0, the NaN that Windows VC++ calls "Indeterminate," and so on. (2) There is no standard-conforming way to create these values. (3) There is no standard-conforming way to detect these values. --Scott David Daniels Scott.Daniels at Acm.Org From rex.eastbourne at gmail.com Tue Jun 28 15:38:06 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 28 Jun 2005 12:38:06 -0700 Subject: Debugger Confusion Message-ID: <1119987486.896625.29890@g49g2000cwa.googlegroups.com> I'm a little confused about which debugging utilities do what, and which I should use for my Python code. I'd like to be able to step through my code, insert breakpoints, etc. I haven't been able to do this yet (I'm using Emacs on Windows). I have seen references to GDB, GUD, PDB, and others. Which ones do I need? Thanks, Rex Eastbourne From mwm at mired.org Sun Jun 12 05:26:20 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 12 Jun 2005 04:26:20 -0500 Subject: Best Web dev language References: <11al0nhr4opfgaa@corp.supernews.com> <86br6c4pwp.fsf@guru.mired.org> <11amltm8d7me528@news.supernews.com> Message-ID: <86d5qs2af7.fsf@guru.mired.org> "John Roth" writes: > "Mike Meyer" wrote in message > news:86br6c4pwp.fsf at guru.mired.org... >> "Jon Slaughter" writes: >> >> Someone mentioned that you might "require JavaScript on the client >> side". I recommend against that - people and organizations disable >> JavaScript for security reasons, and browsers on portable devices may >> not have JavaScript at all. Why limit your audience? If you understand >> HTML, it's possible to write a web page that uses JavaScript (or any >> other such technology) for flashy effects, but still functions >> properly if the user has disabled JavaScript, or doesn't have it >> available. But that's a long discussion - see > http://www.mired.org/home/mwm/papers.green.html > for more >> information. > > I would have said that at one time, but then the world changed > with AJAX, expecially with Google using very script heavy applications > for all of their new work. It leads to very responsive web applications. Actually, AJAX just makes the case for wanting JavaScript turned on stronger - it doesn't change the fundamental facts of what's going on. People/organization will still turn off JavaScript because it represents a security risk. Low-end network devices will still have browsers that can't do JavaScript. You can still either code your pages to alienate such users, or you can provide them with the same basic functionality as they'd get if they had JavaScript, except it won't be as responsive/flashy as it would be if they did. Try Googles new work with JavaScript turned off. You'll find that a lot of the new stuff works fine without it, thought it may not be as spiffy. For those that don't, they warn the user that it won't work, which means they are doing better than 90% of the sites that require JavaScript on the web. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From elprodigio at gmail.com Mon Jun 20 03:54:08 2005 From: elprodigio at gmail.com (Didier Casse) Date: 20 Jun 2005 00:54:08 -0700 Subject: Can we pass some arguments to system("cmdline")? References: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> Message-ID: <1119254048.614944.123570@g43g2000cwa.googlegroups.com> Thanks all for the reply. I'll try out those things out. :) Cheers, Didier. Leif K-Brooks a ?crit : > Didier C wrote: > > E.g in Perl, we can do something like: > > > > $dir="/home/cypher"; > > > > system("ls $dir"); > > > > Is there a way to reproduce the same thing in Python? > > system("ls %s" % dir) > > But you should really be using subprocess for security (so that if > dir=="/home/foo; rm -rf /" nothing bad will happen): > > import subprocess > subprocess.Popen(['ls', dir]) From kkzuberi at yahoo.com Thu Jun 9 14:19:21 2005 From: kkzuberi at yahoo.com (Khalid Zuberi) Date: Thu, 09 Jun 2005 14:19:21 -0400 Subject: PIL and GeoTIFF In-Reply-To: References: Message-ID: Matt Feinstein wrote: > Hi all-- > > I've succeeded in using the PIL (Python Imaging Library) to read a > simple GeoTIFF file and to extract data from the file's GeoTIFF key-- > but I'd also like to write GeoTIFFs, and there doesn't appear to be a > one-step way of doing that. > If you are willing to go in a bit of a different direction, GDAL supports GeoTIFF and includes python bindings: http://www.remotesensing.org/gdal/ - kz From steven.bethard at gmail.com Mon Jun 20 20:40:21 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Jun 2005 18:40:21 -0600 Subject: Tuple Unpacking in raise In-Reply-To: References: Message-ID: James Stroud wrote: > Hello All, > > Is this a bug? Why is this tuple getting unpacked by raise? Am I missing some > subtle logic? Why does print not work the same way as raise? Both are > statements. Why does raise need to be so special? > > py> sometup = 1,2 > py> print sometup > (1, 2) > py> print 1,2,3, sometup > 1 2 3 (1, 2) > py> class MyErr(Exception): > ... def __init__(self, atup): > ... Exception.__init__(self, "Error with %s-%s" % atup) > ... > py> raise MyErr, sometup > Traceback (most recent call last): > File "", line 1, in ? > TypeError: __init__() takes exactly 2 arguments (3 given) > py> e = MyErr(sometup) > py> print e > Error with 1-2 Well, it's not a bug, because that's what the documentation says it'll do: "The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor."[1] In the example above (as well as almost all code), there's no need to use the two argument version of raise. You can simply write: raise MyErr(sometup) If you need the three argument version of raise, I believe you can still write it as: raise MyErr(sometup), None, tb Note that Guido has mentioned a few times that in Python 3.0, he wants tracebacks to be attributes of the Exception objects so that all raise statements are like the one argument version. STeVe P.S. If you insist on using the two argument version of raise, you can do it like this: py> class E(Exception): ... def __init__(self, atup): ... Exception.__init__(self, "Error with %s-%s" % atup) ... py> raise E, ((1, 2),) Traceback (most recent call last): File "", line 1, in ? E: Error with 1-2 But that seems a lot less elegant than simply using the one argument version. [1] http://docs.python.org/ref/raise.html From t-meyer at ihug.co.nz Fri Jun 24 22:53:50 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sat, 25 Jun 2005 14:53:50 +1200 Subject: Tracing down segfault Message-ID: I have (unfortunately) a Python program that I can consistently (in a reproducible way) segfault. However, I've got somewhat used to Python's very nice habit of protecting me from segfaults and raising exceptions instead, and am having trouble tracking down the problem. The problem that occurs looks something like this: Program received signal SIGSEGV, Segmentation fault. 0x00a502aa in ?? () (gdb) bt #0 0x00a502aa in ?? () Cannot access memory at address 0x0 Which looks something like accessing a NULL pointer to me. The problem is finding the code that is causing this, so I can work around it (or fix it). Unfortunately, the script uses ZEO, ZODB, threading.Threads, and wx (my code is pure Python, though), and I'm having trouble creating a simple version that isolates the problem (I'm pretty sure it started happening when I switched from thread to threading, but I'm not sure why that would be causing a problem; I am join()ing all threads before this happens). Does anyone have any advice for tracking this down? Thanks! Tony Meyer From faassen at infrae.com Fri Jun 17 08:40:10 2005 From: faassen at infrae.com (Martijn Faassen) Date: Fri, 17 Jun 2005 14:40:10 +0200 Subject: ElementTree Namespace Prefixes In-Reply-To: References: Message-ID: <42b2c45d$0$13986$e4fe514c@news.xs4all.nl> Jarek Zgoda wrote: [snip] >> It's a shame the default ns behavior in Elementtree is in such a poort >> staten. I'm surprised no one's forked Elementtree solely to fix this >> issue. > > There is at least one ElementTree API implementation that retains > prefixes, lxml.ETree. Go google for it. Just to make it explicitly clear, lxml is not a fork of ElementTree fork, but a reimplementation of the API on top of libxml2. ElementTree indeed retains prefixes, and since version 0.7 released earlier this way, it's also possible to get some control over generation of prefixes during element construction. You can find it here: http://codespeak.net/lxml Regards, Martijn From mpellecer at galileo.edu Fri Jun 3 15:16:17 2005 From: mpellecer at galileo.edu (Manuel Pellecer) Date: Fri, 03 Jun 2005 13:16:17 -0600 Subject: mod_python config problem Message-ID: <42A0AC81.2030901@galileo.edu> i want to use mod_python with Apache2 and i made a .htaccess in the subdirectory where i have all my scripts: The .htacces goes like this: AddHandler mod_python .py PythonHandler mptest PythonDebug On and I changed the main configuracion file of Apache2 like this: #--memepelle AllowOverride FileInfo #memepelle-- and i made a mptest.py that goes like this: from mod_python import apache def handler(req): req.content_type = "text/plain" req.write("Hello World!") return apache.OK But i still have this error and i don't know why Mod_python error: "PythonHandler mptest" Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 287, in HandlerDispatch log=debug) File "/usr/lib/python2.4/site-packages/mod_python/apache.py", line 454, in import_module f, p, d = imp.find_module(parts[i], path) ImportError: No module named mptest Please some help!!! From tom at dtsam.com Thu Jun 2 11:41:59 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Thu, 2 Jun 2005 10:41:59 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><7xzmu94wrf.fsf@ruckus.brouhaha.com> Message-ID: <0cadndgTMNDJtQLfRVn-gQ@telcove.net> "Skip Montanaro" wrote in message news:mailman.372.1117682729.18027.python-list at python.org... > > >> Are we talking about a drag-and-drop GUI builder? > Thomas> I am! > > >> What about Glade? > Thomas> Dying to try that. Ask me again in a week. > > I use Glade at work on a regular basis. Took me a few days to get > proficient, and it has some warts, but it sure beats the heck out of > manually creating all those widgets in my Python code. > > Skip Yes. Anything that automates/assists the creation of the user interface is a phenomenal time saver. The task of getting data from and delivering it to a human operator is still the most difficult and time consuming part of creating software. It is so onerous that it tempts one to abandon writing software for organic beings altogether. My reference to Visual Basic was meant to be a poke in the eye. The language itself stinks. BUT - having a robust IDE with keyword tooltip prompts, built in language documentation, robust built in debugging, and most of all - a stable GUI , a standard suite of widgets for interacting with those pesky, error prone humans, the ability to draw these on a form with a mouse and have all that running in minutes! It no longer matters that the language itself smells like 4 day old fish! No amount of linguistic or structural elegance can have as much impact on productivity as the IDE/GUI. It drives me crazy when someone suggests that it might amount to no more than a bit of fluff hardly worth bothering with because when it comes to programming - An excellent IDE/GUI just trumps everything. Thomas Bartkus From phil_nospam_schmidt at yahoo.com Tue Jun 14 17:22:44 2005 From: phil_nospam_schmidt at yahoo.com (phil_nospam_schmidt at yahoo.com) Date: 14 Jun 2005 14:22:44 -0700 Subject: how to use pyparsing for identifiers that start with a constant string Message-ID: <1118784164.619007.74150@g14g2000cwa.googlegroups.com> I am scanning text that has identifiers with a constant prefix string followed by alphanumerics and underscores. I can't figure out, using pyparsing, how to match for this. The example expression below seems to be looking for whitespace between the 'atod' and the rest of the identifier. identifier_atod = 'atod' + pp.Word('_' + pp.alphanums) How can I get pyparsing to match 'atodkj45k' and 'atod_asdfaw', but not 'atgdkasdjfhlksj' and 'atod asdf4er', where the first four characters must be 'atod', and not followed by whitespace? Thanks! From maxerickson at gmail.com Mon Jun 6 14:08:36 2005 From: maxerickson at gmail.com (max) Date: Mon, 06 Jun 2005 18:08:36 -0000 Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: Steven D'Aprano wrote in news:pan.2005.06.06.16.52.03.904880 at REMOVETHIScyber.com.au: > On Mon, 06 Jun 2005 16:12:18 +0000, max wrote: > >> This is one thing that bothers me about the gpl. It essentially >> tries to create 'code as a legal entity'. That is, it gives >> rights not to the creator of some code, but to the code itself. > > Can you please show me where in the GPL it gives rights to the > code itself? Because, frankly, I think you are mistaken. > > Of course, I might be wrong in this instance, and I always > welcome corrections. > >> For me, the fact >> that corporations are considered people by the law is >> ridiculous. > > Ridiculous? I don't think so. Take, for example, Acme Inc. Acme > purchases a new factory. Who owns the factory? The CEO? The > Chairperson of the Board of Directors? Split in equal shares > between all the directors? Split between all the thousands of > shareholders? Society has to decide between these methods. > > (Of course, society can choose to hedge its bets by creating > multiple entities that use different rules, such as partnerships, > trusts, public corporations, limited corporations, etc.) > > None of these alternatives are *wrong*, but they all have various > disadvantages. The legal fiction that corporations are legally > persons is a work-around for these disadvantages, and it works > quite well in many circumstances. To call it ridiculous is, well, > ridiculous. Ownership is a legal fiction in any case, so it is no > more ridiculous to say that a collective entity such as a > corporation owns property than it is to say that an individual > being owns property. > > However, if you wanted to argue that giving corporations all the > privileges of legal personhood with none of the responsibilities > caused more harm than good, I would agree with you. I take it > you've seen "The Corporation"? > I haven't seen "The Corporation", but yes, I was reaching for the priviledges/responsibilities balance. > >> Using a license that ends up doing the same thing with code >> leaves a bad taste in my mouth. > > Of course you are free to use some other licence. But without > evidence, I do not accept that the GPL attempts to give rights to > code. > > Perhaps 'attempts' is too strong a word. Maybe 'ends up giving' would help my argument more. The best example I can come up with at the moment is programmer A releases a project under the gpl. Programmer B makes a substantial contribution to the project, which pA reads through and accepts. Later, pA decides that he would like to release the project under a more liberal license. To me, whether he legally can under the gpl is a very murky subject, as pB might not agree, and pA, having looked through/thought about pB's contribution might have some trouble proving that he implemented any matching functionality without referencing pB's earlier contribution, which if he did reference it(even by memory), would presumably require him to continue using the gpl. I guess my argument is that with multiple contributors, the gpl, in comparison to say, a BSD style license, grants power to the code. If 3 people work on a gpl project, they must agree to any changes. If 3 people work on a BSD style project, they each can do whatever the hell they like with the code. So, in my opinion, the gpl ends up giving perhaps not rights, but certainly power, to the actual code base. Based on the limited coherence of this answer I probably need to think about it somemore, max From steven.bethard at gmail.com Mon Jun 27 15:16:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Jun 2005 13:16:23 -0600 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> Message-ID: Fredrik Johansson wrote: > On 6/27/05, Reinhold Birkenfeld wrote: > >>Do you have any other good and valued Python modules that you would think are >>bug-free, mature (that includes a long release distance) and useful enough to >>be granted a place in the stdlib? > > First of all, numeric/numarray, obviously! There has been recent discussion about this. Check the python-dev list archives I think. It's unlikely that all of numeric/numarray could go into the Python stdlib because there still is disagreement between the two camps as to the module architecture. However, there does seem to be some agreement at the level of the basic array object, so it may be possible that at least the array object itself might join the stdlib in the not too distant future. I suspect there's more detailed discussion of this in the numeric/numarray lists. STeVe From kent37 at tds.net Thu Jun 16 13:44:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jun 2005 13:44:47 -0400 Subject: access properties of parent widget in Tkinter In-Reply-To: References: <42b17114$1_2@newspeer2.tds.net> Message-ID: <42b1ba13$1_2@newspeer2.tds.net> William Gill wrote: > Kent Johnson wrote: > > If I change the area code in one record only the phonenumber table needs > to be updated, but since areaCode is a child of phones, > phones.hasChanged needs to be set to True by the areaCode entry widget. One possibility is for the phones.hasChanged to poll the hasChanged attributes of its children. In other words, instead of propagating hasChanged up when a change occurs, poll the dependent widgets when you need to know. Another way would be to pass a calllback to the child widget that it calls when it is changed, or to set up some kind of event mechanism. In Java I often set the parent to monitor property change events of the child. > > > Personally I think it is bad design for a widget to assume anything > > about its enclosing environment. What about passing a StringVar or > > IntVar to the child widget and letting it work with that? > > This is not a criticism, but how is passing a known intVar or stringVar > any different than designing with the knowledge that an areaCode widget > can not exist except as a child of phonenumber? When you pass a stringVar to the child, it knows only what it is told, it is not assuming that some incantation on its parent will do the right thing. This has a direct effect on reusability of the child in other contexts. You may think you don't want to reuse the child, but it is very handy to be able to make a small test harness for a widget rather than firing up the whole application, navigating to the correct screen, etc. It is much harder to do this if the widget depends on its enclosing environment. And I find that if I design widgets for reuse, other uses tend to come up often enough to make it worth-while. It's not that different from relying on any other global state. It makes code harder to understand, harder to test and harder to reuse. More generally, IMO it is good practice to try to make acyclic dependency graphs between classes and modules, so if the parent depends on the child, the child shouldn't depend on the parent. > Besides, I need to > pass the state of areaCode (has it changed or not), not its value? OK, I misunderstood your original post on that point. Kent > From newsgroups at jhrothjr.com Sat Jun 11 17:29:23 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 11 Jun 2005 15:29:23 -0600 Subject: Best Web dev language References: <11al0nhr4opfgaa@corp.supernews.com> <86br6c4pwp.fsf@guru.mired.org> Message-ID: <11amltm8d7me528@news.supernews.com> "Mike Meyer" wrote in message news:86br6c4pwp.fsf at guru.mired.org... > "Jon Slaughter" writes: > > > Someone mentioned that you might "require JavaScript on the client > side". I recommend against that - people and organizations disable > JavaScript for security reasons, and browsers on portable devices may > not have JavaScript at all. Why limit your audience? If you understand > HTML, it's possible to write a web page that uses JavaScript (or any > other such technology) for flashy effects, but still functions > properly if the user has disabled JavaScript, or doesn't have it > available. But that's a long discussion - see http://www.mired.org/home/mwm/papers.green.html > for more > information. I would have said that at one time, but then the world changed with AJAX, expecially with Google using very script heavy applications for all of their new work. It leads to very responsive web applications. John Roth > > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more > information. From kbilsted at hotmail.com Sun Jun 12 20:00:40 2005 From: kbilsted at hotmail.com (newseater) Date: 12 Jun 2005 17:00:40 -0700 Subject: changing how instances are "created" In-Reply-To: <11api166se4itcc@news.supernews.com> References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> <11api166se4itcc@news.supernews.com> Message-ID: <1118620840.352981.60420@g14g2000cwa.googlegroups.com> > > class Creator > > def createInstance(cls, *args, **kwargs): > > anewinstance = cls.__new__(cls, *args, **kwargs) > > anewinstance.__init__(*args, **kwargs) > > > > return anewinstance > > createInstance = staticmethod(createInstance) > > > > > > can anyone help?? > > __new__ is the proper way to do this, but making it work > is a bit tricky. If you could post the code you tried to > get to work for __new__(), we could critique it. > > The current documentation is in 3.3.1 of the Python > Reference Manual (Python 2.4 version). In earlier > versions, there were a couple of other documents > that did a better (IMO) job of explaining things. > > The trick is that __new__ must return an instance. > It can be a newly created instance (and the doc shows > how to do this) or an existing instance of any new style > class. from the documentation it was very hard to guess what the "..." was supposed to be. also i wasn't able to find out how to control if __init__() would be called on an instance (if i reused that instance.. and that instance could be of a completely different type). eg. i didn't get much out of http://docs.python.org/ref/customization.html from http://gnosis.cx/publish/programming/metaclass_1.html i get >>> class ChattyType(type): ... def __new__(cls, name, bases, dct): ... print "Allocating memory for class", name ... return type.__new__(cls, name, bases, dct) ... def __init__(cls, name, bases, dct): ... print "Init'ing (configuring) class", name ... super(ChattyType, cls).__init__(name, bases, dct) ... >>> X = ChattyType('X',(),{'foo':lambda self:'foo'}) Allocating memory for class X Init'ing (configuring) class X >>> X, X().foo() (, 'foo') but that way of creating objects is just plain silly! (the X = Chattype('X'.....) and where are the arguments to __init__() passed?? maybe i want to change those as well.... this is partly why i wanted to use an external class for the creation. I tried looking at the __new__ buildin but this seems to be addressing old-style objects (which i'm not interested in using) > > By the way - when you post code, please use spaces > for indentation. There are a number of popular mail > clients that don't play fair with tabs, and people using > these clients will frequently ignore code that isn't > properly indented. sorry. maybe people should complain to those lousy newsreader authors instead of everyone having to comply to the lowest standards? I guess the readers are actually un*x readers although your comment typically is found in the w*ndows world where everyone is forced into using word :-) > John Roth From gdamjan at gmail.com Wed Jun 29 09:18:10 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 29 Jun 2005 15:18:10 +0200 Subject: MySQLdb reconnect References: <42b9a0d0_2@x-privat.org> Message-ID: <42c29f64_3@x-privat.org> > Does MySQLdb automatically reconnect if the connection to the database is > broken? It seems so. > I'm asking this since I have a longrunning Python precess that is > connected to Mysql-4.1.11, and I execute "set names utf8" when I connect > to it. > > But after running a day the results from the python program were displayed > as if the "set names utf8" was not executed i.e. I got question marks > where utf-8 cyrillics should've appeared. After restarting the Python > program everything was ok, just as when I first started it. This is the sollution I've come to: try: # This will fail on MySQL < 4.1 db = MySQLdb.connect(godot.dbhost, godot.dbuser, godot.dbpass, godot.dbname, use_unicode=1, init_command="set names utf8") except MySQLdb.OperationalError: db = MySQLdb.connect(godot.dbhost, godot.dbuser, godot.dbpass, godot.dbname, use_unicode=1) db.charset = 'utf8' -- damjan From onurb at xiludom.gro Tue Jun 7 06:05:59 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 07 Jun 2005 12:05:59 +0200 Subject: reg php.ini equivalent file in python In-Reply-To: References: Message-ID: <42a57188$0$8116$626a14ce@news.free.fr> praba kar wrote: > Dear All, > > I have one doubt. Is there python.ini > file like php.ini in Php? bruno at localhost ~ $ python -h usage: python [option] ... [-c cmd | file | -] [arg] ... (snip) PYTHONSTARTUP: file executed on interactive startup (no default) (snip) I guess this is the closer thing. > Actually php.ini file controls many aspects of > PHP's behavior. The following details of php.ini > will explain about it. > > max_execution_time = 5000 ; Maximum execution time > of each script, in seconds (UNIX only) > > memory_limit = 134217728 ; Maximum amount of > memory a script may consume (128MB) > > post_max_size = 67108864 ; Maximum POST-Content > length (64MB) All those settings are somewhat web-specific, and would not have much meaning in most Python usages. > If I want to update the above details in Python where > I need to change these things in Python This (if possible) depends on the web developpement solution you use (cgi, mod_python, CherryPy, Webware, Zope, other...). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grumman at example.com Sun Jun 12 22:40:22 2005 From: grumman at example.com (Grumman) Date: Sun, 12 Jun 2005 22:40:22 -0400 Subject: searching for IDE In-Reply-To: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: alexrait1 wrote: > I need an IDE for python that has the ability to show the filds of a > class when I write "." > Just the way it works in eclipse/JBuilder with java or visual studio > with c++ > For now I treid eric3 and IDLE they don't do this... > The ActiveState python editor (pythonwin?) does this. From peter at engcorp.com Fri Jun 24 07:25:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 07:25:48 -0400 Subject: Help wanted in piping in Windows In-Reply-To: References: Message-ID: Thomas Guettler wrote: > AFAIK ">file" and "2>file" does work on windows. Not, unfortunately (at least in the past), on Windows 98. That might no longer matter, however. How many people are still stuck using Windows 98? Given that in one year you won't even be able to get support from Microsoft's update site (such as if you have to reinstall), isn't it time to move on? to Linux... -Peter From robin at SPAMREMOVEjessikat.fsnet.co.uk Sun Jun 5 10:50:17 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sun, 05 Jun 2005 14:50:17 +0000 Subject: Q: functional/equational language, smells a little of Python In-Reply-To: <87k6l8lv77.fsf@pobox.com> References: <871x7hn5za.fsf@pobox.com> <1117959822.889652.257290@g44g2000cwa.googlegroups.com> <87k6l8lv77.fsf@pobox.com> Message-ID: <42A31129.2080106@jessikat.fsnet.co.uk> John J. Lee wrote: .... > > What's a fast object library? > ferrarilib :) -- Robin Becker From skromta at gmail.com Tue Jun 14 03:31:15 2005 From: skromta at gmail.com (Kalle Anke) Date: Tue, 14 Jun 2005 09:31:15 +0200 Subject: How to get/set class attributes in Python References: <0001HW.BED3BE5000197B71F0488550@news.individual.de> Message-ID: <0001HW.BED45463001BCED9F0488550@news.individual.de> On Tue, 14 Jun 2005 06:40:51 +0200, Terry Hancock wrote (in article ): > I find the biggest problem coming to Python from a language > like C, C++, or Java is that you overthink things and try to > do them the hard way. A lot of times, you find out that the > "Python way" to do the thing is so blindingly obvious that > it just didn't occur to you that it could be that simple. It's very possible that this is the case, I'm not experienced enough in Python yet to have a opinion on this yet. I tend to think in terms of larger systems with several programmers ... instead of what I'm actually doing writing code for my own pleasure. But I'm learning new stuff every day ... so in 6 months I'll probably have an opinion. From bootsch at acm.org Tue Jun 21 06:00:02 2005 From: bootsch at acm.org (Paul Boots) Date: Tue, 21 Jun 2005 12:00:02 +0200 Subject: ZEO client hangs when combined with other asyncore code Message-ID: Dear people, We have an application that makes use of a ZEO client and has other async socket code that implements as POP3 proxy. The ZEO client is called (to query and store ZEO server) from within the proxy code when it runs during mail checks, so we have multiple async connections at the same time. Somehow, a call to the ZEO client never returns, it just hangs and sits there. In an attempt to fix this problem we added code to use a different socket map for the proxy objects, the ZEO client uses the default asyncore socket_map. But that did NOT solve our problem. At this point we are clueless to the reason behind this behaviour and hope that anyone on this list has some ideas or similar experiences. I realize this is a very terse description of our application, when necessary I can elaborate. -- Best regards, Paul Boots From ods at strana.ru Tue Jun 21 08:32:31 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 21 Jun 2005 16:32:31 +0400 Subject: Embedding Python - Deleting a class instance In-Reply-To: References: Message-ID: <20050621163231.418002fe@ods.pravda.rfn.ru> On Tue, 21 Jun 2005 12:06:47 GMT "Bue Krogh Vedel-Larsen" wrote: > How do I delete a class instance created using PyInstance_New? I've tried > calling Py_CLEAR on the instance, but __del__ isn't called. I've also tried > calling PyObject_Del, but this gives an access violation in > _PyObject_DebugDumpAddress so I guess that ain't a good idea :) It is deleted automatically when reference count become zero or when garbage collector runs if the object contains references to itself. Just call Py_DECREF on it if you are not going to use it anymore. > I've noticed that the PyObject returned by PyInstance_New has refcount = 2, > does this have any significance? The code below prints 1: PyObject *obj = PyInstance_New(PyExc_Exception, 0, 0); std::cerr << obj->ob_refcnt << "\n"; Does it create circular references in constructor? -- Denis S. Otkidach http://www.python.ru/ [ru] From philippe at philippecmartin.com Mon Jun 20 12:13:12 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 16:13:12 GMT Subject: Python choice of database References: Message-ID: > 1. 5000 files -- my personal favourite. You got a point William Park wrote: > Philippe C. Martin wrote: >> Hi, >> >> I am looking for a stand-alone (not client/server) database solution >> for Python. >> >> 1) speed is not an issue >> 2) I wish to store less than 5000 records >> 3) each record should not be larger than 16K >> >> As I start with Python objects, I thought of using shelve, but looking >> at the restrictions (record size + potential collisions) I feel I >> should study my options a bit further before I get started. > > Possible approach might be: > 1. 5000 files -- my personal favourite. > 2. GDBM > 3. SQLite > From rodriwOh at gmail.com Mon Jun 6 22:04:00 2005 From: rodriwOh at gmail.com (Rod Castellanos) Date: 6 Jun 2005 19:04:00 -0700 Subject: PSP / mod_python ... how to get POST vars on .psp ? Message-ID: Ive been looking everywhere, I need to get a var in my .psp file from another one, I managed to send it with a form and I can read it with "req.read" but it reads all of the variables together separated by a "&" like all POST/GET vars. How do I store each one in a python var, Im looking for something like $_POST and $_GET from php. Thanx. From deets at web.de Mon Jun 20 18:00:32 2005 From: deets at web.de (Diez B. Roggisch) Date: Tue, 21 Jun 2005 00:00:32 +0200 Subject: Python and encodings drives me crazy In-Reply-To: References: <6f7b52d05062013545cbc435d@mail.gmail.com> Message-ID: <3hosk2FhhjonU1@uni-berlin.de> Oliver Andrich wrote: > Well, I narrowed my problem down to writing a macroman or cp850 file > using the codecs module. The rest was basically a misunderstanding > about codecs module and the wrong assumption, that my input data is > iso-latin-1 encode. It is UTF-8 encoded. So, curently I am at the > point where I have my data ready for writing.... > > Does the following code write headline and caption in MacRoman > encoding to the disk? Or better that, is this the way to do it? > headline and caption are both unicode strings. > > f = codecs.open(outfilename, "w", "macroman") > f.write(headline) > f.write("\n\n") > f.write(caption) > f.close() looks ok - but you should use u"\n\n" in general - if that line for some reason chages to "???" (german umlauts), you'll get the error you already observed. But using u"???" the parser pukes at you when the specified coding of the file can't decode that bytes to the unicode object. Most problems occdure when one confuses unicode objects with strings - this requires a coercion that will be done using the default encoding error you already observed. Diez From xah at xahlee.org Sat Jun 18 02:21:55 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jun 2005 23:21:55 -0700 Subject: tree functions daily exercise: Table In-Reply-To: <1118616178.259864.187180@g44g2000cwa.googlegroups.com> References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> Message-ID: <1119075715.004033.169450@g14g2000cwa.googlegroups.com> The Perl version of the Tree function is posted. It's a bit long. Please see the code here: http://xahlee.org/tree/Table.html the choice of having a string as the first argument to Table is a bit awkward in Perl. Possibly i'll have to rewrite it so that the first argument is a function instead, where in each iteration the the variables are fed to the function. This necessarily breaks the Mathematica's syntactical form of Table, and is slightly less flexible in power, but is more natural and practical in non-symbolic languages like Perl, Python, Java. I think the goal of the whole tree functions project http://xahlee.org/tree/tree.html would make the code actually practically useful for processing trees in each language, as opposed to sticking to uniformness of these functions across languages. later on, as we write more tree functions, the whole set will be very useful in processing tree structures, such as XML and many other things spurn from it today. Disclaimer: this project is not affiliated with Wolfram Research Inc. Xah xah at xahlee.org ? http://xahlee.org/ From darkpaladin79 at hotmail.com Thu Jun 9 12:38:12 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 12:38:12 -0400 Subject: Exe file In-Reply-To: Message-ID: >From: "Philip Seeger" >To: python-list at python.org >Subject: Exe file >Date: Thu, 9 Jun 2005 18:24:15 +0200 > >Hi @ll > >I'm sorry for that newbie question but how can I compile a program (a .py >file) to an executable file? > >-- >Philip Seeger > > Yes there is and its very easy, simplely use the Freeze program. You can google it and download it, just run it and it will complile an exe for you, with a dll. Run it like any other apllication. -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kent37 at tds.net Sat Jun 4 21:42:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 21:42:16 -0400 Subject: Newbie Python & XML In-Reply-To: <1117899758.058056.291670@g47g2000cwa.googlegroups.com> References: <1117899758.058056.291670@g47g2000cwa.googlegroups.com> Message-ID: <42a25838$1_2@newspeer2.tds.net> LenS wrote: > I have a situation at work. Will be receiving XML file which contains > quote information for car insurance. I need to translate this file > into a flat comma delimited file which will be imported into a software > package. Each XML file I receive will contain information on one quote > only. I have documentation on layout of flat file and examples of XML > file (lot of fields but only container tags and field tags no > DTD's,look easy enough). I am just starting to learn python and have > never had to work with XML files before. Working in MS Windows > environment. I have Python 2.4 with win32 extensions. > > 1. What else do I need I recommend ElementTree for XML processing in Python http://effbot.org/zone/element-index.htm and the Python-tutor mailing list for getting started with Python: http://mail.python.org/mailman/listinfo/tutor Kent From see at sig.for.address.edu Fri Jun 24 10:34:35 2005 From: see at sig.for.address.edu (Doug Schwarz) Date: Fri, 24 Jun 2005 14:34:35 GMT Subject: Favorite non-python language trick? References: Message-ID: In article , "Enrico" wrote: > "Joseph Garvin" ha scritto nel messaggio > news:mailman.837.1119596150.10512.python-list at python.org... > > --This code won't run because it's in a comment block > > --[[ > > print(10) > > --]] > > > > --This code will, because the first two dashes make the rest a comment, > > breaking the block > > ---[[ > > print(10) > > --]] > > > > So you can change whether or not code is commented out just by adding a > > dash. This is much nicer than in C or Python having to get rid of """ or > > /* and */. Of course, the IDE can compensate. But it's still neat :) > > python: > > """ > print 10 > """ > > and > > #""" > print 10 > #""" It seems to me that this trick works in Python,too. """ print 10 #""" and #""" print 10 #""" You only have to change the first triple quote. -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. From eric_brunel at despammed.com Tue Jun 28 08:42:18 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 28 Jun 2005 14:42:18 +0200 Subject: Python 2.1 / 2.3: xreadlines not working with codecs.open References: Message-ID: On Thu, 23 Jun 2005 14:23:34 +0200, Eric Brunel wrote: > Hi all, > > I just found a problem in the xreadlines method/module when used with codecs.open: the codec specified in the open does not seem to be taken into account by xreadlines which also returns byte-strings instead of unicode strings. > > For example, if a file foo.txt contains some text encoded in latin1: > >>>> import codecs >>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace') >>>> [l for l in f.xreadlines()] > ['\xe9\xe0\xe7\xf9\n'] > > But: > >>>> import codecs >>>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace') >>>> f.readlines() > [u'\ufffd\ufffd'] > > The characters in latin1 are correctly "dumped" with readlines, but are still in latin1 encoding in byte-strings with xreadlines. Replying to myself. One more funny thing: >>> import codecs, xreadlines >>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace') >>> [l for l in xreadlines.xreadlines(f)] [u'\ufffd\ufffd'] So f.xreadlines does not work, but xreadlines.xreadlines(f) does. And this happens in Python 2.3, but also in Python 2.1, where the implementation for f.xreadlines() calls xreadlines.xreadlines(f) (?!?). Something's escaping me here... Reading the source didn't help. At least, it does provide a workaround... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From jepler at unpythonic.net Wed Jun 22 12:27:06 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 22 Jun 2005 11:27:06 -0500 Subject: PEP ? os.listdir enhancement In-Reply-To: References: Message-ID: <20050622162704.GA26783@unpythonic.net> Why not just define the function yourself? Not every 3-line function needs to be built in. def listdir_joined(path): return [os.path.join(path, entry) for entry in os.listdir(path)] dirs = [x for x in listdir_joined(path) if os.path.isdir(x)] path_size = [(x, getsize(x)) for x in listdir_joined(path) if os.path.isfile(x)] Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From elmo13 at jippii.fi Sat Jun 25 18:04:48 2005 From: elmo13 at jippii.fi (=?ISO-8859-1?Q?Elmo_M=E4ntynen?=) Date: Sun, 26 Jun 2005 01:04:48 +0300 Subject: A strange and annoying restriction, possibly a bug. A glance by a more experienced would be nice. Message-ID: <42BDD500.4060303@jippii.fi> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 This is the case: >>> n=(100,) tuple(*n) Traceback (most recent call last): File "", line 1, in -toplevel- tuple(*n) TypeError: iteration over non-sequence To be sure I searched for ways to check if something is a sequence: >>> n.__iter__().next() 100 >>> n.__getitem__(0) 100 >>> iter(n).next() 100 So as you see, as far as I can see, I gave a sequence, but the Traceback says the opposite. To me it seems like a bug, but I haven't filed any bugs before, so a little help wouldn't be bad. I haven't checked if there is bug for this, but I don't consider me finding a bug as obvious as this very propable and something like this not to be fixed a long time ago. I tried this with python 2.3 and 2.4. If possible, could you send any anwsers to my own address also. Thanks in advance. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFCvdUActNFyQJObrsRAha+AJ9oEyL7sufkXCcsQxuMDvyxNqvGGACglBrF le8HmOgXAyRqAY3DASArjM4= =F9NR -----END PGP SIGNATURE----- From jhefferon at smcvt.edu Tue Jun 14 07:41:45 2005 From: jhefferon at smcvt.edu (Jim) Date: 14 Jun 2005 04:41:45 -0700 Subject: Learning more about "The Python Way" In-Reply-To: References: Message-ID: <1118749305.876610.33970@g44g2000cwa.googlegroups.com> Have you seen the Zen of Python http://www.python.org/peps/pep-0020.html ? Like a lot of humor, it has a lot of truth in it. Jim From dan.eloff at gmail.com Sun Jun 12 15:34:49 2005 From: dan.eloff at gmail.com (dan.eloff at gmail.com) Date: 12 Jun 2005 12:34:49 -0700 Subject: How to test if an object IS another object? Message-ID: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> If two objects are of equal value you can compare them with ==. What I want to do is find out if two objects are actually just references to the same object, how can I do this in Python? Thanks From sjmachin at lexicon.net Tue Jun 14 18:59:23 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 15 Jun 2005 08:59:23 +1000 Subject: Cause for using objects? In-Reply-To: References: Message-ID: <42AF614B.7020005@lexicon.net> John Heasly wrote: > >> John Heasly wrote: >> >>> Given: >>> [{"mugshot": "nw_gradspeaker4_0608", "width": 67.0, "height": >>> 96.0}, \ >>> {"mugshot": "nw_gradspeaker2_0608", "width": 67.0, "height": >>> 96.0}, \ >>> {"freehand": "b1.developreport.0614", "width": 154.0, "height": >>> 210.0}, \ >>> {"graphic": "bz_cafeparadiso_0613", "width": 493.0, "height": >>> 341.0}] >>> >>> Return: >>> {"mugshot1": "nw_gradspeaker4_0608", "mugshot1.width": 67.0, >>> "mugshot1.height": 96.0,\ >>> "mugshot2": "nw_gradspeaker2_0608", "mugshot2.width": 67.0, >>> "mugshot2.height": 96.0, \ >>> "freehand1": "b1.developreport.0614", "freehand1.width": 154.0, >>> "freehand1.width": 210.0, \ >>> "graphic1": "bz_cafeparadiso_0613", "graphic1.width": 493.0, >>> "graphic1.height": 341.0} >>> >>> I'm trying to teach myself some OOP. Does grinding the Given above into >>> the Return seem like a good candidate? >> >> >> If that's all you're doing, and you must use that output format, then >> I'd say no. OOP is not a panacea. >> >> Now if you're going to *do* something with the return information, then >> I would say yes. But in that case, don't use a single dict as a return, >> use objects. >> -- >> Michael Hoffman > > > Michael, > > Thanks. I'm thinking maybe list comprehension is a more appropriate > tool. And I need to keep the return a single dict 'cause that's what the > next step in the process expects. > > John > All that means is that the next step in the process also needs an attitude transplant :-) From fabioz at esss.com.br Wed Jun 29 12:34:23 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Wed, 29 Jun 2005 13:34:23 -0300 Subject: ANN: PyDev 0.9.5 released In-Reply-To: References: <42A720BD.5050701@esss.com.br> Message-ID: <42C2CD8F.6090009@esss.com.br> Most things do work, but some still seem to have problems with version 3.1 (and thus it is still not officially supported - but should be, not long from now). Cheers, Fabio Dave Cook wrote: >On 2005-06-28, Fabio Zadrozny wrote: > > > >>PyDev - Python IDE (Python Development Enviroment for Eclipse) version >>0.9.5 has just been released. >> >> > >Does it work with the newly released Eclipse 3.1? > >Dave COok > > -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com From almad at include.cz Tue Jun 14 12:15:27 2005 From: almad at include.cz (Almad) Date: Tue, 14 Jun 2005 18:15:27 +0200 Subject: ZCatalog for standalone Zodb? References: Message-ID: Thomas Guettler wrote: > Hi, Hi, > There was someone who said that he has ported ZCatalog to "standalone" > ZODB. Look in the archive of zodb-dev. Thanks, I'll try. > AFAIK IndexedCatalog is still in > development. Maybe the mailing list is calm, but I think it is not > orphaned. As developers on #async told me, they are not using IC for their product any more. So, They will fix reported bugs, but not adding new features. > HTH, > Thomas Thanks, -- Lukas "Almad" Linhart [:: http://www.almad.net/ ::] From mithrandir42 at web.de Thu Jun 2 13:52:24 2005 From: mithrandir42 at web.de (N. Volbers) Date: Thu, 02 Jun 2005 19:52:24 +0200 Subject: python 2.4: tarfile tell() and seek() seem to be broeken References: Message-ID: Am Thu, 02 Jun 2005 17:57:20 +0200 schrieb Lars Gust?bel: > On Wed, 01 Jun 2005 14:58:23 +0200, N. Volbers wrote: > >> - subsequent calls of fd.readline() and fd.tell() will yield the correct >> lines but always the same value from fd.tell(). [...] > > Thank you for pointing that out. I'll take care of this getting fixed. Thanks for taking care of it ;-) From siyer at Princeton.EDU Fri Jun 24 10:21:01 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Fri, 24 Jun 2005 10:21:01 -0400 Subject: Frame widget (title and geometry) Message-ID: <785a1e003cabc.42bbde8d@Princeton.EDU> Hi, I am still new to Python and Tkinter, so I apologize in advance if I do not word my question optimally. I am trying to use a frame widget as the parent for other widgets. There is a class with the header "class classtitle(Frame):" in a script called classtitle.py. Having imported classtitle, I create a Frame widget within my gui using the command "w = Frame(self)." Then, I grid this widget and issue the command "classinstance = classtitle.classtitle(w)." When I attempt to execute this code, I receive an error claiming that w lacks geometry and title attributes that the code in classtitle.py attempts to access. Does this mean that I cannot use a Frame widget as w in this situation? Thanks for your help. Shankar From arazavi at swen.uwaterloo.ca Mon Jun 13 18:51:29 2005 From: arazavi at swen.uwaterloo.ca (Ali Razavi) Date: Mon, 13 Jun 2005 18:51:29 -0400 Subject: implicit variable declaration and access In-Reply-To: References: Message-ID: Tom Anderson wrote: > On Mon, 13 Jun 2005, Ali Razavi wrote: > >> Is there any reflective facility in python that I can use to define a >> variable with a name stored in another variable ? >> >> like I have : >> x = "myVarName" >> >> what can I do to declare a new variable with the name of the string >> stored in x. And how can I access that implicitly later ? > > > Are you absolutely sure you want to do this? > > tom > Have you ever heard of meta programming ? I guess if you had, it wouldn't seem this odd to you. From philippe at philippecmartin.com Wed Jun 8 12:33:49 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 08 Jun 2005 16:33:49 GMT Subject: circular import Module References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Message-ID: That's the only way out I found with some module import problem using code generated by wxDesigner. Josef Meile wrote: >>>Circular import does not work on module level, but you can >>>import the module in a method: >>> >>>file1.py: >>>import file2 >>>.... >>> >>> >>>file2.py: >>># import file1 # Does not work! >>>def foo(): >>> import file1 # Does work >> >> >> Cool idea ! >> >> It works on local namespaces, wich dont cause trouble to the whole >> program. >> >> +1 > Yes, I also think is a good solution. Once I needed to do something like > that and ended by writting a third module with the shared functions that > the two conflicting modules needed. At that time I already knew that one > could import modules from functions; however, I didn't come up with that > solution :-( > > Regards, > Josef From barney.dalton at gmail.com Mon Jun 6 18:33:19 2005 From: barney.dalton at gmail.com (barney) Date: 6 Jun 2005 15:33:19 -0700 Subject: file permissions on windows XP (home) Message-ID: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> I'm trying to write to an existing file under windows XP (home). The files are in 'My Music' which I think may be treated in some special way under XP. The relevant python code is as follows: os.chdir(dir) os.chmod(filename, 0744) print "Okay to write = "+str(os.access(filename, os.W_OK)) afile = file(filename, 'r+b') When I run this I get the following console output: Okay to write = True Traceback (most recent call last): File "c:\temp\eyed3-0.6.6\src\test.py", line 28, in ? processFiles(root,files) File "c:\temp\eyed3-0.6.6\src\test.py", line 24, in processFiles afile = file(filename, 'r+b') IOError: [Errno 13] Permission denied: "02 - New Year's Day.mp3" If I look at the files in explorer then the read only flag is not set. If I change to cygwin and then do an ls -l I get something like: -r--r--r-- 1 Barney None 4142103 Feb 28 1999 02 - New Year's Day.mp3 If I do a chmod 644 from bash first then the python works fine? I'm at a loss to understand what is going on. Why is python returing True from os.access? Why isn't chmod doing anything? Why is cygwin able to sort the problem out? Thanks Barney p.s. I'm using ActiveState Python 2.4 From philippe at philippecmartin.com Fri Jun 10 09:39:34 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 10 Jun 2005 13:39:34 GMT Subject: Generating HTML from python References: <1118342111.655843.85940@o13g2000cwo.googlegroups.com> Message-ID: PS: Just wanted to add that HTMLGen works very well and outputs html that wxHtmlEasyPrinting and my email client have not problem reading (I output student grades, missing assignments, ... in tables). The one gitch is they do not have any installation program (that I've seen) for windows. Regards, Philippe Walter D?rwald wrote: > Cappy2112 wrote: >> I looked at HTMLGen a while ago- I didn't see what the advantage was. >> I wrote soem code similar to the example above, to generate a page.. >> It worked out fine. >> >> However, I want to add HTML ouput to many of my other python programs, >> and I don't want to re-write this for each program. So some higher >> level of abastraction is needed, but I don't know how just yet. >> >> HTMLGen is no longer maintained, so I don't know what the best choice >> is. > > If you want an alternative to HTMLGen that is still maintained, you > might want to try XIST (http://www.livinglogic.de/Python/xist) > > A few simple examples can be found here: > http://www.livinglogic.de/Python/xist/Examples.html > > Bye, > Walter D?rwald From me at privacy.net Wed Jun 8 08:22:39 2005 From: me at privacy.net (Dan Sommers) Date: 08 Jun 2005 08:22:39 -0400 Subject: OO re-factoring (was Pythonese/Efficiency/Generalese critique [on Tutor]) References: Message-ID: On Wed, 8 Jun 2005 00:52:06 -0400, Lee Cullens wrote: > ... My thinking is that class/subclass method instances would replace > the recursive functions approach, but have as yet not formed the > coding in my mind. I don't remember the original post, but methods and recursion are *not* mutually exclusive (e.g., an Integer class with a factorial method, or a binary tree class whose nodes are also binary trees). Regards, Dan -- Dan Sommers From siona at chiark.greenend.org.uk Tue Jun 14 07:38:13 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 14 Jun 2005 12:38:13 +0100 (BST) Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: Fredrik Lundh wrote: >Ron Adam wrote: >> True, but I think this is considerably less clear. The current for-else >> is IMHO is reversed to how the else is used in an if statement. >nope. else works in exactly the same way for all statements that >support it: if the controlling expression is false, run the else suite >and leave the statement. For example, consider the behaviour of: condition = False if condition: print "true" else: print "false" and condition = False while condition: print "true" break else: print "false" >From this, it's clear that while/else gets its semantics from if/else. Then: i = 0 while i < 10: print i i += 1 else: print "Done!" for i in range(10): print i else: print "Done!" So for/else behaves while/else, hence for/else really is the same way round as if/else. It may not be "intuitive", but it's consistent, and personally I'd rather have that. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From smitty_one_each at bigfoot.com Fri Jun 17 19:24:26 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Fri, 17 Jun 2005 18:24:26 -0500 Subject: Regex for repeated character? References: <5J9se.136$Q75.39412@newshog.newsread.com> Message-ID: <87wtosa7o5.fsf@bigfoot.com> >>>>> "Leif" == Leif K-Brooks writes: Leif> How do I make a regular expression which will match the same Leif> character repeated one or more times, instead of matching Leif> repetitions of any (possibly non-same) characters like ".+" Leif> does? In other words, I want a pattern like this: >>>> re.findall(".+", "foo") # not what I want Leif> ['foo'] >>>> re.findall("something", "foo") # what I want Leif> ['f', 'oo'] Do you mean: http://www.python.org/doc/current/lib/re-syntax.html {m} Specifies that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six "a" characters, but not five. {m,n} Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 "a" characters. Omitting m specifies a lower bound of zero, and omitting n specifies an infinite upper bound. As an example, a{4,}b will match aaaab or a thousand "a" characters followed by a b, but not aaab. The comma may not be omitted or the modifier would be confused with the previously described form. {m,n}? Causes the resulting RE to match from m to n repetitions of the preceding RE, attempting to match as few repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string 'aaaaaa', a{3,5} will match 5 "a" characters, while a{3,5}? will only match 3 characters. HTH, Chris From google at binarystar.org Thu Jun 30 06:02:26 2005 From: google at binarystar.org (binarystar) Date: 30 Jun 2005 03:02:26 -0700 Subject: Control Printer Queue On Windows 2000/XP Message-ID: <1120125746.630192.308880@g49g2000cwa.googlegroups.com> Hi folks, I am writing a script to print a few thousand pdf documents and I need to have some control over the number of jobs that are sent to the printer queue at time ... something along the lines of if number_jobs > MAX_JOBS: time.sleep(10) else: #Print More Files I have been investigating the win32print utility http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32print.html ... but can not see how to get print queue information eg the number of jobs pending .. atleast my attempts are failing any ideas?? thx in advance ** From edwardbunt at gmail.com Wed Jun 22 10:52:31 2005 From: edwardbunt at gmail.com (MisterBuntMan) Date: 22 Jun 2005 07:52:31 -0700 Subject: Need Python web hosting ASAP In-Reply-To: References: Message-ID: <1119451951.353745.265900@z14g2000cwz.googlegroups.com> textdrive.com From philipseeger at yahoo.de Fri Jun 10 07:40:38 2005 From: philipseeger at yahoo.de (Philip Seeger) Date: Fri, 10 Jun 2005 13:40:38 +0200 Subject: Exe file References: Message-ID: For easier distribution. Otherwise the client computer had to have Python installed. Philip "Peter Hansen" schrieb im Newsbeitrag news:l76dnYzoqt8iFTXfRVn-rA at powergate.ca... > Philip Seeger wrote: >> I'm sorry for that newbie question but how can I compile a program (a .py >> file) to an executable file? > > To save you what might be much wasted time on a wild goose chase, could > you please tell us why you want to do this? (performance, protection from > prying eyes, easier distribution, or some other reason?) > > -Peter From xah at xahlee.org Sun Jun 19 18:00:01 2005 From: xah at xahlee.org (Xah Lee) Date: 19 Jun 2005 15:00:01 -0700 Subject: functions with unlimeted variable arguments... In-Reply-To: <7xr7f0yv0c.fsf@ruckus.brouhaha.com> References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> <7xr7f0yv0c.fsf@ruckus.brouhaha.com> Message-ID: <1119218400.989803.230410@g47g2000cwa.googlegroups.com> oops... it is in the tutorial... sorry. though, where would one find it in the python reference? i.e. the function def with variable/default parameters. This is not a rhetorical question, but where would one start to look for it in the python ref? a language is used by programers. Subroutine definition with variable/default parameters is a basic issue a programer wants to know, and different languages differs very much in how they handle this. This is what i mean that the language doc should be programing oriented, as opposed to computer-sciency or implementation oriented... Xah xah at xahlee.org ? http://xahlee.org/ From hancock at anansispaceworks.com Thu Jun 23 14:48:33 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 23 Jun 2005 13:48:33 -0500 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: <1119540719.150128.66470@g14g2000cwa.googlegroups.com> References: <42b99d7b$0$21804$626a14ce@news.free.fr> <1119540719.150128.66470@g14g2000cwa.googlegroups.com> Message-ID: <200506231348.33613.hancock@anansispaceworks.com> On Thursday 23 June 2005 10:31 am, Singletoned wrote: > Rocco Moretti wrote: > > Steven D'Aprano wrote: > > > > That's the joys of a mostly self-taught programming knowledge: you miss > > > out on all the buzzwords. > > > > Being mostly self taught myself, I have a tendancy to use infrequently > > encountered terms in related but technically inappropriate contexts, > > confusing the better informed people I deal with. ;-) > > Indeed. I find I use even more buzzwords because I can just make up as > many as I want. As fun as that is ;-), it does make it hard to communicate. It seems to me that I spend a lot of time trying to figure out what buzzwords mean, only to find that 9/10ths of them are for things I've already done somewhere. Of course, that 10th one can be a doozy, "metaclasses" comes to mind. And it does make it easier to find help on problems, if you know what other people call them. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From bvande at po-box.mcgill.ca Tue Jun 28 11:24:25 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 28 Jun 2005 11:24:25 -0400 Subject: How to compress a folder and all of its sub directories and filesinto a zip file? In-Reply-To: References: <311b5ce105062723167e892833@mail.gmail.com> <42C188F3.7010704@rt.sk> <311b5ce1050628002075da2e3@mail.gmail.com> <311b5ce10506280029682b9366@mail.gmail.com> <42C0FFCC.8030708@po-box.mcgill.ca> Message-ID: <42C16BA9.1040300@po-box.mcgill.ca> Fredrik Lundh said unto the world upon 28/06/2005 08:04: > Brian van den Broek wrote: > > >>So, it would appear that compression requires a 3rd party module, not >>included in Python (and not present on my Windows box). > > > where did you get your Windows Python? afaik, the zlib module has been > included in all major Python binary distributions since 1.5.2 or so... > > This is embarrassing :-[ I felt quite certain that I'd correctly typed 'import zlib' and received an import error. I'm going to have to plead a bad case of 3am goggles. Off to retract a spurious bug I filed ... Thanks Fredrik. Brian vdB From hancock at anansispaceworks.com Sat Jun 18 18:49:12 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 18 Jun 2005 17:49:12 -0500 Subject: Regex for repeated character? In-Reply-To: <42B3C7AA.7090907@lexicon.net> References: <5J9se.136$Q75.39412@newshog.newsread.com> <42B3C7AA.7090907@lexicon.net> Message-ID: <200506181749.12357.hancock@anansispaceworks.com> On Saturday 18 June 2005 02:05 am, John Machin wrote: > Doug Schwarz wrote: > > In article <5J9se.136$Q75.39412 at newshog.newsread.com>, > > Leif K-Brooks wrote: > >>How do I make a regular expression which will match the same character > >>repeated one or more times, > > How's this? > > > > >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbcccddddcccbba')] > > ['a', 'bb', 'ccc', 'dddd', 'ccc', 'bb', 'a'] > > I think it's fantastic, but I'd be bound to say that given that it's the > same as what I posted almost two days ago :-) Guess there's only one obvious way to do it, then. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From newsgroups at jhrothjr.com Thu Jun 2 14:41:15 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 2 Jun 2005 12:41:15 -0600 Subject: Unicode string in exec References: <1117687496.341548.117760@g14g2000cwa.googlegroups.com> Message-ID: <119ukmgd1nh8ve0@news.supernews.com> See below. -------------- "Jeff Epler" wrote in message news:mailman.411.1117734725.18027.python-list at python.org... First off, I just have to correct your terminology. "exec" is a statement, and doesn't require parentheses, so talking about "exec()" invites confusion. I'll answer your question in terms of eval(), which takes a string representing a Python expression, interprets it, and returns the result. In Python 2.3, the following works right: >>> eval(u"u'\u0190'") u'\u0190' Here, the string passed to eval() contains the literal LATIN CAPITAL LETTER OPEN E, and the expected Unicode string is returned The following behaves "surprisingly": >>> eval(u"'\u0190'") '\xc6\x90' ... you seem to get the UTF-8 encoding of the Unicode. This is related to PEP 263 (http://www.python.org/peps/pep-0263.html) but the behavior of compile(), eval() and exec don't seem to be spelled out. Jeff [response] To expand on Jeff's reply: in the first example, he's passing a Unicode string to eval(), which contains a Unicode string that contains a Unicode escape. The result is a Unicode string containing a single Unicode character. In the second example, he's passing a Unicode string to eval(), which string contains a ***normal*** string that contains a Unicode escape. The Unicode escape produces two characters. The result is a ***normal*** string that contains two characters. Is this your problem? John Roth From sjmachin at lexicon.net Sun Jun 5 21:42:49 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 06 Jun 2005 11:42:49 +1000 Subject: PyArg_ParseTuple and dict In-Reply-To: <1118019836.874936.47490@o13g2000cwo.googlegroups.com> References: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> <42A39E67.4060909@lexicon.net> <1118019836.874936.47490@o13g2000cwo.googlegroups.com> Message-ID: <42A3AA19.9030904@lexicon.net> sjh at gmail.com wrote: >>3. What is your platform? Which C compiler? What warnings does it give, >>[or would it give if allowed free speech]? Are you running Python 2.4 or >>2.4.1? > > > Python 2.4 (#1, Mar 10 2005, 16:54:23) [C] on sunos5 > > Solaris 9 x86, forte 6.2 > warnings? > > >>4. Do you get the same symptoms when you pass in a list instead of a >>dict? What about a minimal user-created object? > > A list works fine, as does a 1 element tuple with a dict in it. I'm > not sure what you mean by minimal user-created object. > class Muco: pass my_extension_func(42) # good my_extension_func("xyzzy") # good my_extension_func([]) # good my_extension_func({}) # bad my_extension_func(Muco()) # dunno yet From harlinseritt at yahoo.com Sat Jun 18 19:28:59 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 18 Jun 2005 16:28:59 -0700 Subject: extreme newbie In-Reply-To: <1119121987.131b80ae9685ccc81cd29fe3170de805@teranews> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <1119121987.131b80ae9685ccc81cd29fe3170de805@teranews> Message-ID: <1119137339.663666.165500@o13g2000cwo.googlegroups.com> ? From tjreedy at udel.edu Tue Jun 14 12:19:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Jun 2005 12:19:47 -0400 Subject: Controlling assignation References: <42aded8f$0$31916$636a15ce@news.free.fr> <42AE8657.9070806@imag.fr> Message-ID: "Xavier D?coret" wrote in message news:42AE8657.9070806 at imag.fr... >> class A( object): >> def __init__(self, value): >> self.value = value >More seriously, try to do this with your simpler approach. >a = A(4) >b = A(lambda : a.x+5) >a.x = 2 >print b.x # I want this to be 7, not 9 As written, it will be neither, since b.x is a function. But if you call it, its value *is* 7, not 9, as you specified wanting. So I don't understand your point. >>> class A: ... def __init__(self,val): self.x = val ... >>> a = A(4) >>> b = A(lambda : a.x+5) >>> a.x=2 >>> b.x at 0x008D1650> >>> b.x() 7 Terry J. Reedy From rschroev_nospam_ml at fastmail.fm Mon Jun 13 08:10:31 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 13 Jun 2005 12:10:31 GMT Subject: MD5 problem In-Reply-To: <42ad7561$0$1325$636a15ce@news.free.fr> References: <42ad7561$0$1325$636a15ce@news.free.fr> Message-ID: fargo wrote: > Hi. > > I'm in trouble with the md5 module. > > Under Linux, it's ok, I get real signatures. > > The problem is under Windows XP, with some kind of files. > > If I use the md5 module with .txt files, it'ok. > > The Problem comes from the .msg files. I get the same signature for > every .msg file I try to hash with the md5 algorithm. I think some > character are strange for python, and makes it stop before the end of > the .msg file. That sounds like you opened the file in text mode. For things like this it is better to open it in binary mode: file(filename, 'rb') -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From tjreedy at udel.edu Wed Jun 8 14:33:23 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 8 Jun 2005 14:33:23 -0400 Subject: MoinMoin WikiName and python regexes References: Message-ID: "Ara.T.Howard" wrote in message news:Pine.LNX.4.62.0506080907300.18046 at harp.ngdc.noaa.gov... > i'm trying to fix a bug in MoinMoin whereby A 'bug' is a discrepancy between promise (specification) and perfomance (implementation). Have you really found such -- does MoinMoin not follow the Wiki standard -- or are you just trying to customize MoinMoin to your different specification. > WordsWithTwoCapsInARowLike > ^^ > do not become WikiNames. Would your proposed change to make the above into an Wiki name also make all-cap sequences like NATO, FTP, and API into WikiNames and do you really want that? If WikiNum, appearing one place, were also mistyped as WikeNUm (from holding down the shift key too long, which I do occasionally), should the latter become a separate WikiName? I can certainly understand why the Wike designers might have answered both questions 'No." Terry J. Reedy From drool.galz at gmail.com Thu Jun 23 15:30:27 2005 From: drool.galz at gmail.com (Aditi) Date: 23 Jun 2005 12:30:27 -0700 Subject: suggestions invited In-Reply-To: <1119552092.000448.10230@g47g2000cwa.googlegroups.com> References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119552092.000448.10230@g47g2000cwa.googlegroups.com> Message-ID: <1119555027.087947.100970@g43g2000cwa.googlegroups.com> Thanks for ur effort... And I apologise for being sloppy in writing. Well I agree the whole project sounds fictitious because it has been assigned to me in that spirit. The project was explained to me in just 5 minutes and so these are the only details I have and the only documentation I have is a list of the 31 applications used in the company and that the platform used in the company is OS 400. The reason why I posted this mail was to invite ideas as to how could I make the best use of these details and suggestions because I myself found these details way too less. I think I should have written about this in the first mail to avoid frustration to the people who are trying to help me. Anyways now that it is known that the project has been assigned to me just for the heck of it would like to make my project such that they want to use it...I would definately not let my work go wasted...So do let me know what you think could be done in this direction. Greetings... Aditi From mwm at mired.org Tue Jun 28 19:34:12 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 28 Jun 2005 19:34:12 -0400 Subject: Is there something similar to ?: operator (C/C++) in Python? References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: <86y88um4y3.fsf@bhuda.mired.org> Riccardo Galli writes: > On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote: > >>> Bo Peng wrote: >>> >>>> I need to pass a bunch of parameters conditionally. In C/C++, I can >>>> do func(cond1?a:b,cond2?c:d,.....) >>>> >>>> Is there an easier way to do this in Python? >>> >>> >> The answer is simply no, just use an if statement instead. > > That's not true. > One used form is this: > result = cond and value1 or value2 > > which is equal to > if cond: > result=value1 > else: > result=value2 > > > another form is: > > result = [value2,value1][cond] > > > the first form is nice but value1 must _always_ have a true value (so not > None,0,'' and so on), but often you can handle this. Note that [value2, value1][cond] doesn't do exactly what cond ? value1 : value2 does either. The array subscript will always evaluate both value2 and value1. The ?: form will always evaluate only one of them. So for something like: [compute_1000_digits_of_pi(), compute_1000_digits_of_e][cond] you'd really rather have: cond ? compute_1000_digits_of_e() : compute_1000_digits_of_pi() There are other such hacks, with other gotchas. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From multiethniccommunities at yahoo.com Tue Jun 21 23:30:19 2005 From: multiethniccommunities at yahoo.com (Jenta) Date: Tue, 21 Jun 2005 23:30:19 -0400 Subject: A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... Message-ID: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... ..and Online Registration is now available if you plan to table and participate in the International Grassroots Exhibition: http://www.lfhniivaaaa.info/awbcgrassrootsofpeace We would greatly like some proposals from all people worldwide, especially marginalized communities and minorities. The Mission Statement: A World Beyond Capitalism (AWBC) 2005 invites activists to come to Portland, Oregon in August 2005 and engage in a weekend of educational discussion and visionary dialogue. We believe in the need to reflect and imagine the future of the world beyond capitalism. We will emphasize the need for multi-lingual, long-term strategy through open dialogue and bridging political theory with practice. By building on the increasing number of conferences worldwide in which people from diverse backgrounds, races and cultures discuss subjects regarding world peace, we hope to build solidarity among diverse organizing communities. Over 1000 participants from Canada, Kenya, Mexico, Ghana, Germany, the U.S. and all over the world will come together in harmony in Portland, Oregon in August 2005 to share ideas regarding new visions, changing the world, the cooperative movement, intentional communities and much, much more. Come and be a part of this tremendous occasion. Activist, Punks, Minority and Marginalized Communities from Alternative medicine healers and activists, Intentional communities, Permaculture Homes, co-ops, independent publishing communities, progressive activist groups and other equality seeking groups are invited to volunteer, table, or just fellowship, network and learn with every one from all over the world. There will also be a performance of live, multicultural musicians and a theatrical debut prior to the conference. August 26-28, 2005, Portland State University, Portland, Oregon. Not only is this a conference, but it is a multi-lingual, multi-racial alliance building experience. This conference will create alliances in a manner which transcends the boundaries of the English Language, Race, Class, Gender, Age, Ability, Sexual Orientation and Endless Theory. In addition, The Grassroots Exhibition enables non-government and non-corporate people and groups of many different types the chance to come together in solidarity. The Grassroots Exhibition gives everyone the opportunity to share information and items with people outside of their usual circle of friends, yet still amongst those who desire to see a world that is beyond forced corporate dependence and capitalism. Below are a few of the different groups that you can look forward to seeing at the Grassroots Exhibition: (Listed in Alphabetical order) Activist groups Alternative media, small press and zine writers and creators Alternative medicine activists and practictioners All underrepresented, marginalized and minority groups Co-ops and members of co-ops Cohousing Groups Collectives and members of collectives Do-it-yourself (DIY) and independent musicians FreeSkool, (Free School) free education supporters and groups Independent creators and artisans of handmade art and items Independent distributors Independent film, documentary and theatre creators, dancers and supporters Independent music and independent non-music audio items Independent press librarians, zine librarians and activist librarians Indigenous and Native tribes Intentional communities and non-corporate, community and family owned farm groups and farm workers Mail-Art and international mail networks Non-corporate, low power FM radio station creators and operators Non-pharmaceutical, homeopathic, holistic and energywork groups Online information and online discussion group creators and operators Opensource Technology Activist or user Punk Music and Art Python/computer activists Rainbow Gathering groups Selfschool and homeschool supporters, teachers and students Translation and handicapable access related services And many more groups which are related to these groups. Wicca Activists Online Registration is now available if you plan to participate in the International Grassroots Exhibition: http://www.lfhniivaaaa.info/aw?bcgrassrootsofpeace Location: Portland State University Smith Ballroom Portland, Oregon 97208 Portland OR Contact: AWBC International Multiracial Alliance Building Peace Conference Organizers. We are accepting proposals until August 10th, 2005 and we greatly encourage people of all races, social classes and educational backgrounds to submit a proposal. You may present workshops in your native language as we will have translators. Volunteers needed continuously. Thank You, Love And Solidarity Worldwide, Volunteers for the AWBC 2005 http://www.CommonUnityPeaceCon?ference.org or http://www.awbc.lfhniivaaaa.in?fo Thanks all, sisters and brothers. From codedivine at gmail.com Thu Jun 16 14:47:10 2005 From: codedivine at gmail.com (Rahul) Date: 16 Jun 2005 11:47:10 -0700 Subject: Multiple instances of a python program Message-ID: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> Hi. I am part of a group in my univ where we organize a programming contest. In this contest we have a UDP based server. The server simulates a game and each contestant is to develop a team of virtual players. Each team is composed of 75 similar bots...i.e. governed by the same logic. Thus the contestant submits a single copy of the client and we instantiate the same program 75 times at the same time. The problem is that while executables from C source files are small and we can make 75 processes but we dont know what to do with python. If you have a python script and you want that 75 copies of the script be run simultaneously how will you do it? Is there anyway to do so without running 75 copies of the python interpreter simultaneously? From greg at cosc.canterbury.ac.nz Thu Jun 2 22:12:09 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 03 Jun 2005 14:12:09 +1200 Subject: Beginner question: Logs? In-Reply-To: References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: <3g9sk7Fba0toU1@individual.net> Peter Hansen wrote: > It's always a good idea, especially when answering a beginner's > question, to add the caution that this form ("from xxx import *") has > certain dangers** associated with it, and is widely considered poor > style, and should really only rarely be used. Better still, don't even *mention* it to a beginner. They don't need to know about it. At all. Really. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From lycka at carmen.se Mon Jun 20 15:58:30 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 20 Jun 2005 21:58:30 +0200 Subject: UML to Python/Java code generation In-Reply-To: <1119066144.174522.193340@f14g2000cwb.googlegroups.com> References: <873brhufez.fsf@hector.domek> <1119066144.174522.193340@f14g2000cwb.googlegroups.com> Message-ID: <42B71FE6.1020107@carmen.se> James wrote: > The brain may be fine for generating Python from UML but it is MANY > MANY orders of magnitude harder to generate UML from code with just > your brain than using a tool (usually zero effort and error free) no > matter how good you are at Python. I've really only used Rational Rose, but that tool is really limited in both directions. Class structure to class diagrams work both ways (not for Python, but for Java and C++ at least) but that's just a tiny part of UML. I don't expect any tool to do anything meaningful about e.g. use case diagrams, but what about activity diagrams, sequence diagrams, collaboration diagrams and state diagrams? I agree that the brain is poor at such things, but I doubt that any current tool is much better except for trivial subsets of UML. From ajikoe at gmail.com Sun Jun 26 09:39:00 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jun 2005 06:39:00 -0700 Subject: accessing object attribute as parameter In-Reply-To: <3i7gk9Fjr5buU1@uni-berlin.de> References: <1119782637.483529.101890@g43g2000cwa.googlegroups.com> <3i7gk9Fjr5buU1@uni-berlin.de> Message-ID: <1119793139.992542.189480@g44g2000cwa.googlegroups.com> thanks Diez pujo From kasimov at i.com.ua Wed Jun 8 10:58:52 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Wed, 08 Jun 2005 17:58:52 +0300 Subject: different time tuple format In-Reply-To: <1118239337.961657.242660@g49g2000cwa.googlegroups.com> References: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> <1118239337.961657.242660@g49g2000cwa.googlegroups.com> Message-ID: <42A707AC.9000405@i.com.ua> yes, i agree, on my WinXP it gives another values. but my question is how to setup the python (or OS) to make it gives the same results when i call time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") on various servers (and maybe with various OS)? for now, i can't get it even with the same OS. and i would like to set time string exactly as "2005-06-07 15:07:12", without "CEST", "EEST" and so on, because as you've notice before, it is different on a variuos systems wittempj at hotmail.com wrote: > The names are at least platform specific, see below the names of the > timezones on my Windows NT 4 box > > *** Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit > (Intel)] on win32 > *** Type "help", "copyright", "credits" or "license" for more > information. > *** >>> import time > *** >>> print time.tzname > *** ('W. Europe Standard Time', 'W. Europe Daylight Time') > *** >>> > -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From http Mon Jun 13 14:28:42 2005 From: http (Paul Rubin) Date: 13 Jun 2005 11:28:42 -0700 Subject: Is Python Suitable for Large Find & Replace Operations? References: Message-ID: <7xr7f6cdr9.fsf@ruckus.brouhaha.com> rbt writes: > Now, management would like the IT guys to go thru the old data and > replace as many SSNs with the new ID numbers as possible. You have a > tab delimited txt file that maps the SSNs to the new ID numbers. There > are 500,000 of these number pairs. What is the most efficient way to > approach this? I have done small-scale find and replace programs > before, but the scale of this is larger than what I'm accustomed to. Just use an ordinary python dict for the map, on a system with enough ram (maybe 100 bytes or so for each pair, so the map would be 50 MB). Then it's simply a matter of scanning through the input files to find SSN's and look them up in the dict. From rkern at ucsd.edu Sat Jun 25 16:31:19 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 25 Jun 2005 13:31:19 -0700 Subject: Favorite non-python language trick? In-Reply-To: <1119730516.936848.195640@f14g2000cwb.googlegroups.com> References: <3i232vFj0b57U1@individual.net> <1119730516.936848.195640@f14g2000cwb.googlegroups.com> Message-ID: Devan L wrote: > But by using the builtin reduce, you need to specify a function, which > probably slows it down more than any speed-up from the loop in C. Not if the function is from an extension module. For some applications, this can be quite common. Of course, in a Python 3000 world, nothing stops anyone from using their own extension module implementing map, filter, and reduce if they really want to. TSBOOOWTDI in the language/stdlib, but it shouldn't stop anyone from using other ways to do it that aren't in the stdlib if the tradeoffs are right for them. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mauriceling at acm.org Thu Jun 2 19:57:33 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Jun 2005 09:57:33 +1000 Subject: something like CPAN, PPMs? References: <1d70n2-g5a.ln1@news.interplanet.it> Message-ID: deelan wrote: > Maurice LING wrote: > >> Hi Alex, >> >> I am actually working on something like that as an academic project. >> At this stage, at least for the purpose of my scope, it will not be as >> extensive as CPAN but a set of mechanisms for the same effect for Python. > > > don't foget to keep an eye on python's eggs: > > > > and related blog posts: > > > > > > HTH. > Thanks, I think PythonEggs will have increasing effect in the future as Python is moving more towards enterprise development, as what we hope to see. Although it is stated in their website that using PythonEggs does not automatically confer platform-independence, it might still be a good way for enterprises, especially on the reverse engineering issue. My approach now is to work out a prototype system that is made as a 3rd party installation process for my software. My software requires tools like PLY, SciPy etc etc. My idea is that by doing "python setup.py install" to install my stuffs, a function in setup.py calls a system (in my software, call it centipyde) and installs the pre-requisites as required. "Centipyde" can then be developed into a better management tool. As I've posted in many mailing lists, I've intended this to be an academic project (any other contradictory decisions made will be announced). However, I do welcome opinions. Cheers Maurice From JOHNWUN at aol.com Mon Jun 6 15:20:46 2005 From: JOHNWUN at aol.com (Grooooops) Date: 6 Jun 2005 12:20:46 -0700 Subject: the python way? In-Reply-To: <3gjksrFcmvf4U1@individual.net> References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> <3gjksrFcmvf4U1@individual.net> Message-ID: <1118085646.302294.188860@g44g2000cwa.googlegroups.com> Wow... Thanks for all the tips guys... I will study the above examples. ...down to 8 lines of exquisitely readable code... Wow... Python rocks... (still aspiring to greatness myself,) cheers, -John ------------ x=["ohndes","j","wu","x[1][0]+x[0][:3]+chr(((len(x))*16))+x[2]+x[0][2:]+`round(1)`[1]+x[3][17]+x[0][0]+chr(ord(x[0][2])-1)"] print eval(x[3]) ------------ From finite.automaton at gmail.com Thu Jun 9 14:28:32 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 9 Jun 2005 11:28:32 -0700 Subject: Any way to not create .pyc files? In-Reply-To: References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <1118341712.757348.9850@g49g2000cwa.googlegroups.com> Of course! ZIP imports! I think that will solve the problem nicely. We already have a starter application that locates the codebase on the network drive, so it wouldn't be too hard to implement the "keep a local copy up to date" solution. But I'll try the zip idea first. Many thanks for your helpful suggestions =) From falcon3166 at hotmail.com Thu Jun 30 11:22:52 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Thu, 30 Jun 2005 09:22:52 -0600 Subject: I have a question. Message-ID: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Hi all, Does Python have a random function? If so, can you show me an example using it? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From twic at urchin.earth.li Mon Jun 13 07:48:19 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 13 Jun 2005 12:48:19 +0100 Subject: What is different with Python ? In-Reply-To: <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: On Mon, 13 Jun 2005, Andrea Griffini wrote: > On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: > >>> Also concrete->abstract shows a clear path; starting in the middle and >>> looking both up (to higher abstractions) and down (to the >>> implementation details) is IMO much more confusing. >> >> At some point, you need to draw a line in the sand (so to speak) and >> say, "I understand everything down to *here* and can do cool stuff with >> that knowledge. Below that, I'm willing to take on faith". > > I think that if you don't understand memory, addresses and allocation > and deallocation, or (roughly) how an hard disk works and what's the > difference between hard disks and RAM then you're going to be a horrible > programmer. > > There's no way you will remember what is O(n), what O(1) and what is > O(log(n)) among containers unless you roughly understand how it works. > If those are magic formulas you'll just forget them and you'll end up > writing code that is thousands times slower than necessary. I don't buy that. I think there's a world of difference between knowing what something does and how it does it; a black-box view of the memory system (allocation + GC) is perfectly sufficient as a basis for programming using it. That black-box view should include some idea of how long the various operations take, but it's not necessary to understand how it works, or even how pointers work, to have this. tom -- Think logical, act incremental From richardlewis at fastmail.co.uk Fri Jun 3 12:07:37 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Fri, 03 Jun 2005 17:07:37 +0100 Subject: minidom Node to Element Message-ID: <1117814857.13561.235587400@webmail.messagingengine.com> Hey, Can I convert an xml.dom.Node object to an xml.dom.Element object? I want to do the conversion inside a condition like this: if node.nodeType == Node.ELEMENT_NODE: # do conversion: element = Element(node) element = node.toElement() so it definitely won't cause problems. I just can't find a way to do it! (I want to be able to call getElementsByTagName() on the resultant object; any other workarounds which allow the same functionality would be just as cool ;-) Cheers, Richard From c0chong at gmail.com Wed Jun 29 20:55:44 2005 From: c0chong at gmail.com (c0chong at gmail.com) Date: 29 Jun 2005 17:55:44 -0700 Subject: Help please: How to assign an object name at runtime Message-ID: <1120092944.710361.309310@g44g2000cwa.googlegroups.com> Good day: Probably the answer to my question is staring me in the face, but the solution escapes me. The following is the input line of the file: SoftDict-.csv: ca1017,GRPHScriptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14 I expected an instance of Machine() to be created with a name ca1017. Instead, an object is assigned to l[0] named: <__main__.Machine instance at 0x01282558> ----------------------------- Here is my code: class Machine: def __init__(self): self.software = []# Holds attributes of the instance def add(self, sware): self.software.append(sware)# Append attribute return self.software def show(self): return self.software def __call__(self): return [ e for e in self.software] def cnt(self): return '%s' % (len(self.software)) def installed(self, sware): if sware in self.software: return True else: return False class FileList: def __init__(self, filename): self.file = open(filename, 'r') # open and save file def __getitem__(self, i): # overload indexing line = self.file.readline() if line: return line # return the next line else: raise IndexError # end 'for' loops, 'in' def __getattr__(self, name): return getattr(self.file, name) # other attrs if __name__ == '__main__': import sys, fileinput, os, string # when run, not imported for line in FileList('SoftDict-.csv'): # Treat .csv as a text if len(line)==1: break # Quit processing; end of file l=line.split(',')# Split the line into constituent parts l[0]=Machine() # Create a Machine() object named: ca1017 ------------------------------------------- That's it. I evidently have no idea what I am doing. Thanks for your help. From peter at engcorp.com Thu Jun 30 08:32:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 30 Jun 2005 08:32:17 -0400 Subject: POP3 and "seen" flag In-Reply-To: References: Message-ID: Miki Tebeka wrote: > Is there a way to know in a POP session of a message was seen (old) or not > (new)? Define "seen". It could be interpreted as either "TOP" or "RETR" having been executing for a message, or something like "this client has seen this message before" ... not sure what you mean. In any case, the short answer is "no". The longer answer is that _some_ POP3 servers provide non-standard support for this by doing things like adding a special header to the message, things like "X-Seen", which can be seen by using the TOP command. This sort of thing is entirely non-standard and you can't rely on it in general, AFAIK. A better approach would be to have your client software track the Message-ID header, but something tells me you are interpreting "seen" as meaning "anyone has RETRed the message", so that won't work either. -Peter From piet at cs.uu.nl Sat Jun 11 07:14:13 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 11 Jun 2005 13:14:13 +0200 Subject: Any way to not create .pyc files? References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> <2LCdnaLtfdK9HTTfRVn-pg@powergate.ca> Message-ID: >>>>> Terry Hancock (TH) wrote: >TH> It looks to me like Python just deleted a read-only file owned by >TH> root in order to replace it with a new pyc file. Can somebody >TH> explain that to me?! Isn't that supposed to be impossible? If the directory is writable, you can delete a file and write a new one with the same name. The permissions of the file itself are of no importance in this case. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From exarkun at divmod.com Fri Jun 24 21:30:49 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 24 Jun 2005 21:30:49 -0400 Subject: Newbie question: how to keep a socket listening? In-Reply-To: Message-ID: <20050625013049.26278.1709605860.divmod.quotient.80@ohm> On Fri, 24 Jun 2005 21:21:34 -0400, Peter Hansen wrote: >ncf wrote: >> Heh, like I said. I was not at all sure. :P >> >> Nevertheless, could this be the problem? =\ > >You *may* correct, mainly because the OP's code doesn't appear to spawn >off new threads to handle the client connections, which means he can >handle only one connection at a time. Specifically, while he is talking >to one client he is not also in an accept() call on the server socket, >which means there will be (because of the listen(1) call) only a single >pending connection allowed in the backlog. > >I haven't attempted a thorough analysis... just this much, trying to see >whether it is obvious that the listen(1) is at fault -- and it's not >obvious. I thought this response might clarify the meaning of listen(1) >a little bit for some folks nevertheless. The argument to listen() is only a _hint_ to the TCP/IP stack. Linux, at least, will not create a buffer large enough for only a single connection. You can test this easily: create a socket, bind it to an address, call listen(1) on it, and *don't* call accept(). Telnet (or connect somehow) repeatedly, until your connection is not accepted. On my system (Linux 2.6.10), I can connect successfully 8 times before the behavior changes. Jp From theller at python.net Thu Jun 23 08:54:40 2005 From: theller at python.net (Thomas Heller) Date: Thu, 23 Jun 2005 14:54:40 +0200 Subject: List of all installed applications (XP)? References: Message-ID: "Guy Lateur" writes: > | What -- from your point of view -- is an "application"? > > Good question. Let me try to elaborate: I would like to know if people in > our company (building techniques) are using non-licensed software (eg > Photoshop, Office, AutoCad). So I guess by 'application' I mean commercial > software packages like those. > > Is it safe to assume those apps get listed in AppPath? I don't think my > users are cunning enough to mess with the registry, so I guess we're talking > about the 'standard' installation. > > > > | Neither does every app have an Add/Remove Program > | entry. (And some things have entries which aren't apps). > > Just out of curiosity: can one read the info/list one gets in Add/Remove > Programs? It's not a problem I get results that aren't actually apps, but it > is important I get all apps. > I think it's this registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall Maybe you should try HKEY_CURRENT_USER\.. or HKEY_USERS\..\.. as well. Thomas From jabailo at texeme.com Fri Jun 3 01:41:00 2005 From: jabailo at texeme.com (jabailo at texeme.com) Date: Thu, 02 Jun 2005 22:41:00 -0700 Subject: Simple Kiosks Serve The World References: <429e7155.6739473@news.alphalink.com.au> Message-ID: Jeff_Relf wrote: > As I've told you a quintillion times, Earthlink's insanity aside, > Win_XP is a virtual network, quite indepent of the connection used. > Linux is hardly an OS, it's just a kernel. The world doesn't need a 'virtual network'...it needs an Internet Kiosk. While Jeff the Bolshevik was sleeping; American Capitalism produced what the Governments of India, Africa and China could not: A $69 Internet Kiosk from which they can derive Knowledge, Commerce and Society. Yes, listen here World Bank, Unicef, UN, Bono, Gate$ Foundation: Do you want the world to have computers? Then cough up $69 a head to Microtek and have them send it Ground Freight to Burkina Faso, Outer Mongolia and Bangalore. As for 'virtual networks' -- yes, virtual in the sense of not being real...in the sense of not having substance. Yes. virtual. -- Texeme Textcasting Technology http://www.texeme.com From Scott.Daniels at Acm.Org Tue Jun 28 11:55:46 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 28 Jun 2005 08:55:46 -0700 Subject: [OT] Re: What is different with Python ? (OT I guess) In-Reply-To: References: <42AED7B3.8060009@carmen.se> <6kh2c151vvhda93jghhm8qcrf9v64llf7t@4ax.com> Message-ID: <42c16b70$1@nntp0.pdx.net> Peter Otten wrote: > Christos TZOTZIOY Georgiou wrote: > >>and then, apart from t-shirts, the PSF could sell Python-branded >>shampoos named "poetry in lotion" etc. > > Which will once and for all solve the dandruffs problem prevalent among the > snake community these days. And once again the Pythonistas will be known as snake-oil salesmen. From mkb at incubus.de Wed Jun 1 10:07:58 2005 From: mkb at incubus.de (Matthias Buelow) Date: Wed, 01 Jun 2005 16:07:58 +0200 Subject: What are OOP's Jargons and Complexities? In-Reply-To: References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> Message-ID: <3g5tlqFaq4meU1@news.dfncis.de> Anno Siegel wrote: > I've been through Pascal, Modula2 and Oberon, and I agree. > In the short run they succeeded. For a number of years, languages of > that family were widely used, primarily in educational programming > but also in implementing large real-life systems. With a few relaxations and extensions, you can get a surprisingly useful language out of the rigid Pascal, as evidenced by Turbo Pascal, one of the most popular (and practical) programming languages in the late 80ies / start of the 90ies. mkb. From steve at holdenweb.com Thu Jun 9 14:07:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 09 Jun 2005 14:07:07 -0400 Subject: Any way to not create .pyc files? In-Reply-To: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <42A8854B.6060204@holdenweb.com> Lonnie Princehouse wrote: > In short: > > Is there any way to run Python WITHOUT trying to create .pyc files (or > .pyo) or to have Python not attempt to import the .pyc files it finds? > > Reason: > > We have a site-specific package installed on a network drive[1]. When > anyone with write access imports this package, the network drive gets > spammed with .pyc files. > Well, at least they have the right to create them. Wouldn't it be easier, though, to just create all the .pyc files. > If these .pyc files exist, they appear to cause problems when other > users' Python interpreters use them instead of the .py files. (I know, > they *should* work, but they don't). This may have something to do > with the fact that all of these users (on Windows) have the network > drive mapped to arbitrary drive letters. I don't know. The .pyc file is normally created in the same directory as the .py file. You may be seeing problems because one user doesn't have permissions to access a file created by another. In that case you may be able to set the inherited permissions for Creator Owner to allow reading by all users. You might also expect problems if one user was using python 2.2 and another was using 2.4, since each version requires its own format for the .pyc file, and they might conflict. Ulitmately it sounds like a permissions problem. > > PEP 304 would have helped, but it appears to be deceased. What I > really want is a command line option > Not sure it's deceased (a dead parrot?) - it's on the standards track, it hasn't been rejected, and Skip has actually provided a patch to implement the solution. > I'm going to have to cobble together a work-around, like having > imported modules delete their own .pyc files immediately after import, > but it would be really nice to have a /good/ way of not using .pyc... > It would be *much* more sensible to find the underlying cause of the problems and actually fix them :-) > (footnotes) > > [1] Because it's an administrative nightmare to distribute code updates > to dozens of non-technical users > I hear that. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From ntv1534 at gmail.com Thu Jun 30 17:38:17 2005 From: ntv1534 at gmail.com (MooMaster) Date: 30 Jun 2005 14:38:17 -0700 Subject: Lost in a sea of documentation...can you point me in the right direction? Message-ID: <1120167496.973373.163400@f14g2000cwb.googlegroups.com> I'm a complete beginner in Python, but I've been fooling around with Java for a couple years, so I have decent programming experience... Anyway, I was sitting around playing with Python, when I thought to myself: "I know! I'd like to write a program that I can pass a path to (say: My Pictures) and at a timer interval will pick a picture from it and set my wallpaper to that" So I started reading about os, threads, and the path for the special folders in the archives and in the Python docs and I'm kind of lost because there aren't many concrete examples in the documentation. Can anyone point me in the right direction as to where I might find info that can help me write this? Thanks! From Danielnord15 at yahoo.se Thu Jun 9 02:43:26 2005 From: Danielnord15 at yahoo.se (Svennglenn) Date: 8 Jun 2005 23:43:26 -0700 Subject: Make Tkinter child window active In-Reply-To: <-bydnZoo6YSkVDrfRVn-tQ@rogers.com> References: <1118253789.591161.88220@o13g2000cwo.googlegroups.com> <-bydnZoo6YSkVDrfRVn-tQ@rogers.com> Message-ID: <1118299405.939668.96210@g14g2000cwa.googlegroups.com> It's working, thank you very much :) From lambacck at gmail.com Wed Jun 8 14:56:29 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Wed, 8 Jun 2005 14:56:29 -0400 Subject: [Pyrex] Allocating an array.array of a specific length in pyrex In-Reply-To: References: <396556a2050608111658e56203@mail.gmail.com> Message-ID: And we have a winner. For reference the final code is below. Thanks for your help, -Chris import array cdef extern from "Python.h": int PyObject_AsWriteBuffer(object obj, void **buffer, int *buffer_len) int PyObject_AsReadBuffer(object obj, void **buffer, int *buffer_len) object PyString_FromStringAndSize(char *, int) char *PyString_AsString(object obj) cdef int get_w_buffer(obj, unsigned char **data, int *length) except -1: cdef int result cdef void *vd # use a void * result = PyObject_AsWriteBuffer(obj, &vd, length) data[0] = vd return result cdef int get_r_buffer(obj, unsigned char **data, int *length) except -1: cdef int result cdef void *vd # use a void * result = PyObject_AsReadBuffer(obj, &vd, length) data[0] = vd return result def encode(int w, int h, in_a): cdef unsigned int pixels, a_off, str_off#, buffer_len cdef int res, inlen, buffer_len cdef unsigned char *in_str, *out_str res = get_r_buffer(in_a, &in_str, &inlen) if res: raise Exception, "Could not get a readable buffer from the input" pixels = w * h a = PyString_FromStringAndSize(NULL, pixels * 2) out_str = PyString_AsString(a) buffer_len = pixels * 2 str_off = 0 a_off = 0 while a_off < buffer_len and str_off < inlen: out_str[a_off] = in_str[str_off] out_str[a_off+1] = (in_str[str_off+1] + in_str[str_off+4])/2 out_str[a_off+2] = in_str[str_off+3] out_str[a_off+3] = (in_str[str_off+2] + in_str[str_off+5])/2 str_off = str_off + 6 a_off = a_off + 4 return a On 6/8/05, Chris Lambacher wrote: > I replaced: > a = array.array('B', , [0] * (pixels * 2)) > with: > a = PyString_FromStringAndSize(NULL, pixels * 2) > > and got: > C:\work\testing\plink_o_ip>python ycbycr.py > Traceback (most recent call last): > File "ycbycr.py", line 62, in ? > ycbycr = image2ycbycr(im) > File "ycbycr.py", line 38, in image2ycbycr > return _ycbycr.ycbcr2ycbycr(w, h, ycbcrim.tostring()) > File "_ycbycr.pyx", line 42, in _ycbycr.ycbcr2ycbycr > res = get_w_buffer(a, &out_str, &buffer_len) > TypeError: Cannot use string as modifiable buffer > > Strings are not mutable so this is not going to work for me :( > > Is there a way to allocate a python buffer object and give that to > array.array or a string object? > > -Chris > > On 6/8/05, Chris Lambacher wrote: > > The memory is not temporary, I am passing it out as an array, thus the > > malloc/free route will require double allocation(once for malloc/free, > > once for array.array). I am not using string because when I tried to > > pass the data in as string, pyrex complained about the conversion. > > However, I could probably use the same PyObject_AsReadBuffer function > > call to get at the data passed in to the function as a string and then > > pass it out as a string as well using the interface suggested ( > > PyString_FromStringAndSize and PyString_AsString ). Perhapse I need > > to substitute PyObject_AsWriteBuffer instead of PyString_AsString in > > order for my changes to get propegated back to the string object? > > > > -Chris > > > > > > On 6/8/05, Adam Langley wrote: > > > On 6/8/05, Chris Lambacher wrote: > > > > My question is, is there a better way to > > > > allocate the memory for the array.array object than: > > > > a = array.array('B', [0] * (pixels * 2)) > > > > > > cdef unsigned char *buffer > > > temp_string = PyString_FromStringAndSize(NULL, length) > > > buffer = PyString_AsString(temp_string) > > > > > > That's one way to do it. But it looks like you just want an area of > > > memory so why not: > > > > > > cdef extern from "stdlib.h": > > > ctypedef unsigned long size_t > > > void *malloc(size_t size) > > > void free(void *mem) > > > > > > ? > > > > > > AGL > > > > > > -- > > > Adam Langley agl at imperialviolet.org > > > http://www.imperialviolet.org (+44) (0)7906 332512 > > > PGP: 9113 256A CC0F 71A6 4C84 5087 CDA5 52DF 2CB6 3D60 > > > > > > > > > -- > > Christopher Lambacher > > lambacck at computer.org > > > > > -- > Christopher Lambacher > lambacck at computer.org > -- Christopher Lambacher lambacck at computer.org From philipseeger at yahoo.de Thu Jun 9 12:24:15 2005 From: philipseeger at yahoo.de (Philip Seeger) Date: Thu, 9 Jun 2005 18:24:15 +0200 Subject: Exe file Message-ID: Hi @ll I'm sorry for that newbie question but how can I compile a program (a .py file) to an executable file? -- Philip Seeger From jrivet at ameritech.net Mon Jun 20 13:06:38 2005 From: jrivet at ameritech.net (Jonathan) Date: 20 Jun 2005 10:06:38 -0700 Subject: sudoku dictionary attack In-Reply-To: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> References: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> Message-ID: <1119287197.993599.160240@g47g2000cwa.googlegroups.com> sub1ime_uk at yahoo.com wrote: > Thought I'd offer a method for solving all possible 9x9 sudoku puzzles > in one go. It'll takes a bit of time to run however (and 9x9 seems to > be about as big as is reasonably possible before combinatorial > explosion completely scuppers this type of program)... > > Basic idea:- > > Start with a grid initialised with: > > 123456789 > 234567891 > 345678912 > 456789123 > 567891234 > 678912345 > 789123456 > 891234567 > 912345678 > > Note that all rows and columns contain all 9 digits (but that the > sub-tiles aren't correct for a sudoku solution). > > Next write a program which permutes all 9 columns, and then for each of > those permutations permutes the last 8 rows. This will, I believe, > generate all possible grids with no digit repetitions in any row or > column. It will generate 14,631,321,600 (9!*8!) possible sudoku > candidates. Finally, check each candidate to see if any 3x3 subtile has > a repeated digit in it and discard as soon as a repeat is found (sooner > the better). Any that come through unscathed get written as a 82 (81 + > lf) char string to an output file. I'm having trouble coming up with anything that fits this grid: ..12..... ..2x..... ......... ......... ......... ......... ......... ......... ......... where x is not 3, by permuting columns, then rows. You may also have to permute the numbers. Although, even then, x=1 is still impossible. From davecook at nowhere.net Thu Jun 23 07:23:17 2005 From: davecook at nowhere.net (Dave Cook) Date: Thu, 23 Jun 2005 11:23:17 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: On 2005-06-23, Joel Rosdahl wrote: > Or APSW . Interesting. I was hoping it would not have one pysqlite2 limitation: if you have an empty database, cursor.description always returns None, even if you have "pragma empty_result_callbacks=1" (pysqlite 1.x doesn't have the problem). But apsw also requires data to be avaliable before you can get column descriptions. However, the tracing stuff and the various hooks you can set look really interesting. Dave Cook From rupole at hotmail.com Sun Jun 12 20:21:51 2005 From: rupole at hotmail.com (Roger Upole) Date: Sun, 12 Jun 2005 20:21:51 -0400 Subject: How to receive events (eg. user mouse clicks) from IE References: <1116476411.853695.235670@g14g2000cwa.googlegroups.com> <428c3cbe$1_1@spool9-west.superfeed.net> <1116529345.146032.91880@f14g2000cwb.googlegroups.com> <428cf5a9$1_1@spool9-west.superfeed.net> <1116537405.495521.252570@f14g2000cwb.googlegroups.com> <428f5882$1_2@spool9-west.superfeed.net> <428f8660$1_1@spool9-west.superfeed.net> <1116792093.323847.312700@g49g2000cwa.googlegroups.com> <42915ad9$1_1@spool9-west.superfeed.net> <1118544283.178003.277370@g47g2000cwa.googlegroups.com> Message-ID: <42acd28f$1_1@spool9-west.superfeed.net> Each frame acts as a separate document. You should be able catch document events from a frame using something like win32com.client.DispatchWithEvents(ie.Document.frames().document, ) Roger wrote in message news:1118544283.178003.277370 at g47g2000cwa.googlegroups.com... > Resurrecting an old thread.. > It seems that this solution does not return events on objects within > frames in webpages eg . if you go to www.andersondirect.com - the page > is composed of three frames called as topFrame main and address. Now > when I click on say 'Select a Vehicle' which is within main - I do not > get any Onclick event. I also do not get an OnMousemove event if I move > the mouse. However, I do get on Mousemove event on a tag called as > frameset (which is part of the top page). > How does one get events from the frames then? > As always thanks a lot. > > Roger Upole wrote: >> wrote in message >> news:1116792093.323847.312700 at g49g2000cwa.googlegroups.com... >> ... >> > The problem is that msdn documentation says that in order to identify >> > the element that was clicked - one has to query on IHTMLWindow2::event >> > property on iHTMLWindow2 interface to get IEventOBj interface and then >> > from there - use query interfce to get to the id of the element. >> > >> > How do I do this in python? ie. I have this code >> > class Doc_Events(doc_mod.HTMLDocumentEvents): >> > def Ononclick(self): >> > print 'onClick fired ' >> > and I see onClick being trapped. >> > Now I need to go and get a reference to the iHTMLWindow2 interface. For >> > this I need to get a reference to doc_mod (as far as I can see). How do >> > I get that in the OnonClick method above. >> >> To get the IHTMLWindow2, you can just use self.parentWindow >> inside the event hander, and then get the event from it. And then >> the event's srcElement should be what you need. >> >> class Doc_Events(doc_mod.HTMLDocumentEvents): >> def Ononclick(self): >> print 'onclick' >> ev=self.parentWindow.event >> src=ev.srcElement >> print 'tagName:',src.tagName,'name:',src.getAttribute('name') >> >> For clicking on google's input field, this yields >> tagName: INPUT name: q >> >> > >> > b) You had mentioned PumpWaitingMessages in the previous posting. I >> > first encountered this on newsgroup postings. None of the standard >> > books (python on win32 / python developer) seem to explain this in >> > detail although this seems to be commonly used. Though I understand >> > this now - my problem is that there seems to be a lack of cohesive >> > explanation on how python ties up with COM (despite a good chapter 12 >> >> PumpWaitingMessages is just a way to ensure that normal message processing >> (window messages, events, dde, etc) happens while python code is running. >> Normally you don't need it, but every once in a while you hit a situation >> where >> blocking occurs. >> >> For how exactly python interacts with COM, the source is your best bet. >> >> Roger >> >> >> >> >> >> ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- >> http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups >> ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From mwm at idiom.com Wed Jun 22 08:18:48 2005 From: mwm at idiom.com (Mike Meyer) Date: 22 Jun 2005 05:18:48 -0700 Subject: A tool for Python - request for some advice References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> Message-ID: <5jvf464maf.fsf@idiom.com> "TPJ" writes: > I've written this script in bash, because I thought it would be better > to have a script which would run in environment without Python (it all > was about installing Python anyway!). I used bash, dialog, wget... And > now someone suggested, that I shuld use Python. That using Python would > lead to clearer and - probably - smaller code. (I have to admit it - my > code in bash is just messy.) > > And now I'm considering this idea. Python is already present on > (almost?) every distribution today, so why worry about it's presence? Is your target platform Linux? I've seen the claim that every Linux distro comes with Python installed, but can't verify it. On the other hand, not every Unix distribution comes with Python installed. BSD systems for instance tend to be pretty minimalist. Solaris isn't minimalist, but you have to get Python from a third party. This is probably true of other commercial Unix distributions as well. MacOS X is a known exception - it comes with Python preinstalled. Then again, the same comments apply to bash. Distributions that have their roots in AT&T Unix probably don't come with bash by default, with Mac OS X being an exception. This makes depending on bash a bad idea if you want to write a script that portable across Unix distros. If your target platform is Linux, indications are that python is as portable as bash. If your target platform is Unix, then the same is true - except you shouldn't be writing bash if you want portability. Try reading for what's involved in writing portable shell scripts. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Sat Jun 18 07:38:11 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Jun 2005 21:38:11 +1000 Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> <1119088178.088667.227150@g44g2000cwa.googlegroups.com> <0001HW.BED9BDBF0048D1A8F0488550@news.individual.de> Message-ID: On Sat, 18 Jun 2005 12:02:07 +0200, Kalle Anke wrote: > On Sat, 18 Jun 2005 11:49:38 +0200, Xah Lee wrote > (in article <1119088178.088667.227150 at g44g2000cwa.googlegroups.com>): > >> the problem is that the page essentially says nothing. Nothing that is >> relevant to programing, and such nothingness occupies a significant >> portion of the python doc. (at least a quarter) It is like reading a >> manual to operate a machinery, and in every other paragraph it offers >> the (technically-fantastically-correct) explanations of what bolt or >> material were used where. > > I'm new to Python and the information that's in the docs (at least that > example) was what I was looking for. I read this as the referece manual, not > a cookbook or a tutorial which clearly requires another style of > documentation. At the risk of making an ad hominem attack, Xah Lee's posts usually have all the characteristics of Internet trolling. He unnecessarily cross-posts to multiple newsgroups. He makes sweeping generalizations and inflammatory criticisms based on little understanding. He frequently uses abusive language. He tries to critique Python as an expert, and yet frequently makes silly newbie mistakes or displays ignorance of some very basic Python features. http://en.wikipedia.org/wiki/Internet_troll http://www.teamtechnology.co.uk/troll.htm -- Steven. From riccardo_cut1 at cut2_sideralis.net Fri Jun 24 13:42:34 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Fri, 24 Jun 2005 19:42:34 +0200 Subject: Is there something similar to ?: operator (C/C++) in Python? References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote: >> Bo Peng wrote: >> >>> I need to pass a bunch of parameters conditionally. In C/C++, I can >>> do func(cond1?a:b,cond2?c:d,.....) >>> >>> Is there an easier way to do this in Python? >> >> > The answer is simply no, just use an if statement instead. That's not true. One used form is this: result = cond and value1 or value2 which is equal to if cond: result=value1 else: result=value2 another form is: result = [value2,value1][cond] the first form is nice but value1 must _always_ have a true value (so not None,0,'' and so on), but often you can handle this. Bye, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From Ara.T.Howard at noaa.gov Wed Jun 8 15:31:40 2005 From: Ara.T.Howard at noaa.gov (Ara.T.Howard) Date: Wed, 8 Jun 2005 13:31:40 -0600 Subject: MoinMoin WikiName and python regexes In-Reply-To: References: Message-ID: On Wed, 8 Jun 2005, Terry Reedy wrote: > > "Ara.T.Howard" wrote in message > news:Pine.LNX.4.62.0506080907300.18046 at harp.ngdc.noaa.gov... >> i'm trying to fix a bug in MoinMoin whereby > > A 'bug' is a discrepancy between promise (specification) and perfomance > (implementation). Have you really found such -- does MoinMoin not follow > the Wiki standard -- or are you just trying to customize MoinMoin to your > different specification. well, according to the specification at http://moinmoin.wikiwikiweb.de/WikiName?highlight=%28wikiname%29 ThisIsAWikiName there seems to be general agreement here http://wikka.jsnx.com/WikiName http://twiki.org/cgi-bin/view/TWiki/WikiWord though not a wikis agree. in moinmoin others have noted the inconsistency and filed a bug as noted in http://moinmoin.wikiwikiweb.de/MoinMoinBugs/AllCapsInWikiName?highlight=%28wikiname%29 the problem being that the specification is simply vague here and does not specifically prohibit AWikiName. > >> WordsWithTwoCapsInARowLike >> ^^ >> do not become WikiNames. > > Would your proposed change to make the above into an Wiki name also make > all-cap sequences like NATO, FTP, and API into WikiNames it wouldn't since NATO !~ /^([A-Z]+[a-z]+){2,}$/ FTP !~ /^([A-Z]+[a-z]+){2,}$/ API !~ /^([A-Z]+[a-z]+){2,}$/ the pattern is word = one, or more, upper case letters followed by one, or more, lower case letters wikiword = at least two words together so FOobar is not a link but AFooBar is > If WikiNum, appearing one place, were also mistyped as WikeNUm (from holding > down the shift key too long, which I do occasionally), should the latter > become a separate WikiName? I can certainly understand why the Wike > designers might have answered both questions 'No." perhaps - it's just inconsistent the way it is now. cheers. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso =============================================================================== From max at alcyone.com Tue Jun 28 11:28:50 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 28 Jun 2005 08:28:50 -0700 Subject: Dictionary to tuple In-Reply-To: <42c169d0$0$23811$626a14ce@news.free.fr> References: <42c169d0$0$23811$626a14ce@news.free.fr> Message-ID: bruno modulix wrote: > Err... don't you spot any useless code here ?-) > > (tip: dict.items() already returns a list of (k,v) tuples...) But it doesn't return a tuple of them. Which is what the tuple call there does. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis But when I reached the finished line / Young black male -- Ice Cube From rbt at athop1.ath.vt.edu Mon Jun 13 14:05:07 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 13 Jun 2005 14:05:07 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? Message-ID: Here's the scenario: You have many hundred gigabytes of data... possible even a terabyte or two. Within this data, you have private, sensitive information (US social security numbers) about your company's clients. Your company has generated its own unique ID numbers to replace the social security numbers. Now, management would like the IT guys to go thru the old data and replace as many SSNs with the new ID numbers as possible. You have a tab delimited txt file that maps the SSNs to the new ID numbers. There are 500,000 of these number pairs. What is the most efficient way to approach this? I have done small-scale find and replace programs before, but the scale of this is larger than what I'm accustomed to. Any suggestions on how to approach this are much appreciated. From michele.simionato at gmail.com Mon Jun 6 10:04:26 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Jun 2005 07:04:26 -0700 Subject: Destructive Windows Script In-Reply-To: References: <1118063741.854716.183560@g14g2000cwa.googlegroups.com> Message-ID: <1118066666.704002.5720@g47g2000cwa.googlegroups.com> The problem is that Google gives me too many non-relevant hits. I just would like something like this: $ rm what-I-think-is-an-useless-file ACK! It was not that useless!! $ recover what-I-think-is-an-useless-file Michele Simionato From hancock at anansispaceworks.com Mon Jun 27 13:47:57 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 27 Jun 2005 12:47:57 -0500 Subject: Life of Python In-Reply-To: References: Message-ID: <200506271247.58235.hancock@anansispaceworks.com> On Monday 27 June 2005 02:34 am, Alan Gauld wrote: > "Uwe Mayer" wrote in message > news:d9jcij$nm6$1 at news2.rz.uni-karlsruhe.de... > > con: If you are planning larger applications (for a reasonable > > [...] > > Then you will want to specify interfaces, accessor functions > with different > > read /write access, ... > > Why? What advantage does this really give you over indicative > doc strings? interfaces in particular are a modern madness. Interfaces, IMHO are best viewed as documentation. I have used the Zope 3 interfaces module, and I think it's going to be very useful to me. Although, theoretically, you could do all of this with doc strings, being able to check that you've documented everything that should be (including methods and attributes). With interfaces, you distribute the docstrings over the class. Also, the interpreter helps you with documentation problems, because standardized means are used to represent what methods expect as arguments, and so on. They don't really force you to do it that way, but they generally catch broken attempts to implement the interface. > Why not just define a class with a set of unimplemented methods. Takes too much time, and gets mixed in with functionality. Basically, it's more boilerplate than the better interface modules written for Python. > Who cares if someone tries to instantiate it? What can they do > with it? They only make sense in languages which are statically > typed and rely on inheritance to implement polymorphism. > Pure accessor methods are usually a mistake anyway, but can > be done using properties if you really must. Yes -- there's just no reason to do that in Python. Properties mean you don't have to worry about an attribute changing into a method, so there's no reason to try to "preempt the damage". No damage, so no preemption needed. I personally, really prefer attributes (or properties) over explicit get/set methods. > > Unless you have designed the software interactions completely > bevorehand > > (which never works out) this is the only way to incorporate > changes without > > refactoring your source all the time. > > On really big projects it is fairly normal to define the > structure of the code to quite a detailed level - often > using Case tools and UML etc - so refactoring is only needed > when you discover a hole. Thats true regardless of size of > project but the Case approach tends to limit the damage. Okay. This makes sense if the software is: 1) Designed by one institution. 2) Designed almost entirely before deployment. 3) Not designed to be worked on by users and semi-trained developers. In other words --- proprietary software. For a free-software application, in which you want to maximize your collaborative advantage, you want to make one-sided cooperation as easy as possible. I do not *know* who my collaborators will be. They may well not be privy to UML diagrams and CASE tools I may have used. Certainly a lot of them wouldn't bother to look if they could avoid it. OTOH, a well-defined set of interfaces shows them where they can make clean breaks in the design in order to localize what they need to learn and what they need to fix -- and it's all right there in the source code. It's just like fixing an old house. The biggest problem is knowing where to stop --- how much of that plumbing do you want to take out and rework? If it has cutoff valves and unions in the right places, it will come apart in sections and you have a much better chance of fixing it without getting into an intractable mess. Software interfaces can be used to the same effect --- making the job easier for the next person who comes along. If you are trying to trade on a free-software advantage, then it is absolutely in your best interest to make the way as easy as possible for the people who follow you. > > this should be expanded further, i.e. more build-in decorators > for > > interfaces, abstract classes, parameter and return value > restrictions. Specifically, *I* would like one of the available interface implementations to find its way into the standard library. Obviously, *my* life would be easier if it's the Zope 3 implementation, but I'll learn to use whatever gets in there. > What kind of parameter and return value restrictions? > In a dynamically typed language there is a limit to what can > be applied, and much of that is of limited value IMHO. Yes, there is a limit, and it's madness to go beyond it. But there is a useful middle ground. For example, it is quite useful to specify that an argument of a method should expect an object which implements a given interface. For simple objects, this is usually handled by things in the interface module. A method which expects a number may check that the object has __add__, __mul__, etc. But the real win is when it's supposed to be a much more elaborate object defined by the application. Intelligent use, of course, will suggest many cases where constraint is unnecessary boilerplate. But there are other situations where it's useful. > > with Perl than with Python and since there is no way of forcing > > I'm always uncomfortable about trying to "force" a programmer > to do it a certain way. > [...] > to believe that trying to force programmers rather than inform > them is a good idea. Yeah, IMHO, the Python way is to *suggest*, not *force*. I generally would consider it good style to provide test code that the application programmer can use to check out their classes during development. Of course, one of the points of this is that Python *does* provide these abilities, in contrast to what the OP said. They may not look quite like they do in Java, and they may not seem as "tough". But, IMHO, they are "tough enough". -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From aahz at pythoncraft.com Sat Jun 4 14:34:52 2005 From: aahz at pythoncraft.com (Aahz) Date: Sat, 4 Jun 2005 11:34:52 -0700 Subject: BayPIGgies: June 9, 7:30pm (IronPort) Message-ID: <20050604183452.GA29448@panix.com> The next meeting of BayPIGgies will be Thurs, June 9 at 7:30pm at IronPort. Drew Perttula will discuss his Python-based lighting system controller. The system includes a music player, a variety of programs to design and time light cues, and drivers for hardware that outputs the DMX protocol used by most theatrical lighting gear. BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://www.baypiggies.net/ Before the meeting, we may meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The July 14 meeting will be Alex Martelli's "Black Magic" talk. Advance notice: The August 11 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The only problem with Microsoft is they just have no taste." --Steve Jobs From chad.hughes at pnl.gov Fri Jun 17 14:04:15 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Fri, 17 Jun 2005 11:04:15 -0700 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6197@pnlmse27.pnl.gov> Thanks, I will keep that in mind. Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of Steven D'Aprano Sent: Friday, June 17, 2005 11:06 AM To: python-list at python.org Subject: RE: Overcoming herpetophobia (or what's up w/ Python scopes)? On Fri, 17 Jun 2005 10:22:05 -0700, Hughes, Chad O wrote: > Are you sure about the lower-case thing. The original post states > "Perlhead" and there are many instances at www.Perl.com where O'REILLY > spells perl as Perl. I did say "usually" :-) But in fact it seems that the creator of Perl/perl, Larry Wall, now distinguishes between the two spellings. From the FAQs: Q: What's the difference between "perl" and "Perl"? A: One bit. Oh, you weren't talking ASCII? :-) Larry now uses "Perl" to signify the language proper and "perl" the implementation of it, i.e. the current interpreter. Hence Tom's quip that "Nothing but perl can parse Perl." You may or may not choose to follow this usage. For example, parallelism means "awk and perl" and "Python and Perl" look OK, while "awk and Perl" and "Python and perl" do not. But never write "PERL", because perl is not an acronym, apocryphal folklore and post-facto expansions notwithstanding. http://faq.perl.org/perlfaq1.html -- Steven -- http://mail.python.org/mailman/listinfo/python-list From duncan.booth at invalid.invalid Thu Jun 9 04:48:21 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jun 2005 08:48:21 GMT Subject: multiple inheritance References: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> <1118305667.847406.58280@g44g2000cwa.googlegroups.com> Message-ID: newseater wrote: > if I only use the super() construct it seems not to call B > > > > > class A(object): > def foo(self): > print "a" > > class B(object): > def foo(self): > print "b" > > class C(A,B): > def foo(self): > print "c" > super(C,self).foo() > > > c = C() > > produces > c > a > > That is because a single call to super only calls a single method from one base class. Each call to super works out which is the next method that should be called and calls it, but it is then up to that method to ensure the call gets passed on along the chain. The problem with super is that you need to be sure to terminate that calling chain somehow. You can do what Andreas did, and use getattr to check for the existence of the base class method, but that gets messy. I find the easiest way is to define the interface in an abstract base class which deliberately doesn't pass the call upwards: class IFoo(object): def foo(self): pass class A(IFoo): def foo(self): print "a" super(A,self).foo() class B(IFoo): def foo(self): print "b" super(B,self).foo() class C(A,B): def foo(self): print "c" super(C,self).foo() >>> A().foo() a >>> B().foo() b >>> C().foo() c a b >>> You can also ask a class the order in which its base classes are examine for methods: >>> C.mro() [, , , , ] This is how super works, 'super(A, self)' when self is a C returns an object which will look at self.__class__.mro(), which is the list above, finds the class A, and then searches the remaining classes for matching attributes (B, IFoo, then object). The same super call on an instance of A gets a shorter list which doesn't include B as a possible target: >>> A.mro() [, , ] From dirgesh at gmail.com Sat Jun 4 14:19:45 2005 From: dirgesh at gmail.com (GujuBoy) Date: 4 Jun 2005 11:19:45 -0700 Subject: using boost to return list Message-ID: <1117909185.573323.80670@f14g2000cwb.googlegroups.com> i am trying to make a "cpp" file which will make an array and pass it to python as a list. how is this possible...i am using BOOST...please can someone point me at some examples thanks From steve at holdenweb.com Wed Jun 15 21:48:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 15 Jun 2005 21:48:00 -0400 Subject: New WYSIWYG Python IDE in the works In-Reply-To: <1118857896.992449.294690@z14g2000cwz.googlegroups.com> References: <1118857896.992449.294690@z14g2000cwz.googlegroups.com> Message-ID: Cappy2112 wrote: > This is great, but it might be worth finding out what the other IDE's > can do first, as well as their weaknesses. > > Eric3 seems to be the most popular & powerfull. Uop until recentluy, it > onluy works on Linux, but has been compiled & runnin on Windows, to > some degree of success. > > QTDesigner is pretty good. > > There's also Boa Constructor, and a handfull of other IDE's. > I's suggest the Boa Constructor be classed with [wx?]Glade and PythonCard as GUI builders, though I must confess I am not fully up to date on Boa developments. must-look-at-eric-sometime-ly y'rs - steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From calfdog at yahoo.com Thu Jun 23 00:21:13 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 22 Jun 2005 21:21:13 -0700 Subject: Pressing A Webpage Button In-Reply-To: References: Message-ID: <1119500473.910504.110920@g44g2000cwa.googlegroups.com> You also may want to fire an event when a button is pressed such as: ie.Document.forms['f'].elements['btnG'].FireEvent('onClick') Events: onclick Fires when the user clicks the left mouse button on the object. onsubmit Fires when a FORM is about to be submitted. For more go here: http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/reference/dhtml_reference_entry.asp Elliot Temple wrote: > How do I make Python press a button on a webpage? I looked at > urllib, but I only see how to open a URL with that. I searched > google but no luck. > > For example, google has a button how would i make a script to press that button? > > Just for fun, is there any way to do the equivalent of typing into a > text field like the google search field before hitting the button? > (I don't actually need to do this.) > > If someone could point me in the right direction it'd be appreciated. > > -- Elliot Temple > http://www.curi.us/ > > > --- > [This E-mail scanned for viruses by Declude Virus] From steve at REMOVETHIScyber.com.au Mon Jun 13 04:59:37 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 18:59:37 +1000 Subject: Request for help on naming conventions Message-ID: Are there any useful naming conventions for modules, classes and functions? For instance, should I name functions as verbs and classes as nouns? eg class Transformer(): pass def transform(): do_stuff What about the module name? transformations.py or transform.py? What do people do with their own code? Do folks find that being consistent helps them remember what is what, or do you name objects whatever feels right at the time? -- Steven. From dsa at unilestemg.br Tue Jun 7 17:08:34 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Tue, 7 Jun 2005 21:08:34 +0000 Subject: Binary numbers Message-ID: <200506072108.34547.dsa@unilestemg.br> Hi ! How to work with binary numbers in python ? Is there a way to print a number in its binary form like we do with oct() or hex() ? Im doing a project that i have to work with binaries and i tired of convert numbers to string all the time to perform some operations. I searched about it in many places like python.org and google, but not found anything useful. Thats why im asking this. And another question... if python has not a way to do this, why i let me use oct(), hex() and not bin() ? Thanks for the help ! -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From twic at urchin.earth.li Fri Jun 17 08:18:18 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 17 Jun 2005 13:18:18 +0100 Subject: Python & firewall control (Win32) In-Reply-To: References: Message-ID: On Fri, 17 Jun 2005, Tim Williams wrote: > On Thu, 16 Jun 2005, Tom Anderson wrote: > > > On Thu, 16 Jun 2005, Tim Williams wrote: > > > > > Does anyone know of (personal/desktop) firewall that can be > > > controlled via Python > > > > http://wipfw.sourceforge.net/ > > Tom, many thanks for that. I'm actually looking for a firewall (packet > filter) I can control in realtime from a Python application, I think you should be able to do that with wipfw ... > or even a Win32 equivalent of http://woozle.org/~neale/src/ipqueue/ . ... but i'm not sure about that! However, i'm not any sort of firewall or network expert, so it's possible that ipfw has some way to call out to external code to get decisions made (a sort of packet version of procmail's filter system) and that i don't know about it. > Though if I can stop & restart ipfw in a fraction of a second from > within a Python app then the result would be the same I guess. I will > have a play with it. AIUI, you won't be stopping and restarting ipfw - the ipfw command just modifies the ruleset being used by a continuously-running instance of the ipfw kernel module or daemon or whatever. How long it takes from starting the os.system call to the changes taking effect in the firewall, though, i have no idea - it might not be fast enough for you. I'd be surprised if it was more than a few hundred milliseconds, though, and really ought to be much, much faster than that. tom -- so if you hear a chaffinch out on the pull attempting a severely off-key version of "Sabotage" by the Beastie Boys then you're not actually going mad. From kevin at rustybear.com Thu Jun 2 10:29:44 2005 From: kevin at rustybear.com (kosuke) Date: 2 Jun 2005 07:29:44 -0700 Subject: optparse.py: FutureWarning error Message-ID: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> I keep getting the following error/warning message when using the python based program getmail4: /usr/lib/python2.3/optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up return ("<%s at 0x%x: %r>" I'm using python2.3.5 on a debian sid box. The getmail4 website/FAQ maintains that this is a bug in the optparse module. Any idea on how to resolve this? Thanks Kevin From merkosh at hadiko.de Thu Jun 23 14:28:05 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 23 Jun 2005 20:28:05 +0200 Subject: don't understand MRO References: Message-ID: Thursday 23 June 2005 19:22 pm Terry Reedy wrote: [...] > In the absence of other information, I would presume that none of the > other classes have a move() method. move() is implemented in the class qtcanvas.QCanvasItem I checked the pyqt sources and it is linked via sip to the C++ object file. In C++, QCanvasItem.move is delegated to QCanvasItem.moveBy. -- snip: C++ sources -- void QCanvasItem::move( double x, double y ){ moveBy( x-myx, y-myy ); } void QCanvasItem::moveBy( double dx, double dy ){ if ( dx || dy ) { removeFromChunks(); myx += dx; myy += dy; addToChunks(); } } -- snip -- > Are you sure that QCanvasItem has a move method? What results from >>>> print qtcanvas.QCanvasItem.move # ? > If so, I would need to see its code to try to answer. >>> import qtcanvas >>> qtcanvas.QCanvasItem.move Here is a working portion which recreates the strange output: -- snip -- from qtcanvas import * class Node(object): def move(self, x,y): print "Node: move(%d,%d)"%(x,y) class Rhomb(QCanvasPolygon, Node): def __init__(self, parent): QCanvasPolygon.__init__(self, parent) Node.__init__(self) print Rhomb.mro() r = Rhomb(None) r.move(1,2) -- snip -- This prints: [, , , , , , , ] Node: move(1,2) Ciao Uwe From ptmcg at austin.rr.com Wed Jun 22 13:36:32 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 22 Jun 2005 10:36:32 -0700 Subject: how to use more than 1 __init__ constructor in a class ? References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: <1119461792.058566.57420@g14g2000cwa.googlegroups.com> This recipe that I submitted to the Python Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223611) describes a technique for doing this. I use the example of creating Color objects for plotting to a bitmap, using either R,G,andB values, or a single integer representing the RGB encoded value. This style you describe is a Java language artifact. If you have optional params, then these really don't represent different method signatures. In my color example, you truly have different signatures, either 3 integers representing color components, or a single encoded integer. -- Paul From maitj at vianet.ca Thu Jun 16 10:30:04 2005 From: maitj at vianet.ca (Jeffrey Maitland) Date: Thu, 16 Jun 2005 10:30:04 -0400 Subject: What is different with Python ? In-Reply-To: <3hdfqlFgeeorU1@individual.net> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118914590.744021.53950@z14g2000cwz.googlegroups.com> <3hdfqlFgeeorU1@individual.net> Message-ID: <20050616143004.28558.qmail@mail.vianet.ca> Well as for the communication skills dropping. I highly doubt that, if anything you are just picking up on things you never noticed before (and your communication skills far surpass the average person that writes anything in todays' society). A good example for me is that I am noticing that I seem to type the like hte often, yes a spell checker picks it up but when writing code it's sometimes not available. Also I think the fact that you think your were diteriating just goes to show how dedicated you are to detail, and making sure you give the right advice or ask the right question. Jeff From lkirsh at cs.ubc.ca Fri Jun 24 05:32:49 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Fri, 24 Jun 2005 02:32:49 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: Check out lisp macros. Other languages have macro systems but none compare in power to lisp's. They are so powerful in lisp because lisp is the only language where the source code closely resembles its parse tree (created within the compiler/interpreter). Lowell Joseph Garvin wrote: > As someone who learned C first, when I came to Python everytime I read > about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > getattr/setattr, the % operator, all of this was very different from C. > > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > > Here's my current candidate: > > So the other day I was looking at the language Lua. In Lua, you make a > line a comment with two dashes: > > -- hey, this is a comment. > > And you can do block comments with --[[ and ---]]. > > --[[ > hey > this > is > a > big > comment > --]] > > This syntax lets you do a nifty trick, where you can add or subtract a > third dash to change whether or not code runs: > > --This code won't run because it's in a comment block > --[[ > print(10) > --]] > > --This code will, because the first two dashes make the rest a comment, > breaking the block > ---[[ > print(10) > --]] > > So you can change whether or not code is commented out just by adding a > dash. This is much nicer than in C or Python having to get rid of """ or > /* and */. Of course, the IDE can compensate. But it's still neat :) From claudio.grondi at freenet.de Thu Jun 16 12:12:44 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 16 Jun 2005 16:12:44 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118914590.744021.53950@z14g2000cwz.googlegroups.com> Message-ID: <3hdfqlFgeeorU1@individual.net> > My communication ability is dropping every day at Probably no reason to worry. Reading your post I haven't even noticed the unnecessary "not", because the message was clear as intended even with it, anyway. Should I start to be seriously in doubt about own physiological problems only because overseeing it? I think no. I think also, that many people here would confirm, that your posts are on a very high communication level showing much insight. > May indeed be I'm just *realizing* how low are my > communication skills... That's another story - moving to the next level of insight is usually a pain, because one detects how "stupid" one was before. Claudio schrieb im Newsbeitrag news:1118914590.744021.53950 at z14g2000cwz.googlegroups.com... > Andrea Griffini wrote: > > > That strings in python are immutable it's surely > > just a detail, and it's implementation specific, > > but this doesn't means it's not something you can > > ignore for a while. If you use python this is a > > *fundamental* property. > > My communication ability is dropping every day at > an incredible rate (it's getting so bad I've been > seriously in doubt about physiological problems). > In the above phrase there is a "not" in excess; I > meant to write > > ... but this doesn't means it's something you can > ignore for a while. If you use python this ... > > > May indeed be I'm just *realizing* how low are my > communication skills... > > Andrea > From stian at soiland.no Thu Jun 2 09:02:13 2005 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Thu, 2 Jun 2005 15:02:13 +0200 Subject: Newbie question: Allocation vs references In-Reply-To: <429efdbf$1@griseus.its.uu.se> References: <429efdbf$1@griseus.its.uu.se> Message-ID: <20050602130213.GE11767@itea.ntnu.no> On 2005-06-02 14:43:40, Jan Danielsson wrote: > a = [ 'Foo', 'Bar' ] > b = [ 'Boo', 'Far' ] > q = [ a, b ] > Or, better yet, how do I store a and b in q, and then tell Python > that I want a and b to point to new lists, without touching the contents > in q? There are several ways to create a copy of a list: a1 = a[:] # new copy, sliced from 0 to end a2 = list(a) # create a new list object out of any sequence import copy a3 = copy.copy(a) # use the copy module So you could do for example: q1 = [ list(a), list(b) ] q2 = [ a[:], b[:] ] q3 = [ list(x) for x in (a,b)] Note that the copy module also has a function deepcopy that will make copies at all levels. So if you had: q = [a,b] q1 = copy.deepcopy(q2) every list in q1, even the inner "a" and "b" will be new copies. Note that non-mutables such as "Foo" and "Bar" are NOT copied, but as they cannot be changed, that doesn't matter. -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] Og dette er en ekstra linje From cpu.crazy at gmail.com Thu Jun 2 14:00:44 2005 From: cpu.crazy at gmail.com (CPUFreak91) Date: 2 Jun 2005 11:00:44 -0700 Subject: Looking for Image, Audio and Internet/Web HOTWO's or tutorials Message-ID: <1117735244.363447.10340@f14g2000cwb.googlegroups.com> The Python Tutorials don't suply me with enough info and examples. If you know of any python tutorials or howto's please tell me, but preferably the Audio, Image, and Internet/Web ones. Thanks From philippe at philippecmartin.com Mon Jun 13 15:18:43 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 13 Jun 2005 19:18:43 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: > I don't buy that. I think there's a world of difference between knowing > what something does and how it does it; a black-box view of the memory > system (allocation + GC) is perfectly sufficient as a basis for > programming using it. That black-box view should include some idea of how > long the various operations take, but it's not necessary to understand how > it works, or even how pointers work, to have this. Maybe you should say programming at the application level. Also if you will notice from this newsgroup that people are sometimes trying to figure out how to optimize the speed of their application; you will also notice that the answers they get usually involve how Python is implemeted in their specific environment. I like analogies: twice in my career in and two different companies in two different industries, it was decided that the application should be prototyped on workstations and then ported to the embedded environment. Both times, the speed/size of the "ported" code was so bad that it was virtually unsusable. It was then decided to spend some time (it took years) optimizing the system(s) to make it feasible. I am conviced that if some of the target constraints had been taken into consideration from the beginning: 1) much less time would have been spent in the optimization process. 2) the architecture of the final piece of code would have been cleaner. Assuming I am correct, this implies that the folks working on the initial prototypes should fully understand the constraints of a realtime embedded environment (and that includes memory management) Regards, Philippe Tom Anderson wrote: > On Mon, 13 Jun 2005, Andrea Griffini wrote: > >> On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: >> >>>> Also concrete->abstract shows a clear path; starting in the middle and >>>> looking both up (to higher abstractions) and down (to the >>>> implementation details) is IMO much more confusing. >>> >>> At some point, you need to draw a line in the sand (so to speak) and >>> say, "I understand everything down to *here* and can do cool stuff with >>> that knowledge. Below that, I'm willing to take on faith". >> >> I think that if you don't understand memory, addresses and allocation >> and deallocation, or (roughly) how an hard disk works and what's the >> difference between hard disks and RAM then you're going to be a horrible >> programmer. >> >> There's no way you will remember what is O(n), what O(1) and what is >> O(log(n)) among containers unless you roughly understand how it works. >> If those are magic formulas you'll just forget them and you'll end up >> writing code that is thousands times slower than necessary. > > I don't buy that. I think there's a world of difference between knowing > what something does and how it does it; a black-box view of the memory > system (allocation + GC) is perfectly sufficient as a basis for > programming using it. That black-box view should include some idea of how > long the various operations take, but it's not necessary to understand how > it works, or even how pointers work, to have this. > > tom > From gene.tani at gmail.com Wed Jun 22 18:23:52 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jun 2005 15:23:52 -0700 Subject: Optimize a cache In-Reply-To: <7xoe9yt6ob.fsf@ruckus.brouhaha.com> References: <7xoe9yt6ob.fsf@ruckus.brouhaha.com> Message-ID: <1119479032.062850.318590@g47g2000cwa.googlegroups.com> i think ring buffer http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 From alangley at gmail.com Wed Jun 8 14:16:47 2005 From: alangley at gmail.com (Adam Langley) Date: Wed, 8 Jun 2005 19:16:47 +0100 Subject: [Pyrex] Allocating an array.array of a specific length in pyrex In-Reply-To: References: Message-ID: <396556a2050608111658e56203@mail.gmail.com> On 6/8/05, Chris Lambacher wrote: > My question is, is there a better way to > allocate the memory for the array.array object than: > a = array.array('B', [0] * (pixels * 2)) cdef unsigned char *buffer temp_string = PyString_FromStringAndSize(NULL, length) buffer = PyString_AsString(temp_string) That's one way to do it. But it looks like you just want an area of memory so why not: cdef extern from "stdlib.h": ctypedef unsigned long size_t void *malloc(size_t size) void free(void *mem) ? AGL -- Adam Langley agl at imperialviolet.org http://www.imperialviolet.org (+44) (0)7906 332512 PGP: 9113 256A CC0F 71A6 4C84 5087 CDA5 52DF 2CB6 3D60 From guy.lateur at b-b.be Thu Jun 23 03:49:10 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 23 Jun 2005 07:49:10 GMT Subject: Where is Word - COM solution Message-ID: Hi all, This goes back to my previous post called "Where is Word". In short, I wanted to make a temporary file (directory listing), open it in Word to let the user edit, layout and print it, and then delete the temp file afterwards. I almost got it to work without using COM, but there was a problem when the user runs the script a second time without closing Word after the first time. In that case, the temp file could not be deleted (see original post). Luckily, the following code was provided to me by a good fellow named Hughes, Chad O. Thanks again for your time and effort on this, Chad! import os from win32com.client import Dispatch dirlist = os.listdir(os.getcwd()) word = Dispatch('Word.Application') word.Documents.Add(Visible = True) word.Visible = True for line in dirlist: word.Selection.TypeText(line + '\r\n') So the questions 'where is Word' and 'how to delete the temp file' have become obsolete. Nice, eh? COM rules! Cheers, g From rkern at ucsd.edu Mon Jun 6 06:23:48 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 06 Jun 2005 03:23:48 -0700 Subject: how to show simulation at web In-Reply-To: References: Message-ID: Hallo wrote: > hi all, > > I have tried making a simulation with python. I want it to be shown at > a web. It is ok when I run it. so, I decided using cgi. but, when I try > it using a web browser it doesn't work. > > Is it problem in the header or something else ? > > If there are any suggestions about this problem, I will be very happy. First, read this: http://www.catb.org/~esr/faqs/smart-questions.html Then, come back and give us some substantive information about your problem. A small example of code that you think should work, but doesn't, will help us help you. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pinard at iro.umontreal.ca Wed Jun 15 10:32:20 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Wed, 15 Jun 2005 10:32:20 -0400 Subject: dynamic In-Reply-To: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> References: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> Message-ID: <20050615143220.GA100@alcyon.progiciels-bpi.ca> [Michele Simionato] > Having a class that returns instances of some other class is horrible, > [...] don't do it! Unusual, granted. Horrible, why? I found useful, sometimes, (ab)using Python syntax for representing data having more or less complex structure. More than once, it spared me the trouble of inventing a syntax, and then writing a lexer and a parser. Letting class constructors returning arbitrary objects has often been useful in such circumstances. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From codedivine at gmail.com Fri Jun 17 17:24:32 2005 From: codedivine at gmail.com (Rahul) Date: 17 Jun 2005 14:24:32 -0700 Subject: Multiple instances of a python program References: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> Message-ID: <1119043472.013942.233980@f14g2000cwb.googlegroups.com> Steven D'Aprano wrote: > On Thu, 16 Jun 2005 11:47:10 -0700, Rahul wrote: > > > Hi. > > I am part of a group in my univ where we organize a programming > > contest. In this contest we have a UDP based server. The server > > simulates a game and each contestant is to develop a team of virtual > > players. Each team is composed of 75 similar bots...i.e. governed by > > the same logic. Thus the contestant submits a single copy of the client > > and we instantiate the same program 75 times at the same time. > > The problem is that while executables from C source files are small and > > we can make 75 processes but we dont know what to do with python. > > > > If you have a python script and you want that 75 copies of the script > > be run simultaneously how will you do it? Is there anyway to do so > > without running 75 copies of the python interpreter simultaneously? > > Have you actually tested the performance of 75 instances of Python > running? Do you know that it will be too slow for your server, or are you > trying to optimize before testing? > > I wrote a short Python script, then launched 115 instances of Python > executing the script. There was no detectable slowdown of my system, which > is far from a high-end PC. > > The details of the script aren't important. It may even be that what I > tested is not even close to the load your server needs to deal with. But > you may be surprised at just how easily even a low-end PC copes 75 > instances of Python. Or perhaps not -- but the only way to tell is to try. Well...i havent tried (yes i hear "Premature optimization is evil evil evil i say") but the point was that if we can find a solution consuming less memory than we can even increase the number from 75 to lets say 200. as for hardware we have machines with 1.7 Ghz P4 and 128 mb ram. and i cant run them right now...since i am currently not in my univ...but asked now since we are planning right now and wanted to see which languages we can support. Probably c,c++,python and lisp using clisp...and java if we can find a way to avoid running 75 jvms...this year we supported c,c++,java and actually ran 75 jvms using 3 machines and it was horrible so we are looking for better ways for the 2006 contest. And we may port our server from java to python too but it seems not many people had python installed but most had java installed. rahul From andreas at kostyrka.org Thu Jun 30 07:24:21 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 30 Jun 2005 13:24:21 +0200 Subject: Store multiple dictionaries in a file In-Reply-To: References: Message-ID: <20050630112421.GA28901@heaven.kostyrka.org> How so? >>> import cPickle as cp >>> f=open("/tmp/test.pck", "wb") >>> cp.dump(dict(a=1), f) >>> cp.dump(dict(b=1), f) >>> f.close() >>> f=open("/tmp/test.pck", "rb") >>> cp.load(f) {'a': 1} >>> cp.load(f) {'b': 1} >>> cp.load(f) Traceback (most recent call last): File "", line 1, in ? EOFError >>> f.close() On Thu, Jun 30, 2005 at 11:32:27AM +0100, Philipp H. Mohr wrote: > Hello, > > I would like to store multiple dictionaries in a file, if possible one per > line. My code currently produces a new dictionary every iteration and > passes it on to another peace of code. In order to be able to re-run some > experiments at a later date I would like to store every dictionary in the > same file. > I looked at pickel, but that seems to require a whole file for each > dictionary. > > It would be great if some one could tell me how to do that. > > Thank you, > Phil > > -- > http://mail.python.org/mailman/listinfo/python-list From hrkorns at ccr.net Mon Jun 6 18:27:02 2005 From: hrkorns at ccr.net (Heather Korns) Date: 6 Jun 2005 15:27:02 -0700 Subject: PyRun_String does not appear to handle EInvalidOp exceptions Message-ID: <1118096822.381396.164210@g14g2000cwa.googlegroups.com> Here's a snippet of code that demonstrates my problem: result = PyRun_String ("import math", Py_file_input, pdict,pdict); result = PyRun_String ("math.sqrt(-1)", Py_file_input, pdict,pdict); result = PyRun_String ("math.pow(2,1024)", Py_file_input, pdict,pdict); Other types of exceptions seem to be handled properly by PyRun_String; however, EInvalidOp or EOverflow exceptions do not seem to be handled. My application is unable to recover gracefully after this exception occurs. Has anyone else run into this problem? Thanks. From thorsten at thorstenkampe.de Wed Jun 29 06:26:50 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 29 Jun 2005 11:26:50 +0100 Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> <5aj2c11l5vl4qds031uj7ucikikcf7uvji@4ax.com> Message-ID: <1e8524e0tgh18$.km3m85gcrjgm$.dlg@40tude.net> * Richie Hindle (2005-06-28 14:44 +0100) > [Christos, on widening the Windows Command Prompt] >> Hm... right-click the cmd.exe window's title bar (or click on the >> top-left icon, or press Alt-Space), go to Properties, Layout tab, Window >> Size, Width. > > Just to take this thread *completely* off-topic: does anyone know of a way > to scroll a Command Prompt window using the keyboard? [Shift+PageUp/Down]: rxvt (Cywin). Unfortunately only per page; if you want to scroll one line you have to use the scrollbar. From zathras at thwackety.com Mon Jun 20 15:16:29 2005 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 20 Jun 2005 20:16:29 +0100 Subject: Embedded Systems Python? References: <11bdnto1au02i63@corp.supernews.com> Message-ID: <42b71612$0$3140$ed2619ec@ptn-nntp-reader01.plus.net> Dennis Clark wrote: ... > Has anyone, or is anyone working with Python in an embedded Linux > environment? Mine is NO where near as constrained as a cell phone since > I've got plenty of memory to work with, I'm just running a Linux 2.4 > kernel on an ARM9 platform. This really shouldn't be a problem - especially given python can be made to run on mobile phones (Nokia Series 60). We've found using python on Series 60 phones to be quite useful, so if you're using a linux box, you're presumably got more memory/CPU available than there, so I doubt you'll see major problems. Regards, Michael. -- http://kamaelia.sourceforge.net/ From darkpaladin79 at hotmail.com Thu Jun 30 10:23:30 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 30 Jun 2005 10:23:30 -0400 Subject: Open the command line within a script Message-ID: Hey this is probally a noob question but here goes. . .How could I open the command line inside of a python script? Would I have to use COM? -Ivan _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From newsgroups at jhrothjr.com Tue Jun 28 14:13:18 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 28 Jun 2005 12:13:18 -0600 Subject: Dictionary to tuple References: <42c16464$0$26260$626a14ce@news.free.fr> Message-ID: <11c34q4djv5u4f6@news.supernews.com> "bruno modulix" wrote in message news:42c16464$0$26260$626a14ce at news.free.fr... > Odd-R. wrote: >> I have a dictionary, and I want to convert it to a tuple, >> that is, I want each key - value pair in the dictionary >> to be a tuple in a tuple. >> >> If this is the dictionary {1:'one',2:'two',3:'three'}, >> then I want this to be the resulting tuple: >> ((1,'one'),(2,'two'),(3,'three')). >> >> I have been trying for quite some time now, but I do not >> get the result as I want it. Can this be done, or is it not >> possible? > > It's of course possible, and even a no-brainer: > > dic = {1:'one',2:'two',3:'three'} > tup = tuple(dic.items()) I think I'll add a little clarification since the OP is really new to Python. The (dict.items()) part of the expression returns a list, and if you want to sort it, then you need to sort the list and then convert it to a tuple. dic = {1:'one',2:'two',3:'three'} dic.sort() tup = tuple(dic) This points up the fact that the final conversion to a tuple may not be necessary. Whether or not is is depends on the circumstances. >> I must also add that I'm new to Python. > Welcome on board. > John Roth > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From claudio.grondi at freenet.de Fri Jun 17 11:06:08 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 17 Jun 2005 15:06:08 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: <3hg08rFh2tr3U1@individual.net> >> there is a 1% of people extremely interested in turning >> on or off a pixel I taught "adults" aged from 16 to 86 for some years a course "Introduction to data processing", where I had tried to teach the basics beginning with switching light on and off. Having around twenty participants I experienced from time to time one or two who found it fascinating, so the 1% is in my eyes a good guess. > 40x50. Probably nowdays unless you show them an antialiased > texture mapped 3D floating torus with their name and > face on it in live video they'll prefer exchanging > stupid messages with the mobile phone instead. The ability of making a video (I currently experience a run towards "equipping" videos from camcorders showing the involved teenager fighting using ordinary sticks with StarWars laser sword effects) when equipped with appropriate software tool is given now even to the not gifted 99%. After the videos are done by the a little bit smarter ones of the entire group, it doesn't whetting the apetite for more programming skills - it creates traffic on ICQ and Internet by exchanging the videos and the opinions if they are cool or not. > If it's about the time it will take to get a rotating > 3d torus with live video on it I know for sure that most > of the programmers I know that started from high level > will probably *never* reach that point. Many consider such skills as not worth to achieve, looking for a solution to eventually raising problems in a better computer hardware and new software tools in case of timing problems. Generally it appears to me, that it is true that many of current teenagers look for authorities not for own experience (this is nothing new) and that they perceive the world around them through the window of the Internet browser not through the window of the room (this is what makes the difference compared to past time). But the current world they experience is so different from what it was twenty years ago, that it is today sure possible to start on a very high level and stay there all the life never beeing able to go down to the details without having therefore serious disadvantages as a programmer. I experienced beeing very surprised myself, that it is even possible to be hired as a programmer having an IQ below the level of around 80. I am personally biased towards trying to understand anything as deep as possible and in the past was quite certain, that one can not achieve good results without a deep insight into the underlying details. I have now to admit, that I was just wrong. From my overall experience I infer, that it is not only possible but has sometimes even better chances for success, because one is not overloaded with the ballast of deep understanding which can not only be useful but also hinder from fast progress. Claudio "Andrea Griffini" schrieb im Newsbeitrag news:ofc5b1plbui6n61qpr9iv421ranugbq82q at 4ax.com... > On 17 Jun 2005 01:25:29 -0700, "Michele Simionato" > wrote: > > >I don't think anything significant changed in the percentages. > > Then why starting from > > print "Hello world" > > that can't be explained (to say better it can't be > *really* understood) without introducing a huge > amount of magic and not from a simple 8 bit CPU > instead ? What are the pluses of the start-from-high-level > approach ? If one is to avoid bordeom I don't agree > as assembler is all but boring (when you start), > or at least this was what *I* experienced. > > If it's about the time it will take to get a rotating > 3d torus with live video on it I know for sure that most > of the programmers I know that started from high level > will probably *never* reach that point. Surely if > you start say from pull-down menus they'll be able to > do pull down menus. And IMO there are good chances > they'll stay there lifetime. > > So is python the good first programming language ? > IMO not at all if you wanna become a programmer; it > hides too much and that hidden stuff will bite back > badly. Unless you know what is behind python it will > be almost impossible for you to remember and avoid > all the traps. Buf if you need to know what is behind > it then it's better to learn that stuff first, because > it's more concrete and simpler from a logical point > of view; the constructions are complex but (because) > the bricks are simpler. > > But it probably all boils down to what is a programmer. > > Is C++ a good first programming language ? > > BWHAHAHAHAHAHAHAHA :D > > But apparently some guru I greatly respect thinks so > (I'm not kidding, http://www.spellen.org/youcandoit/). > > Andrea From donn at u.washington.edu Fri Jun 10 15:07:43 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 10 Jun 2005 12:07:43 -0700 Subject: without shell References: <11aj9d3fga9or8b@corp.supernews.com> <11ajkap3isrmndf@corp.supernews.com> Message-ID: In article <11ajkap3isrmndf at corp.supernews.com>, Grant Edwards wrote: ... > According to the current module reference, that's the behavior > of the os.popen*() functions: > > http://docs.python.org/lib/os-newstreams.html#os-newstreams > > > On UNIX, os.popen is posix.popen, is a simple wrapper around > > the C library popen. It always invokes the shell. > > Not according the the docs: > > Also, for each of these variants, on Unix, cmd may be a > sequence, in which case arguments will be passed directly to > the program without shell intervention (as with os.spawnv()). > If cmd is a string it will be passed to the shell (as with > os.system()). > > It's not exactly clear what "these variants" refer to, but I > read it as referring to all of the the os.popen functions. > > Perhaps it only refers to os.popen[234]? Right. The paragraphs seem a little scrambled. Note the use of "cmd" instead of "command" as the parameter is named for popen(). Also note "These methods do not make it possible to retrieve the return code from the child processes", after the popen() paragraph above tells you how to do it (using the better term "exit status".) Or one may look at the source. Donn Cave, donn at u.washington.edu From fredrik at pythonware.com Wed Jun 15 07:23:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Jun 2005 13:23:59 +0200 Subject: Elementtree and CDATA handling References: <1117631202.723453.20060@z14g2000cwz.googlegroups.com> Message-ID: Terry Reedy wrote: >> the above are six ways to write the same string literal in Python. > > Minor nit: I believe 'hell' + 'o' is two string literals and a runtime concatenation operation. I guess I should have written "constant". on the other hand, while the difference might matter for current python interpreter implementations, it doesn't really matter for the user. after the operation, they end up with a string object that doesn't contain what they wrote. From thomas at thomas-lotze.de Wed Jun 22 15:52:14 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Wed, 22 Jun 2005 21:52:14 +0200 Subject: Package organization References: <42b9b96f$0$32342$636a15ce@news.free.fr> Message-ID: F. Petitjean wrote: > As you whish :-) Damn freedom of choice *g > if in the package ie in the __init__.py (not the best idea) from PDF > import File as PDFFile # always possible Technically, this is clear - however I don't like the idea of giving the same thing different names, especially if there's a chance that other people get to look at and try to understand the code... Using short names being unique by virtue of the subpackage hierarchy internally and leaving it to the user (which might even be another subpackage of the library) to import it as something more descriptive in his context is probably the easiest, cleanest and least obtrusive thing, as I think about it. > Have you installed the reportlab package ? It is full of from ... import > .. and it generates PDF. I do know ReportLab. IIRC, last time I looked, it didn't simply expose an API that models and operates on a PDF document's structures, but was designed to produce PDF files with a certain kind of content. It didn't seem to be of much easy use for anything wildly different from that. -- Thomas From deets at web.de Fri Jun 10 10:57:57 2005 From: deets at web.de (Diez B. Roggisch) Date: Fri, 10 Jun 2005 16:57:57 +0200 Subject: Dealing with marketing types... In-Reply-To: <42a9a5c8$0$22628$da0feed9@news.zen.co.uk> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <42a9a5c8$0$22628$da0feed9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Marketing types need a bandwagon to jump on. Point out that Google is > used by Google, ILM and NASA. Certainly a true statement - but I've got the sneaky suspicion that the first google was supposed to be python. Diez From bedouglas at earthlink.net Sun Jun 12 14:01:22 2005 From: bedouglas at earthlink.net (bruce) Date: Sun, 12 Jun 2005 11:01:22 -0700 Subject: Dealing with marketing types... In-Reply-To: Message-ID: <1a9b01c56f78$bed1db30$0301a8c0@Mesa.com> just out of curiosity.. where'd you read the 150,000-200,000 servers... i've never seen guesses that high.. i've seen somewhere as high as possible 100K... but the author stated that he was purely guessing... -bruce -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Terry Reedy Sent: Sunday, June 12, 2005 9:48 AM To: python-list at python.org Subject: Re: Dealing with marketing types... "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xwtp09jh3.fsf at ruckus.brouhaha.com... > Andrew Dalke writes: >> If that's indeed the case then I'll also argue that each of >> them is going to have app-specific choke points which are best >> hand-optimized and not framework optimized. Is there enough >> real-world experience to design a EnterpriseWeb-o-Rama (your >> "printing press") which can handle those examples you gave >> any better than starting off with a LAMP system and hand-caching >> the parts that need it? > > Yes, of course there is. Look at the mainframe transaction systems of > the 60's-70's-80's, for example. Look at Google. Based on what I've read, if we could look at Google, we would see 150,000 to 200,000 servers (about half bought with IPO money). We would see a highly customized dynamic cluster computing infrastructure that can be utilized with high-level (Python-like) commands. The need to throw hundreds of machines at each web request strikes me as rather specialized, though definitely not limited to search. So while not LAMP, I don't see it as generic EWeboRama either. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list From gsakkis at rutgers.edu Sat Jun 25 14:51:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Jun 2005 11:51:59 -0700 Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> <1119707062.260303.185590@g47g2000cwa.googlegroups.com> Message-ID: <1119725519.910753.98190@g47g2000cwa.googlegroups.com> "Steven D'Aprano" wrote: > On Sat, 25 Jun 2005 06:44:22 -0700, George Sakkis wrote: > > > "Roy Smith" wrote: > > > >> I just re-read the documentation on the dict() constructor. Why does it > >> support keyword arguments? > >> > >> dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"} > >> > >> This smacks of creeping featurism. Is this actually useful in real code? > >> It took me several readings of the doc to understand what this was doing. > >> Essentially, it's Perl's bareword syntax, and once I realized that, I > >> simultaneously understood what was happening and was revolted that Python > >> seems to have picked up one of Perl's most bizarre and confusing features. > > > > The worst thing about this form of the dict constructor it's not the > > syntax; I think this becomes obvious after you've seen it once. More > > annoying is that it "wastes" keyword arguments that could otherwise be > > used to determine the characteristics of the dict. Perhaps the most > > common desired feature is setting a default value for the dict, that > > would allow for instance: > > > > wordCount = dict(default=0) > > wordPos = dict(default=[]) > > for pos,word in enumerate(text): > > wordCount[word] += 1 > > wordPos[word].append(pos) > > > > Other candidate optional arguments would allow type checking (e.g. > > dict(keys=int, values=list)) or performance fine-tuning (e.g. > > dict(minsize = 10, maxsize = 10000, average = 200)). I hope the > > decision for this form of the constructor is reconsidered for python > > 3K. > > Since Python dicts don't have default values, or type-checking, or > user-editable performance fine-tuning, or for that matter any optional > arguments, it is hardly possible to "waste" keyword arguments for a > function that doesn't need any keyword arguments. > > What you actually mean to say is that the use of keyword arguments as > "bareword" syntax for initialising dicts conflicts with the use of keyword > arguments for non-existent, hypothetical and/or user-defined classes. > > That's okay. I'm perfectly comfortable with the fact that the syntax for > initialising a dict conflicts with the syntax for initialising a list, a > Decimal, a MutableString, and a ConfigParser object. > > So why should I be distressed that it conflicts with the syntax for > initialising MyDictWithDefaultValue objects? Because this specific use case at least is/was considered useful enough to start off a thread that invited over a hundred posts on a pre-PEP suggesting two new accumulator methods (http://tinyurl.com/aqpk3). Default-valued dicts make the two proposed methods redundant and are a more elegant solution to the dictionary based accumulation problem. So yes, one can write MyDictWithDefaultValue (and I'm sure many have), but the keyword-arg dict constructor prevents python from including it in the future without breaking backwards compatibility. George From hancock at anansispaceworks.com Wed Jun 1 15:50:34 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Jun 2005 14:50:34 -0500 Subject: [OT] SQL-records and OOP In-Reply-To: <20050530093514.GA3695@hccnet.nl> References: <20050530093514.GA3695@hccnet.nl> Message-ID: <200506011450.34332.hancock@anansispaceworks.com> On Monday 30 May 2005 04:35 am, egbert wrote: > Each row of an sql table may be the data_part_in_spe > of some class_instance. > I try to think about, and am looking for, the do's and don'ts > and caveat's and the right way of thinking about this transformation. > For me it is new territory. > > For instance, my sql-query produces much more rows than I am > interested in eventually. So I have to narrow this collection. > > I can inspect the data while it is still a list of rows, > and make instances of only the rows I really need. > Or I may create an aggregate of full-blown instances derived > from all the selected rows. Zope has (or had) an object called a "Pluggable Brain" that was for this kind of use, but I found that, outside of "through the web programming" in Zope, it was more trouble than it was worth. The simplest approach is to define the class without any data or with default data. Parse and reduce your rows, then return a list of objects by wrapping the data: class SmartRow: a, b, c = 0,0,0 def __init__(self, rowdata): self.a, self.b, self.c = rowdata # [...] dumb_data = select_rows_you_need() smart_data = [SmartRow(r) for r in dumb_data] I don't think there's really much overhead in creating Python classes. In any case, it's never been an issue for me. But I'd still recommend only wrapping the data after you've already reduced the number of rows as much as possible. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From newsgroups at jhrothjr.com Wed Jun 8 18:11:29 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 8 Jun 2005 16:11:29 -0600 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> <1118259397.502842.260270@z14g2000cwz.googlegroups.com> Message-ID: <11aer8n2vc74839@news.supernews.com> "Jordan Rastrick" wrote in message news:1118259397.502842.260270 at z14g2000cwz.googlegroups.com... > Well, I'll admit I haven't ever used the Numeric module, but since > PEP207 was submitted and accepted, with Numeric as apparently one of > its main motivations, I'm going to assume that the pros and cons for > having == and ilk return things other than True or False have already > been discussed at length and that argument settled. (I suppose theres a > reason why Numeric arrays weren't just given the same behaviour as > builtin lists, and then simple non-special named methods to do the > 'rich' comparisons.) They were - read the PEP again. That's the behavior they wanted to get away from. > But again, it seems like a pretty rare and marginal use case, compared > to simply wanting to see if some object a is equal to (in a non object > identity sense) object b. > > The current situation seems to be essentially use __cmp__ for normal > cases, and use the rich operations, __eq__, __gt__, __ne__, and rest, > only in the rare cases. Also, if you define one of them, make sure you > define all of them. > > Theres no room for the case of objects where the == and != operators > should return a simple True or False, and are always each others > complement, but <, >= and the rest give an error. I haven't written > enough Python to know for sure, but based on my experience in other > languages I'd guess this case is vastly more common than all others put > together. > > I'd be prepared to bet that anyone defining just __eq__ on a class, but > none of __cmp__, __ne__, __gt__ etc, wants a != b to return the > negation of a.__eq__(b). It can't be any worse than the current case of > having == work as the method __eq__ method describes but != work by > object identity. To quote Calvin Coolege: You lose. The primary open source package I work on, PyFit, always wants to do an equal comparison, and never needs to do a not equal. It also has no use for ordering comparisons. I do not equals as a matter of symmetry in case someone else wants them, but I usually have no need of them. Strict XP says I shouldn't do them without a customer request. > So far, I stand by my suggested change. I think most of your justification is simple chicken squaking, but write the PEP anyway. I'd suggest tightening it to say that if __eq__ is defined, and if neither __ne__ nor __cmp__ is defined, then use __eq__ and return the negation if and only if the result of __eq__ is a boolean. Otherwise raise the current exception. I wouldn't suggest the reverse, though. Defining __ne__ and not defining __eq__ is simply perverse. John Roth > From peter at engcorp.com Fri Jun 10 07:59:36 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Jun 2005 07:59:36 -0400 Subject: Exe file In-Reply-To: References: Message-ID: <2LCdnd3tfdJPHDTfRVn-pg@powergate.ca> Philip Seeger wrote: >>>I'm sorry for that newbie question but how can I compile a program (a .py >>>file) to an executable file? ... > For easier distribution. Otherwise the client computer had to have Python > installed. In that case, and since you appear to be running on Windows (judging by the headers in your post), look for "py2exe". You may also want to use InnoSetup or another free installer, since py2exe does the packaging you want but doesn't bundle the files all together for easy installation. Py2exe plus InnoSetup is a very widely used and appreciated combo. -Peter From ramen at lackingtalent.com Fri Jun 3 20:22:57 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 03 Jun 2005 17:22:57 -0700 Subject: Removing a warnings filter? In-Reply-To: <87ekbj8pz6.fsf@wilson.rwth-aachen.de> References: <87ekbj8pz6.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > When I add a warning filter with warnings.filterwarnings, how can I > get rid of it? I've read about resetwarnings(), but it removes all > filters, even those that I didn't install in a certain function. I have never used this module, but judging by a quick glance of the source to "warnings.py", it appears that warning filters are added to a list called "warnings.filters". They are added to the beginning of the list unless you pass a true value for the "append" parameter of "filterwarnings", in which case they are added to the end. The usual way to remove items from a list apply, ie.: del warnings.filters[0] # if append was false del warnings.filters[-1] # if append was true Note that all of these operations modify module data, which could have implications in multithreaded programs. If your program is multithreaded, you may want to consider using locks. Hope this helps, Dave From timr at probo.com Wed Jun 1 18:05:11 2005 From: timr at probo.com (Tim Roberts) Date: Wed, 01 Jun 2005 15:05:11 -0700 Subject: Pressing A Webpage Button References: Message-ID: Elliot Temple wrote: > >How do I make Python press a button on a webpage? I looked at >urllib, but I only see how to open a URL with that. I searched >google but no luck. > >For example, google has a button how would i make a script to press that button? > >Just for fun, is there any way to do the equivalent of typing into a >text field like the google search field before hitting the button? >(I don't actually need to do this.) Both things are done the same way. The Google Search button is a field named "btnG" with the value "Google Search". The query field itself is named "q". Then, if you look at the HTML, you'll see that this is wrapped in a
with the action "/search". So, all you need to do, then, is to encode all this in a URL: http://www.google.com/search?btnG=Google%20Search&q=python%20urllib This only works because the Google "search" page accepts parameters using the "GET" method, which is what you get when you send parameters in the URL. Many forms only accept parameters using the "POST" method, in which you send the encoded parameters as the body of the HTTP request. You probably need to do some reading on HTTP, and the GET and POST methods of transmitting parameters. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From pmelone at stratalight.com Tue Jun 14 15:15:14 2005 From: pmelone at stratalight.com (Patrick Melone) Date: Tue, 14 Jun 2005 12:15:14 -0700 Subject: contract python developer in Campbell is needed at Stratalight Message-ID: I understand that job listings are ok on this board so... StrataLight Communications, a 40 GB/s DWDM transport system company, develops innovative fiber transmission subsystems for use by carriers in building next-generation long-haul optical networks. We are located in Campbell CA. and are looking for a contract python developer. www.stratalight.com Development of Python scripts to automate the test execution of OTS-4000 linecards and the development of a test and measurement database that will be used for pass/fail determination and test report generation. * Extensive experience with Python. * BSCS/EE and 3 to 5 years of work experience * Hands on experience with electrical and optical test instruments. * Strong technical (e.g., programming) and analytical skills * Strong working knowledge database schema development and mySQL * Familiar with Linux operating system * Strong interpersonal skills * Desire to engage in extremely challenging assignments. * Excellent verbal and written communication skills, and strong collaborative skills. * Self-managed proactive work style and the ability to work independently and in a team environment. * Strong organizational and problem solving abilities If interested please contact: Patrick Melone StrataLight Communications pmelone at stratalight.com ph) 408/961-6250 fax)408/626-9440 -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Wed Jun 22 23:05:16 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Jun 2005 03:05:16 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <11bk9jf5s6gk204@corp.supernews.com> Message-ID: <11bk9ncdhun9h8e@corp.supernews.com> On 2005-06-23, Grant Edwards wrote: > On 2005-06-23, Tim Peters wrote: > >> C89 doesn't define the result of that, but "most" C compilers these >> days will create a negative 0. >> >>> and (double)0x80000000 doesn't work, > > I think you meant something like > > float f; > *((uint32_t*)&d) = 0xNNNNNNNN; *((uint32_t*)&f) = 0xNNNNNNNN; It doesn't matter how many times one proofreads things like that... -- Grant Edwards grante Yow! I will establish at the first SHOPPING MALL in visi.com NUTLEY, New Jersey... From k04jg02 at kzoo.edu Fri Jun 24 02:55:38 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Fri, 24 Jun 2005 00:55:38 -0600 Subject: Favorite non-python language trick? Message-ID: <42BBAE6A.1040100@kzoo.edu> As someone who learned C first, when I came to Python everytime I read about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), getattr/setattr, the % operator, all of this was very different from C. I'm curious -- what is everyone's favorite trick from a non-python language? And -- why isn't it in Python? Here's my current candidate: So the other day I was looking at the language Lua. In Lua, you make a line a comment with two dashes: -- hey, this is a comment. And you can do block comments with --[[ and ---]]. --[[ hey this is a big comment --]] This syntax lets you do a nifty trick, where you can add or subtract a third dash to change whether or not code runs: --This code won't run because it's in a comment block --[[ print(10) --]] --This code will, because the first two dashes make the rest a comment, breaking the block ---[[ print(10) --]] So you can change whether or not code is commented out just by adding a dash. This is much nicer than in C or Python having to get rid of """ or /* and */. Of course, the IDE can compensate. But it's still neat :) From kveretennicov at gmail.com Sun Jun 26 07:52:27 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sun, 26 Jun 2005 13:52:27 +0200 Subject: noob question In-Reply-To: <42BE37C0.3000306@maudit.net> References: <42BE37C0.3000306@maudit.net> Message-ID: <4660fe30050626045259a87fdb@mail.gmail.com> On 6/26/05, Matt Hollingsworth wrote: > Seems like an _extremely_ elegent language that is very easy to read, so > I suppose it's not really as much of an issue as it is with other > languages. Still, I would like to see what other people do and what are > some good ideas for this kind of thing. Nouns-for-variables vs. verbs-for-functions work for me equally well in Python, C++ and C#. I rarely feel the need for hungarian notation, but it has it's uses (and abuses); see http://joelonsoftware.com/articles/Wrong.html - kv From lbates at syscononline.com Tue Jun 14 19:21:37 2005 From: lbates at syscononline.com (Larry Bates) Date: Tue, 14 Jun 2005 18:21:37 -0500 Subject: Opening a drive folder from Python In-Reply-To: <1118790092.280400.54930@z14g2000cwz.googlegroups.com> References: <1118790092.280400.54930@z14g2000cwz.googlegroups.com> Message-ID: <42AF6681.7000905@syscononline.com> You should supply more information: What operating system? What do you mean by "drive folder"? Does this mean file dialog? Or perhaps you mean an Explorer Window? Larry Bates John Henry wrote: > Can somebody please tell me how to pop open a drive folder from a > Python script? > > Thanks. > > -- > John > From steve at REMOVETHIScyber.com.au Fri Jun 17 14:06:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Jun 2005 04:06:19 +1000 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? References: Message-ID: On Fri, 17 Jun 2005 10:22:05 -0700, Hughes, Chad O wrote: > Are you sure about the lower-case thing. The original post states > "Perlhead" and there are many instances at www.Perl.com where O'REILLY > spells perl as Perl. I did say "usually" :-) But in fact it seems that the creator of Perl/perl, Larry Wall, now distinguishes between the two spellings. From the FAQs: Q: What's the difference between "perl" and "Perl"? A: One bit. Oh, you weren't talking ASCII? :-) Larry now uses "Perl" to signify the language proper and "perl" the implementation of it, i.e. the current interpreter. Hence Tom's quip that "Nothing but perl can parse Perl." You may or may not choose to follow this usage. For example, parallelism means "awk and perl" and "Python and Perl" look OK, while "awk and Perl" and "Python and perl" do not. But never write "PERL", because perl is not an acronym, apocryphal folklore and post-facto expansions notwithstanding. http://faq.perl.org/perlfaq1.html -- Steven From guettli at thomas-guettler.de Thu Jun 23 10:32:22 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 23 Jun 2005 16:32:22 +0200 Subject: PEP 304 - is anyone really interested? References: Message-ID: Am Wed, 22 Jun 2005 18:01:51 -0500 schrieb Skip Montanaro: > > I wrote PEP 304, "Controlling Generation of Bytecode Files": > > http://www.python.org/peps/pep-0304.html > ... Hi, I am interested in a small subset: I want to import a file without a '.pyc' being generated. Background: I sometimes missuse python for config files. For example there is a file $MYAPP/etc/debuglog.py. This file contains simple assignments search=0 indexing=1 .... In the code I use it like this: sys.path.append(...) # Put $MYAPP/etc into the path import debuglog ... if debuglog.search: print "Searching for ...." I don't want pyc files in the etc directory. Up to now I do it like this: import debuglog try: os.unlink("...debuglog.pyc") except: pass Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From gsakkis at rutgers.edu Sun Jun 12 10:35:11 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jun 2005 07:35:11 -0700 Subject: How to get/set class attributes in Python References: <1118573802.257329.271860@g43g2000cwa.googlegroups.com> Message-ID: <1118586911.189555.244470@g14g2000cwa.googlegroups.com> "alex23" wrote: > Kalle Anke wrote: > > I'm coming to Python from other programming languages. I like to > > hide all attributes of a class and to only provide access to them > > via methods. > > I'm pretty fond of this format for setting up class properties: > > class Klass(object): > def propname(): > def fget: pass > def fset: pass > def fdel: pass > def doc: """pass""" > return locals() > propname = property(**propname()) > > (Replacing 'pass' in the getters & setters et.al with the actual > functionality you want, of course...) > > This method minimises the leftover bindings, effectively leaving the > getter/setter methods bound only to the property, ensuring they're only > called when the property is acted upon. > > Incidentally, kudos & thanks to whomever I originally stole it from :) > > -alex23 And a slight improvement in readability IMHO (for python 2.4+) is the following recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/410698. Using the Property decorator, the property declaration above becomes: class Klass(object): @Property # <--- the capitalized 'P' is not a typo def propname(): '''Documentation''' def fget: pass def fset: pass def fdel: pass The Property decorator peeks automagically the fget, fset, fdel and __doc__ from the property's locals(), instead of having the property return locals() explicitly. Also, it doesn't break when the property defines local variables other than [fget, fset, fdel, doc]. George From gdub at ece.utexas.edu Fri Jun 10 10:23:08 2005 From: gdub at ece.utexas.edu (Gary Wilson Jr) Date: Fri, 10 Jun 2005 09:23:08 -0500 Subject: Perl s/ To Python? In-Reply-To: <42A99C41.6050207@plus.net> References: <42A99C41.6050207@plus.net> Message-ID: <42A9A24C.8020001@ece.utexas.edu> John Abel wrote: > Does anyone know of a quick way of performing this: > > $testVar =~ s#/mail/.*$##g Use the re (regular expression) module. Since you are iterating over a lot of entries, it is good to compile the regular expression outside of the loop. >>> import re >>> mailRE = re.compile('/mail/.*$') >>> >>> myList = ['/var/mail/joe', '/var/spool/mail/bob'] >>> remainderList = [] >>> >>> for testVar in myList: ... remainderList.append(mailRE.sub('', testVar)) ... >>> print '\n'.join(remainderList) /var /var/spool From noreply at gcgroup.net Wed Jun 15 19:49:47 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 15 Jun 2005 23:49:47 GMT Subject: access properties of parent widget in Tkinter Message-ID: I am trying to get & set the properties of a widget's parent widget. What I have works, but seems like a long way around the block. First I get the widget name using w.winfo_parent(), then i convert the name to a reference using nametowidget(). self.nametowidget(event.widget.winfo_parent()).hasChanged= True It works, but I can't help but think I'm missing a more direct route. Am I? Bill From cjbottaro at alumni.cs.utexas.edu Sat Jun 4 14:16:54 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Sat, 04 Jun 2005 13:16:54 -0500 Subject: how to get name of function from within function? References: Message-ID: Steven Bethard wrote: ...snip... > Something like this might work: > > py> class C(object): > ... def func_a(self): > ... print "func_a" > ... def func_b_impl(self): > ... print "func_b" > ... raise Exception > ... def __getattr__(self, name): > ... func = getattr(self, '%s_impl' % name) > ... wrapped_func = self._impl_wrapper(func) > ... setattr(self, name, wrapped_func) > ... return wrapped_func > ... def _impl_wrapper(self, func): > ... def wrapper(*args, **kwargs): > ... try: > ... return func(*args, **kwargs) > ... except: > ... print "entered except" > ... raise > ... return wrapper > ... > py> c = C() > py> c.func_a() > func_a > py> c.func_b() > func_b > entered except > Traceback (most recent call last): > File "", line 1, in ? > File "", line 15, in wrapper > File "", line 6, in func_b_impl > Exception > > The idea here is that __getattr__ is called whenever the class doesn't > have a particular function. The __getattr__ method then tries to find a > corresponding _impl function, wraps it with appropriate try/except code, > and returns the wrapped function. > > HTH, Yes, it does! Thats perfect, and it works with Python 2.3 (which I'm using). Thank you very much. > STeVe -- C From python-url at phaseit.net Tue Jun 7 10:08:02 2005 From: python-url at phaseit.net (Simon Brunning) Date: Tue, 07 Jun 2005 14:08:02 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) Message-ID: QOTW: "[expletives deleted]" - John Machin, snipping a section of Perl code. "What sort of programmer are you? If it works on your computer, it's done, ship it!" - Grant Edwards Guido invites us to comment on PEP 343. This Python Enhancement Proposal includes a 'with' statement, allowing you simply and reliably wrap a block of code with entry and exit code, in which resources can be acquired and released. It also proposes enhancements to simple generators, making them easy to use to build these wrappers: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a9d9b591ca7b296d Timothy Smith would like to truncate a Decimal. It's not as easy as it sounds, but Raymond Hettinger has the definitive solution, as is so often the case: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f40d2863110dc81e If you need to set Windows' environment variables persistently, Gigi's recipe is what you need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/416087 EasyInstall, Phillip J. Eby's CPAN clone is ready to go: http://dirtsimple.org/2005/06/cpan-goodies-for-all.html How does one check if a given datetime is within a specified range? Andrew Dalke shows Maksim Kasimov how: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e186c915a237c9a7 Robert Kern shows how to turn a CSV file into a list of dictionaries, and Peter Otten shows off a lovely iterator trick for turning adjacent list entries into dictionary elements: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ed07b9f71724dcbd Ryan Tomayko defends the LAMP (Linux, Apache, MySQL, Python/Perl/PHP) platform: http://naeblis.cx/rtomayko/2005/05/28/ibm-poop-heads Skip Montanaro tells us why Emacs is the perfect IDE for him: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6df813d2d8d187fb#8438e5f0d2352e5f O'Reilly has published a couple of interesting articles by Jeremy Jones, "Python Standard Logging" and "Writing Google Desktop Search Plugins": http://www.onlamp.com/pub/a/python/2005/06/02/logging.html http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html How can you reliably eradicate data from a hard disk? Nuke the site from orbit; it's the only way to be sure. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2e73c88596c35427 Tomasz Bieruta shows us how to sort large files: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/415581 Google's new Sitemaps allow a Webmaster to tell Google what to spider. They provide a Python script to get you started: https://www.google.com/webmasters/sitemaps/docs/en/sitemap-generator.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From renato.ramonda at gmail.com Thu Jun 9 18:53:37 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Fri, 10 Jun 2005 00:53:37 +0200 Subject: Fast text display? In-Reply-To: <7xzmtzm9vi.fsf@ruckus.brouhaha.com> References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> <863brr6xiw.fsf@guru.mired.org> <7xzmtzm9vi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin ha scritto: > The installer is going to download more stuff? Yuccch, I'd rather not > need a network connection to do an install. Anyway, wxpython built ok > on FC3. The problem was wxwidgets, which needed an obsolete version > of GTK. I spent at least an hour or two messing around with it before > deciding it wasn't worth the hassle. AFAIR the linux package for wxpython does not require wxWidgets at all (it's embedded). As for the obsolete gtk look for a "gtk+" package, not for the "gtk" which is the up-to-date gtk2 package. And good luck :-) -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From rrr at ronadam.com Tue Jun 14 01:07:19 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 14 Jun 2005 05:07:19 GMT Subject: "also" to balance "else" ? In-Reply-To: References: <11asi5cps42vfe5@news.supernews.com> Message-ID: Terry Hancock wrote: > On Monday 13 June 2005 11:09 pm, Ron Adam wrote: >>My suggestion is to use, also as the keyword to mean "on normal exit" >>'also' do this. > > > Unfortunately, "also" is also a bad keyword to use for this, IMHO. > I don't find it any more intuitive than "else". (And since your idea > would break if-else code, I don't think it would be allowed, anyway). Hi Terry, How would it break the current if-else? > I can't think of what would be a better keyword, though. :-/ Well there's 'not-else' or 'nelse' Ack! Just kidding of course. Yes, I can't think of anything that has the same meaning that would work. 'And' would be the English language alternative to "else", but it's already used of course. Regards, Ron From peter at engcorp.com Sun Jun 19 12:57:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 19 Jun 2005 12:57:13 -0400 Subject: extreme newbie In-Reply-To: References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: Dave Cook wrote: > On 2005-06-18, cpunerd4 wrote: >>thanks all for the advice. The reason I was thinking about using java >>(or C or something) was that it is a little more secure than >>distributing the source code isn't it? > > 14 and he already wants to horde his source code. Be gentle. Most of us have been there (those fortunate enough to have been in a position to write source code at 14), and it felt like a sensible viewpoint at the time. I suspect that the attitude will be less and less common in the future, as the open source movement continues to prove successful. -Peter From bogus@does.not.exist.com Mon Jun 20 10:35:02 2005 From: bogus@does.not.exist.com () Date: Mon, 20 Jun 2005 14:35:02 -0000 Subject: No subject Message-ID: #! rnews 4339 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Multiple instances of a python program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 83 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1118947630.385547.231370 at g43g2000cwa.googlegroups.com> <1119043472.013942.233980 at f14g2000cwb.googlegroups.com> Mime-Version: 1.0 Date: Mon, 20 Jun 2005 14:14:24 GMT Xref: news.xs4all.nl comp.lang.python:382535 "Rahul" writes: > Steven D'Aprano wrote: > > On Thu, 16 Jun 2005 11:47:10 -0700, Rahul wrote: > > > > > Hi. > > > I am part of a group in my univ where we organize a programming > > > contest. In this contest we have a UDP based server. The server > > > simulates a game and each contestant is to develop a team of virtual > > > players. Each team is composed of 75 similar bots...i.e. governed by > > > the same logic. Thus the contestant submits a single copy of the client > > > and we instantiate the same program 75 times at the same time. > > > The problem is that while executables from C source files are small and > > > we can make 75 processes but we dont know what to do with python. > > > > > > If you have a python script and you want that 75 copies of the script > > > be run simultaneously how will you do it? Is there anyway to do so > > > without running 75 copies of the python interpreter simultaneously? > > > > Have you actually tested the performance of 75 instances of Python > > running? Do you know that it will be too slow for your server, or are you > > trying to optimize before testing? > > > > I wrote a short Python script, then launched 115 instances of Python > > executing the script. There was no detectable slowdown of my system, which > > is far from a high-end PC. > > > > The details of the script aren't important. It may even be that what I > > tested is not even close to the load your server needs to deal with. But > > you may be surprised at just how easily even a low-end PC copes 75 > > instances of Python. Or perhaps not -- but the only way to tell is to try. > > Well...i havent tried (yes i hear "Premature optimization is evil evil > evil i say") but the point was that if we can find a solution consuming > less memory than we can even increase the number from 75 to lets say > 200. as for hardware we have machines with 1.7 Ghz P4 and 128 mb ram. > and i cant run them right now...since i am currently not in my > univ...but asked now since we are planning right now and wanted to see > which languages we can support. Probably c,c++,python and lisp using > clisp...and java if we can find a way to avoid running 75 jvms...this > year we supported c,c++,java and actually ran 75 jvms using 3 machines > and it was horrible so we are looking for better ways for the 2006 > contest. And we may port our server from java to python too but it > seems not many people had python installed but most had java installed. > > rahul > As others have said, start by testing. Given 1.7 MHz and 128MB, I'm guessing your performance problems are coming from swapping. Simply getting more RAM in the box would help. A quick check on process load just for the instances themselves can be done by gradually increasing max_processes (see below) until you swap. On a box with 256MB total, 150MB free, I was getting over 150 children before swap was noticeable. By watching "top" I found each child was using about 3MB, of which about 2MB is "shared" (basically, the python library). In other words, each instance was costing 1MB. Of course, your actual apps will require more RAM than this little test program. ---main program--- max_processes=10 progname="child.py" for i in xrange(max_processes): os.spawnv(os.P_NOWAIT,progname,[progname,str(i)]) ---child program--- def msg(txt): sys.stdout.write(txt) sys.stdout.flush() .... #get childnum from comline parameters .... for i in xrange(10): msg('%i ' % childnum) time.sleep(1) -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From __peter__ at web.de Sat Jun 25 15:30:26 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 25 Jun 2005 21:30:26 +0200 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Mandus wrote: > By using the builtin reduce, I > move the for-loop into the c-code which performs better. No. There is no hope of ever writing fast code when you do not actually measure its performance. Peter From mweihs at gmx.at Fri Jun 10 17:01:13 2005 From: mweihs at gmx.at (Markus Weihs) Date: Fri, 10 Jun 2005 23:01:13 +0200 Subject: bind in Tkinter References: Message-ID: Hi! If you press a key, a key-event is passed to the function, here to self.quit. This is the misterious second argument, which can be useful if you e.g. want to check which key was pressed. Here is a snippet to show how you can do it: from Tkinter import * def quit_program(event): print event.keysym # which key was pressed? root.quit() root = Tk() e = Entry() e.bind("", quit_program) e.pack() root.mainloop() Regards, mawe From chinook.nr at tds.net Tue Jun 28 02:44:56 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 02:44:56 -0400 Subject: OO refactoring trial ?? References: Message-ID: <0001HW.BEE66A28001E112CF0386550@news.gmane.org> On Tue, 28 Jun 2005 02:22:13 -0400, Peter Otten wrote (in article ): > Chinook wrote: > >> 3) Any other comments you might offer > >> if?tv?==?'relates?to?A': >> return?True >> else: >> return?False > > Make that > > return tv == 'relates to A' > > lest your zen master hit you. > > Peter > > > Thank you Peter, So wrapped up in the OO I overlooked the simpler aspects. Lee C From daniel.dittmar at sap.corp Thu Jun 23 07:25:06 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 23 Jun 2005 13:25:06 +0200 Subject: PEP ? os.listdir enhancement In-Reply-To: References: Message-ID: Riccardo Galli wrote: > On Thu, 23 Jun 2005 12:56:08 +0300, Konstantin Veretennicov wrote: >>What about os.listdir(dir='relative/path', abs=True)? Should listdir call >>abspath on results? Should we add another keyword rel? Would it complicate >>listdir unnecessarily? > > keyword dir not exists (don't know if you added as example or not) and > abs set to true would return abspath on result. What else could it do ? He probably meant that a 'join' option would be more natural than an 'abs' option. After all, your examples use os.path.join to create a valid path that can be used as the argument to other module os functions. Whether the results are absolute or relative should depend on the initial argument to os.listdir. Daniel From km at mrna.tn.nic.in Sun Jun 12 13:46:35 2005 From: km at mrna.tn.nic.in (km) Date: Sun, 12 Jun 2005 23:16:35 +0530 Subject: without shell Message-ID: <20050612174635.GA20992@mrna.tn.nic.in> hi all, can any linux command be invoked/ executed without using shell (bash) ? what abt security concerns ? regards, KM From phm4 at kent.ac.uk Thu Jun 30 10:26:58 2005 From: phm4 at kent.ac.uk (Philipp H. Mohr) Date: Thu, 30 Jun 2005 15:26:58 +0100 (BST) Subject: Store multiple dictionaries in a file In-Reply-To: References: Message-ID: Hello, this is the solution I went for, as I am indeed not concernt about security and the implementation is straight forward. Thank you, Phil > If you're not worried about security, you could write the repr() of each > dict to the file and get the values back by using the eval() function. > repr() writes onto one line. > > If you're storing types without repr() representations this will not work. > > Jeremy From steven.bethard at gmail.com Mon Jun 20 02:39:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Jun 2005 00:39:42 -0600 Subject: calling subclass constructor question In-Reply-To: References: Message-ID: In Han Kang wrote: > So each of the sub classes plots a different type of graph. The > superclass defines methods that are the same for all the plots. I want > to be able to pick some points and be able to generate a more plots. > What I was wondering if I could define in a method in the superclass of > an object the ability to make a brand new subclass (new plot). So > basically, one plot makes another plot, but it'd be nice if i could put > all the code in the superclass. Still not sure I understand you. How are you determining which new type of plot to create? If I'm an instance of class PlotA, and the user asks me to create create a new Plot, is it always another instance of class PlotA, or could it be an instance of another class? If the former, you can use a classmethod, e.g.: class Plot(object): @classmethod def new(cls, ...): result = cls(...) # maybe modify result some more return result If the latter, this doesn't sound like something that should be a method of an instance. It sounds more like a factory function. Why not just make it a module-global function, e.g.: def newPlot(...): # determine which kind of Plot object to create ... if ...: return PlotA(...) ... A method signature of the method you want to write would help a lot... STeVe From nicolas.riesch at genevoise.ch Fri Jun 17 06:22:46 2005 From: nicolas.riesch at genevoise.ch (nicolas.riesch at genevoise.ch) Date: 17 Jun 2005 03:22:46 -0700 Subject: strxfrm works with unicode string ? In-Reply-To: References: <1118997804.678723.170070@g44g2000cwa.googlegroups.com> Message-ID: <1119003766.658567.228590@g14g2000cwa.googlegroups.com> Gru?zi, Gerald ;-) Well, ok, but I don't understand why I should first convert a pure unicode string into a byte string. The encoding ( here, latin-1) seems an arbitrary choice. Your solution works, but is it a workaround or the real way to use strxfrm ? It seems a little artificial to me, but perhaps I haven't understood something ... Does this mean that you cannot pass a unicode string to strxfrm ? Bonne journ?e ! From michele.simionato at gmail.com Thu Jun 9 06:56:36 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Jun 2005 03:56:36 -0700 Subject: multiple inheritance In-Reply-To: <1118312893.482453.112320@g44g2000cwa.googlegroups.com> References: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> <1118305667.847406.58280@g44g2000cwa.googlegroups.com> <1118312893.482453.112320@g44g2000cwa.googlegroups.com> Message-ID: <1118314596.829691.170280@g49g2000cwa.googlegroups.com> If you are curious, the MRO algorithm is explained here: http://www.python.org/2.3/mro.html Michele Simionato From vamsikrishna_b at coolgoose.com Tue Jun 21 01:24:09 2005 From: vamsikrishna_b at coolgoose.com (vamsikrishna_b at coolgoose.com) Date: 20 Jun 2005 22:24:09 -0700 Subject: after transfer of data from MS-outlook(mail ids) to application, mail ids are consisting of strange characters Message-ID: <1119331449.803907.285750@z14g2000cwz.googlegroups.com> Hello all,the following problem i encountered while transferring data(mail ids) from MS-outlook to one application.Some mail ids after came into the application looked as strange characters.Eg are [?@ [?. [?,??@ ??. ?? etc.I thought these are the Ascii characters but i'm not quite sure about this.And also each mail id following a certain format as you can observe from the above mail ids.Only one string is repeating in all the 3 parts of the mail id.Is there any procedure to convert these characters to the plain letters.I hope somebody will help me in this regard to unfold this mystery.Bye. Best Regards, Vamsi From cf_1957 at hotmail.com Wed Jun 1 05:45:11 2005 From: cf_1957 at hotmail.com (chris) Date: Wed, 01 Jun 2005 09:45:11 GMT Subject: decimal numarray References: Message-ID: "km" wrote in message news:mailman.257.1117478862.18027.python-list at python.org... > Hi all, > is there any support for decimal type in numarray module ? > regards, > KM Still a noob but perhaps you can use gmpy, a wrapper for GMP arbitrary precision library. I found it here http://gmpy.sourceforge.net/ I just tried this and seemed to produce an array of gmpy.mpf types. Gmpy also has support for arbirtrary length integers (mpz) and rationals (mpq). Works for me. Hope this helps. In [14]: sl=[gmpy.mpf(2)]*10 In [15]: sl Out[15]: [mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0'), mpf('2.e0')] In [16]: x=array(sl) In [17]: x Out[17]: NumPy array, format: long [2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,2.0 ,] In [18]: x[0] Out[18]: mpf('2.e0') From dimitri.pater at gmail.com Thu Jun 30 02:58:41 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Thu, 30 Jun 2005 08:58:41 +0200 Subject: some trouble with MySQLdb In-Reply-To: <42C3989A.8010008@xit.net> References: <42C3989A.8010008@xit.net> Message-ID: try: db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="myDB") localhost can be a URL also (if MySQL is set up properly in the first place) regards, Dimtiri On 6/30/05, nephish wrote: > > Hey there all, > i have a question about how to point my python install to my sql database. > > when i enter this: db = MySQLdb.connect(user="user", passwd="pass", > db="myDB") > > i get this: > Traceback (most recent call last): > File "", line 1, in -toplevel- > db = MySQLdb.connect(user="user", passwd="pass", db="MyDB") > File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66, > in Connect > return Connection(*args, **kwargs) > File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line > 134, in __init__ > super(Connection, self).__init__(*args, **kwargs2) > OperationalError: (1049, "Unknown database 'MyDB'") > > i am using the all in one package from lampp (now xampp) and i have > tested a couple of python scripts from the cgi, but.... nothing that > connects to the database. > > any ideas? > > thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From hsuanyeh at yahoo.com Sat Jun 18 22:21:42 2005 From: hsuanyeh at yahoo.com (Hsuan-Yeh Chang) Date: Sun, 19 Jun 2005 02:21:42 GMT Subject: SciPy gui_thread Problem Message-ID: Dear SciPy users, Can anyone tell me the reason for following error messages: >>> import gui_thread >>> gui_thread.start() Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/scipy_base/pexec.py", line 56, in run exec (code, frame.f_globals,frame.f_locals) File "", line 1, in ? ImportError: /usr/lib/wxPython/lib/libwx_gtk2u_ogl-2.5.so.3: undefined symbol: _ZNK6wxExpr3NthEi Thanks!! HYC From egbert.bouwman at hccnet.nl Mon Jun 13 10:54:17 2005 From: egbert.bouwman at hccnet.nl (egbert) Date: Mon, 13 Jun 2005 16:54:17 +0200 Subject: Controlling assignation In-Reply-To: References: Message-ID: <20050613145417.GA8749@hccnet.nl> On Mon, Jun 13, 2005 at 03:52:14PM +0200, Xavier D?coret wrote: > In other word, I would like to be able to use a=5 instead of a.set(5) If a(5) is acceptable to you in stead of a=5 you can make your instance callable with the __call__ method: class A(object): def __init__(self): self.var=0 def __call__(self,val=None): self.var=val a = A() a(5) print a.var # gives 5 egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From peter at engcorp.com Sat Jun 18 12:20:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:20:47 -0400 Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') In-Reply-To: References: Message-ID: Maxwell Hammer wrote: > On Thu, 16 Jun 2005 16:20:23 -0400, Peter Hansen wrote: >>If the question was well formulated, and it's been more than a couple of >>days, you should consider reposting. It's very unusual for a post with >>such a subject (if it was a clear question) to get _no_ feedback around >>here. > > Fair enough. The question is not expressed clearly for others. Do you have > any suggestions as to how to describe the problem clearer? I hope you didn't get the impression I was criticizing. I don't recall your post at all, and definitely wasn't suggesting that it was unclear, merely asking you to verify that it was and, if not, rewrite it upon reposting. As for suggestions to make it clearer: I can't make any without digging back for your previous posting. I generally don't take the time to do that since older messages are often gone from my server very quickly, and I don't like spending time digging around on Google Groups to find it. Sorry, it's just one of my approaches to conserving my own time, selfishly. > I can think of no other way but to say I have an app that when I terminate > it, completes ok, However the last thing that happens before the shell > prompt returns is that there is a traceback *within* python. > (The actual post goes into more details of course.) This sounds very much like the problem where, during the interpreter shutdown, all globals in all modules are rebound to None, but if daemon threads are still running they will quickly crash as a result and raise exceptions, usually referring to AttributeErrors where "None" doesn't have an attribute of a particular kind, usually the name of a method. If I'd seen your post, I would probably have responded with as much at the time. If you do a Google Groups search for some of those keywords and my name, you'll certainly find a half dozen other threads where someone else asked a similar question, even if I missed your post. > I just took a guess that it is *thread* related from the output of the > traceback. I'm still learning python, so how could one pose the problem > *clearer*? > > And thanks for the feedback regarding threads, by the way. No problem. And if this post didn't help, please do repost the whole original question so I can see it again, and those who read the group via the mailing list will get a fresh email, etc... -Peter From guy.lateurNNOOSSPPAAMM at pandora.be Thu Jun 9 14:01:46 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Thu, 09 Jun 2005 18:01:46 GMT Subject: Start application & continue after app exits References: Message-ID: >>Also note that this method of creating tempfiles is technically unsafe, >>as it is theoretically possible that another process would create a file >>of the same name in the same directory and then try to use it, resulting >>in a race condition between the two processes. This is practically >>unlikely, however, and I'm a pragmatist. I see what you mean, but wouldn't a call to open(fn, 'w') on a filename that's in use (for reading or writing) result in an error condition or something? I'm a noob, btw. Thanks for the info, guys, much appreciated. I'll try it soon (on XP) - I'm a pragmatist, too, you see.. From roy at panix.com Thu Jun 23 08:42:47 2005 From: roy at panix.com (Roy Smith) Date: Thu, 23 Jun 2005 08:42:47 -0400 Subject: case/switch statement? References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> <1119524525.995376.128940@f14g2000cwb.googlegroups.com> Message-ID: "NickC" wrote: > The thing I love most about Python is the fact that callables can be > slung around at run-time, just like any other object. Yup. A while ago, I was doing a lot of file parsing with state machines. Each state was a function. The main loop of the state machine was just: state = start while state != end: state, output = state (input) Each function was responsible for returning a (nextState, output) tuple. From rkern at ucsd.edu Mon Jun 27 15:56:00 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 27 Jun 2005 12:56:00 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Hello, > > at the moment python-dev is discussing including Jason Orendorff's path module > into the standard library. > > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? I would like to see the setuptools/PythonEggs/EasyInstall trifecta get more attention and eyeballs. Once it is mature, I think that it will obviate the desire for stdlibification of most of the packages being requested here. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From d at e.f Fri Jun 24 11:02:34 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 10:02:34 -0500 Subject: Favorite non-python language trick? In-Reply-To: <1119624712.444787.310300@o13g2000cwo.googlegroups.com> References: <1119618780.475725.22580@o13g2000cwo.googlegroups.com> <1119624712.444787.310300@o13g2000cwo.googlegroups.com> Message-ID: infidel wrote: >>def class Colour: >> def __init__(self, blue=0, green=0, red=0): >> # pseudo-Python code borrowing concept "with" from Pascal >> with self: >> blue = blue >> green = green >> red = red >> >>And now you can see why Python doesn't support this idiom. > > > Maybe it would make more sense if it was done a la Visual Basic > > with self: > .blue = blue > .green = green > .red = red > > requiring a dot to be typed removes the ambiguity and gives the IDEs a > chance to Intellisense-ify your coding. Some made a python recipe emulating this I believe. The python cookbook search engine is down though so I cannot find the link. At one point Guido van Rossum was advocating this use of "with" as well, I believe: http://mail.python.org/pipermail/python-dev/2004-March/043545.html But I don't think it is being considered now. I think now "with" is being proposed for something more like VB and C#'s "using" statement. It automatically disposes of a resource when done with it: http://wiki.python.org/moin/WithStatement From duncan.booth at invalid.invalid Mon Jun 20 06:53:30 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2005 10:53:30 GMT Subject: catch argc-argv References: <42B68463.90501@lexicon.net> Message-ID: John Machin wrote: >> So, my question is: does the Python API containe fonctions like >> 'get_argc()' and 'get_argv()' ? >> > > If you can't see them in the documentation, they aren't there. If they > aren't there, that's probably for a good reason -- no demand, no use > case. > > Leaving aside whether or not there is a use-case for this, the reason they aren't there is that they aren't needed. As the OP was already told, to access argv, you simply import the 'sys' module and access sys.argv. There are apis both to import modules and to get an attribute of an existing Python object. So all you need is something like (untested): PyObject *sys = PyImport_ImportModule("sys"); PyObject *argv = PyObject_GetAttrString(sys, "argv"); int argc = PyObject_Length(argv); if (argc != -1) { ... use argc, argv ... } Py_DECREF(argv); Py_DECREF(sys); From cam.ac.uk at mh391.invalid Tue Jun 21 11:33:08 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 21 Jun 2005 16:33:08 +0100 Subject: Using print with format to stdout generates unwanted space In-Reply-To: References: <3hmt4rFhnn89U1@individual.net> <42b6bc99@news.highway1.com.au> <3ho63fFi1o93U1@individual.net> Message-ID: [Tim Williams] >>For quick and simple removal of the extra space, append a '\b' >>backspace character to your output "string" [Jorgen Grahn] > For things that are only ever to be viewed on the terminal, yes. > But this does, of course, print an actual backspace character. > If you feed this output to another program, chances are it will > not treat as no space at all. > > I prefer building up a list and doing ' '.join(thelist) in these situations. A much better approach. Or you can use sys.stdout.write() as others have said. -- Michael Hoffman From claird at lairds.us Mon Jun 13 21:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Jun 2005 01:08:03 GMT Subject: implicit variable declaration and access References: Message-ID: In article , Ali Razavi wrote: >Tom Anderson wrote: >> On Mon, 13 Jun 2005, Ali Razavi wrote: >> >>> Is there any reflective facility in python that I can use to define a >>> variable with a name stored in another variable ? . . . >> Are you absolutely sure you want to do this? >> >> tom >> >Have you ever heard of meta programming ? >I guess if you had, it wouldn't seem this odd to you. Mr. Razavi, Python has explicit idioms for metaprogramming that most experienced Pythoneers favor over name-reflection. is only one of several useful write-ups on the subject. From tdwdotnet at gmail.com Mon Jun 27 18:27:12 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Mon, 27 Jun 2005 23:27:12 +0100 Subject: Python & firewall control (Win32) In-Reply-To: <012401c57345$2f46e480$ccbefea9@twilliams> References: <011101c57338$fcb5e8b0$ccbefea9@twilliams> <012401c57345$2f46e480$ccbefea9@twilliams> Message-ID: <9afea2ac050627152753296263@mail.gmail.com> On 6/17/05, Tim Williams wrote: > > > ----- Original Message ----- > > From: "Tom Anderson" > > > re: http://wipfw.sourceforge.net/?page=home > > Tom, this looks good. I had it downloaded, installed and running some > custom rules in under 5 minutes. Very simple and straightforward. > > > AIUI, you won't be stopping and restarting ipfw > > This is correct, the service doesn't appear to restart, the rule updates > are actioned very quickly (instantaneous) > > I haven't had chance to try it integrated into a Python app, but it looks > very promising,. > Tom, I found that controlling the firewall via popen3 is perfect, I now have server applications that can firewall themselves when they detect possible attacks or abuse from individual IPs, ranges etc eg: import win32pipe as W #add a rule at position 100 i,o,e = W.popen3('C:\\ipfw\\bin\\ipfw add 100 allow IP from me to 192.0.0.1') -or- # list all rules i,o,e = W.popen3('C:\\ipfw\\bin\\ipfw list') -or- #delete rule 100 i,o,e = W.popen3('C:\\ipfw\\bin\\ipfw delete 100') Thanks again From fuzzyman at gmail.com Wed Jun 15 11:08:01 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 15 Jun 2005 08:08:01 -0700 Subject: ANN: rest2web, firedrop2, textmacros Message-ID: <1118848081.775647.91850@g47g2000cwa.googlegroups.com> Threee related announcements : rest2web - latest update adds support for multiple translations firedrop2 - new documentation and updated reST support textmacros - the textmacros module is now available separrately, useful for systems like docutils First of all my all new `Firedrop2 Section`__ [#]_ is up and running. __ http://www.voidspace.org.uk/python/firedrop2/index.shtml .. [#] **Firedrop2** being the blogging tool for discerning pythoneers, written by `Hans Nowak`__. __ http://zephyrfalcon.org It includes my own distribution called *The Fuzzy Version*. This is a temporary fork whilst Hans approves the changes I've made. The main change is improved reST__ support. This requires docutils 0.3.9. __ http://docutils.sourceforge.net The new section has docs on templating, macros, options, plugins, and more. Secondly, I've broken out the *textmacros* module from the Firedrop project. This system is also used by rest2web__ and provides an easy way of extending docutils (or any other text based system). __ http://www.voidspace.org.uk/python/rest2web It maps markup like ``{name;param;param}`` to function calls and replaces the text with the output. It can also apply transformations to whole passages of text using a ``{+name} some text here {-name}`` syntax. See the `textmacros page`__ for download and use details. __ http://www.voidspace.org.uk/python/firedrop2/textmacros.shtml It's very simple though - an ``apply_macros.py`` script will process directories of files. I recommend using it on the *output* of docutils files [#]_. You can use it for adding {acro;acronyms;Like This}, smilies {sm;:evil:}, or even doing Python source coloring. .. [#] I've only ever used it with HTML - it may be just as useful with Laytex. It comes with an example macro file, and it's very simple to add new ones. For full docs see : `The Macro System`__ [#]_ __ http://www.voidspace.org.uk/python/firedrop2/macros.shtml .. [#] Part of the Firedrop docs. There is a new version of **rest2web** [#]_ available at Voidspace__, in SVN__, and at Sourceforge__. .. [#] We're now up to **0.2.2** __ http://www.voidspace.org.uk/python/rest2web __ https://svn.rest2web.python-hosting.com __ http://sourceforge.net/projects/rest2web This version adds something called *uservalues* to rest2web. It allows you to create values that can be used by the templating system, and to specify another file to be used as the body of the page. If that body uses your uservalues, it is easy to have several files using the same body - but inserting different text into it. One obvious use for this is having multiple translations of the same site. See `uservalues`__ for the lowdown and `translation pages`__ for a trivial example. The source of the example is included in the distribution - so you can see how it's done. __ http://www.voidspace.org.uk/python/rest2web/uservalues.html __ http://www.voidspace.org.uk/python/rest2web/translation/index.html For those who don't know, **rest2web** is a website templating system optimised for storing content in `reST format`__. It can autogenerate navigation links and sidebars for you, as well as sporting a flexible templating and macro system. See the `online docs`__ for more details than you could possibly want. __ http://docutils.sourceforge.net __ http://www.voidspace.org.uk/python/rest2web Best Regards, Fuzzyman http://www.voidspace.org.uk/python From pwatson at redlinepy.com Mon Jun 20 12:48:52 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Mon, 20 Jun 2005 11:48:52 -0500 Subject: Couple functions I need, assuming they exist? References: Message-ID: <3hoabmFi28sgU1@individual.net> "Charles Krug" wrote in message news:TVAte.340826$cg1.208130 at bgtnsc04-news.ops.worldnet.att.net... > > The target of the problems (my daughter) would prefer that the thousands > be delimited. Is there a string function that does this? Be sure to use the locale approach and avoid rolling your own. From skip at pobox.com Thu Jun 23 19:00:20 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 23 Jun 2005 18:00:20 -0500 Subject: Running Python interpreter in Emacs In-Reply-To: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> Message-ID: <17083.16132.468981.904676@montanaro.dyndns.org> Rex> I'm interested in running a Python interpreter in Emacs. I have Rex> Python extensions for Emacs, and my python menu lists "C-c !" as Rex> the command to run the interpreter. Yet when I run it I get the Rex> message "Spawning Child Process: invalid argument." What do I need Rex> to do/download to fix this? Good question. Works fine for me on MacOSX 10.3 w/ XEmacs 21.4.15, python-mode 4.75 and Python built from CVS. Can you give some details of your environment? Rex> I read in a post in this group from a while back where someone had Rex> the following lines in his .emacs file: Rex> (setq interpreter-mode-alist Rex> (cons '("python" . python-mode) Rex> interpreter-mode-alist)) Rex> Does that have something to do with it? I doubt it. What's the value of interpreter-mode-alist? I have '("python" . python-mode) in my list by default (as a side-effect of running python-mode). Rex> Do I have to set my load-path to my python interpreter? No. That's how Emacs finds Emacs Lisp files to load. Make sure the "python" command resides in a directory on your PATH. Skip From peter at engcorp.com Wed Jun 29 00:03:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 29 Jun 2005 00:03:40 -0400 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: Elmo M?ntynen wrote: > > Peter Hansen wrote: >>???? ???????? wrote: >>>Anybody thought about this issue? >> >>Perhaps not, but now that you've pointed it out they've taken the time >>machine back and fixed the problem before it arose: > > Maybe funny, but a bit too cocky for my taste. Robert kern is propably > right about what he really meant so don't be too hasty in the future, > right?). Elmo, it's probably neither cocky nor funny, but before you pass judgment you should Google this group for "time machine" and read awhile. (I was merely attempting to parrot a traditional response that is given around here when someone asks for something which is already present in the language.) And whether I misinterpreted the (ambiguous) question or not, my response provides the required information to put together a solution to the OP's question. It would just require one extra level of indirection, so to speak, to do what Robert suggests he might have wanted. (Uncocky enough for you this time?) -Peter From d at e.f Mon Jun 13 23:02:39 2005 From: d at e.f (D H) Date: Mon, 13 Jun 2005 22:02:39 -0500 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Andrea Griffini wrote: > On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen > wrote: > > >>I think new CS students have more than enough to learn with their >>*first* language without having to discover the trials and tribulations >>of memory management (or those other things that Python hides so well). > > > I'm not sure that postponing learning what memory > is, what a pointer is and others "bare metal" > problems is a good idea. Those concept are not > "more complex" at all, they're just more *concrete* > than the abstract concept of "variable". > Human mind work best moving from the concrete to > the abstract, You're exactly right that people learn better going from concrete to abstract, but you're examples (pointers and memory management) are not what is typically meant by concrete in learning contexts. Starting concretely would mean using programming to solve real problems and develop useful tools. In programming it is often good to start with examples - some common ones I've seen in informal learning of programming include a calculator, an RSS viewer or aggregator, a video game, etc. But what you are getting at is more akin to our mental model of what the computer is doing when we write and run a program. Without a fundamental understanding of memory and addresses, a programmer can make certain mistakes that reveal this lack of understanding. But that doesn't mean they have to learn about memory management at the very beginning of their instruction. From sjmachin at lexicon.net Thu Jun 2 20:26:52 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 10:26:52 +1000 Subject: (OT) lincense protection generator In-Reply-To: References: Message-ID: <429fa3cc@news.eftel.com> flupke wrote: > I'm going to be distributing a program based on wxPython & python in a > few weeks time. The code will run on windows machines. > > Because i don't want the users to move the folders around or mess with > the program or taking copies home to fiddle with it, i was thinking of a > way to check when the program starts that it's still on the same > directory and same computer. > > That way i at least avoid unnecessary phone calls asking me for help > when they messed the program up. > > I'm thinking of a function that will generate such a code and put it in > a file. Then when the program starts it checks this file and checks the > code in there with a code that it generates at that time again based for > instance on the current directory and other components unique to that > computer. It could be a long string (but what info?) and then take a > hash from it and store the hash value. > > How could i construct such a code without being a total pain? For > instance i don't want to check for anything hardware related because > then my program would fail to work once the people change their hardware. > Anyway, it doesn't need to be waterproof. (not possible anyway) > Your requirements are confusing -- you want the program to check "that it's still on the same ... computer" but you don't want it to fail if they change their hardware??? In short: don't bother. You will end up annoying people who have not "messed with" your software. Heuristics like "it's not on the same computer therefore it's been fiddled with" don't seem like a good idea. An app should not care where it is installed, so long as it can find its associated files and folders. If the app can't find them: Try putting out informative messages when something does go wrong, and write a copy to a dump-file (like the Dr Watson log file, but skip all the hexdump stuff). Put a timestamp and the computer name and the user's name and whatever else you can dig out of Windows in the dump-file. Then you can ask the user with a problem to e-mail you a copy of the dump-file. If (say) the computer name is "frodo" instead of "pathology03" then you can tell the user their usage is not supported. This is a good idea even with "normal" i.e. non-fiddling users, who can't remember what the error message said -- they've since killed the window or even re-booted their PC. Iy you tend towards paranoia, put a checksum somewhere in each message in case the devious fiends use Notepad to change "frodo" to "pathology03" :-) From kyoguan at gmail.com Mon Jun 13 05:18:47 2005 From: kyoguan at gmail.com (kyo guan) Date: Mon, 13 Jun 2005 17:18:47 +0800 Subject: why python on debian without the module profile? Message-ID: <42ad4f7f.654d1ce2.0691.ffffe36b@mx.gmail.com> Hi All: Python 2.4.1 (#2, May 5 2005, 11:32:06) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import hotshot,hotshot.stats Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/hotshot/stats.py", line 3, in ? import profile ImportError: No module named profile >>> Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import hotshot,hotshot.stats Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/hotshot/stats.py", line 3, in ? import profile ImportError: No module named profile >>> From roccomoretti at hotpop.com Wed Jun 29 13:55:31 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 29 Jun 2005 12:55:31 -0500 Subject: Modules for inclusion in standard library? In-Reply-To: <7xwtodvzsv.fsf@ruckus.brouhaha.com> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Gregory Pi?ero writes: > >>I'd like to see some database API's to the most common databases >>included. > > Yes, certainly, this is a serious deficiency with Python. Except that (please correct me if I'm wrong) there is somewhat of a policy for not including interface code for third party programs which are not part of the operating system. (I.e. the modules in the standard libary should all be usable for anyone with a default OS + Python install.) A notable exception is the dbm modules, but I seem to recall hearing that the official position is that it was a mistake. (Now only kept for backward compatability.) From erchamion.beren at gmail.com Fri Jun 10 11:40:47 2005 From: erchamion.beren at gmail.com (sinan ,) Date: Fri, 10 Jun 2005 18:40:47 +0300 Subject: about accessing mysql In-Reply-To: <1vnon2-fm6.ln1@news.interplanet.it> References: <1vnon2-fm6.ln1@news.interplanet.it> Message-ID: <59dfa14505061008401488708b@mail.gmail.com> i checked innodb support via show variable. they have both same support. mysql version is 4.0.24_Debian-5-log MySQLdb module version is 1.2.1g2 they are same packets in debian. thanks From chad.hughes at pnl.gov Fri Jun 17 12:36:55 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Fri, 17 Jun 2005 09:36:55 -0700 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6194@pnlmse27.pnl.gov> I am very familiar with Python, but I don't know Pearl. In order to answer your question, you will have to tell me about your statement, "I couldn't live without closures and without the fine control over scopes that Pearl provides." I don't know what these things are to Pearl. If you tell me what these features are in Pearl and what you use them for, I can tell you if Python has them as well. Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of kj Sent: Friday, June 17, 2005 9:20 AM To: python-list at python.org Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? I'm a Perlhead (there, I said it). Years ago I made a genuine attempt to learn Python, but my intense disappointed with the way Python deals with scopes ultimately sapped my enthusiasm. I couldn't live without closures and without the fine control over scopes that Perl provides. I've been wanting to make another attempt to (re)learn Python for a while, but this scopes business remained a major damper. What's pushing me over my reluctance is having to work with a large in-house package developed in Python. I am hoping that it may be better this time around. For one thing, like Perl, Python was then (and maybe still is) a "work in progress." So I figure that Python scoping may have improved since then. Even if not, I think that Python is mature enough by now that adequate alternatives must have been devised for the Perlish features that I missed during my first attempt. My question is: is there any tutorial on Python scoping aimed at diehard Perlheads? Thanks! kj -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. -- http://mail.python.org/mailman/listinfo/python-list From greg at cosc.canterbury.ac.nz Fri Jun 10 04:26:44 2005 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 10 Jun 2005 20:26:44 +1200 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> <3gpsl0Fdhq0mU1@individual.net> Message-ID: <42A94EC4.8020106@cosc.canterbury.ac.nz> David M. Cooke wrote: >>To solve that, I would suggest a fourth category of "arbitrary >>ordering", but that's probably Py3k material. > > We've got that: use hash(). > [1+2j, 3+4j].sort(key=hash) What about objects that are not hashable? The purpose of arbitrary ordering would be to provide an ordering for all objects, whatever they might be. Greg From gsakkis at rutgers.edu Thu Jun 30 17:38:48 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 14:38:48 -0700 Subject: Newbie backreference question References: Message-ID: <1120167528.223100.76850@z14g2000cwz.googlegroups.com> > Hi, > In perl I can do something like: > > $a = 'test string'; > $a =~ /test (\w+)/; > $b = $1; > print $b . "\n"; > > and my output would be "string". > > How might this snippet be written in python? > > Thanks to all... import re a = 'test string' b = re.match(r'test (\w+)', a).group(1) print b George From roccomoretti at hotpop.com Wed Jun 29 09:57:48 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 29 Jun 2005 08:57:48 -0500 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1120023753.231890.182890@g43g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1120023753.231890.182890@g43g2000cwa.googlegroups.com> Message-ID: BORT wrote: > Gentle folk of comp.lang.python, I heartily thank you all for your > input. I think I'm taking the boys through the door marked "Logo." We > may be back this way, though. We will likely need MORE in the nebulous > future. I am impressed with the outpouring of support here! Others in the thread mentioned it briefly, but when you do come back to the door marked "Python", someone has eased the transition slightly: http://pylogo.org/ '''PyLogo is a Logo interpreter written in Python. Its implementation is small, and is based on the language as implemented by UCBLogo. The Logo language is a learning language, intended for children for which more "complete" languages aren't appropriate. Many of Logos language design choices are driven by this, and differ from Python.''' Although given it's 0.1 version status, it may be a little rough around the edges. From claird at lairds.us Thu Jun 16 11:08:22 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 16 Jun 2005 15:08:22 GMT Subject: implicit variable declaration and access References: <877jgy88do.fsf@hector.domek> <6kj1o2-13e.ln1@lairds.us> <1Qsre.83795$lQ3.77274@bignews5.bellsouth.net> Message-ID: In article <1Qsre.83795$lQ3.77274 at bignews5.bellsouth.net>, Christopher Subich wrote: . . . >Out of curiosity, where would you classify interpreters for secondary >app-specific programming languages? Specifically, mud-client stored >procedures (triggers, timed events) seem to correspond very naturally to >generating the python code required to execute them in advance, then >compile()ing and storing the compiled code for repeated execution. 1. If you know enough to ask the question, you're a consenting adult, and equipped to deal with the consequences. 2. Hey, that's the whole *idea* of an extension language. Go forth and Python happily, even exec() with righteousness. 3. But Python *is* an unsafe language in such uses--one of which I'm exceptionally fond, but undeniably unsafe. From http Mon Jun 6 00:14:37 2005 From: http (Paul Rubin) Date: 05 Jun 2005 21:14:37 -0700 Subject: Destructive Windows Script References: Message-ID: <7xd5r0uno2.fsf@ruckus.brouhaha.com> rbt writes: > Thanks for the opinion... I don't do malware. Just interested in > speeding up file wiping (if possible) for old computers that will be > auctioned. The boot programs that you allude to (killdisk, autoclave) > work well, but are slow and tedious. Yes, you have to overwrite all the bytes on the disk, which can be slow. If the drive has ultra-sensitive data on it though, you should not auction it no matter what wiping software you've used. Think of bad sector forwarding that might have happened while the drive was in service. The drive firmware might have copied some sector that had recoverable errors to a new sector sometime in the past, and transparently mapped the new sector to the old location, so that normal I/O operations will never find the old sector to erase it. But suitable forensic methods might still be able to get it back. The only way to be 100% sure the data is gone from a drive, is basically to melt the drive. However, if your data is that sensitive, you shouldn't ever write it to a hard drive in the clear anyway. From superprad at gmail.com Mon Jun 13 15:50:48 2005 From: superprad at gmail.com (PyPK) Date: 13 Jun 2005 12:50:48 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> Message-ID: <1118692248.242717.63770@g49g2000cwa.googlegroups.com> Is there any package out there which handles Tiff Images other than PIL or ImageMagic . From rtomek at ceti.pl Fri Jun 10 06:23:58 2005 From: rtomek at ceti.pl (Tomasz Rola) Date: Fri, 10 Jun 2005 12:23:58 +0200 (CEST) Subject: without shell In-Reply-To: <20050612174635.GA20992@mrna.tn.nic.in> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sun, 12 Jun 2005, km wrote: > hi all, > > can any linux command be invoked/ executed without using shell (bash) ? > what abt security concerns ? To answer your question fast, yes it is possible. Just pull every "bad" block from the OS, and put inside some replacement of your own. But it all depends on what exactly you are going to achieve... 1. Disabling rootkits/shellcodes. Without shell (i.e. bash/sh), you loose lots of functionality and you don't get as much in exchange. If what you want really is to disable execution of rootkits, shellcodes etc, then you need to disable almost every interesting program: perl, python, awk, sh, emacs, vi, web browsers with javascript, java, any compiler or interpreter that is installed, and possibly much more but they don't come to my mind right now. After doing so, you get an os that cannot boot past running /sbin/init and is "secure" because it is useless and can be as well turned off. Sure, you can replace/rename all those programs to have functionality and security but this will not protect your computer for too long. It all depends on how much someone wants to get to you. If there is one such person, the above mentioned steps will not help. It also requires much of work and in the result, you will have an incompatible OS i.e., no compatibility beyond some libraries and kernel stuff. I'm not even sure if it is possible to have full KDE/GNOME without shells. The same with X - its startup runs through few shell scripts before the real /usr/bin/X11/X is exec'd. There are better ways of securing Linux with less work and IMHO the resulting OS is much better than anything without shells, etc. at all. Google is your master. www.nsa.gov/selinux/ www.lids.org/ www.openwall.com/ 2. Running some minimal, barebone Linux with carefully carved functionality. You can replace /sbin/init with your own program and make it do whatever you need. Link it statically and you should not even need libraries, just one file and a kernel. Again, sometimes you can get similar or better results without sacrificing the whole OS, and with less work. But this subject is quite broad and so there is not much more to say. > regards, > KM Regards, Tomasz Rola - -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** -----BEGIN PGP SIGNATURE----- Version: PGPfreeware 5.0i for non-commercial use Charset: noconv iQA/AwUBQqlqSBETUsyL9vbiEQLVHwCfX3X0IyZLBq3k1uYJElNh1BUOFdIAoKaL ZH5Eqxq2EnN+XpDT9K79FNsK =Jusy -----END PGP SIGNATURE----- From erinhouston at gmail.com Mon Jun 13 10:12:15 2005 From: erinhouston at gmail.com (erinhouston at gmail.com) Date: 13 Jun 2005 07:12:15 -0700 Subject: separate IE instances? In-Reply-To: <1118668174.021378.244950@g47g2000cwa.googlegroups.com> References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> <1118165668.863841.291290@z14g2000cwz.googlegroups.com> <1118262051.519340.205600@z14g2000cwz.googlegroups.com> <1118668174.021378.244950@g47g2000cwa.googlegroups.com> Message-ID: <1118671935.537464.150380@z14g2000cwz.googlegroups.com> Sorry about that I had an instance of ie running in the background that was version 0 didn't see the problem tell this morining when my computer started to not work. it should be hwnds[1] should be hwnds[0]. I woud enumerate them like in the code below. If you have ie as your default browser you can use a shellExecute(0,None,"some url here", None, None, 1) To open directley to that page. Here is a more complete script: import win32api, time from win32com.client import Dispatch a = win32api.ShellExecute(0,None,"iexplore.exe", "www.ishpeck.net",None,1) b = win32api.ShellExecute(0,None,"iexplore.exe", "www.google.com",None,1) internetExplorerClassIdentity='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' hwnds = Dispatch(internetExplorerClassIdentity) # way I showed you before dosn't work verry well if more then one ie is open #ieObj = hwnds[0] #ieObj.Navigate("http://www.google.com/search?hl=en&lr=&q=python") time.sleep(30) for i in range(hwnds.Count): ....if hwnds[i].LocationURL.lower().find("ishpeck") > -1: ........ieObj1 = hwnds[i] ....if hwnds[i].LocationURL.lower().find("google") > -1: ........ieObj2 = hwnds[i] ieObj1.Navigate("http://www.google.com/search?hl=en&lr=&q=python") ieObj2.Navigate("http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ba1395566452dba6/343672a01d5b2cdc?hl=en#343672a01d5b2cdc") From curi at curi.us Thu Jun 2 03:39:37 2005 From: curi at curi.us (Elliot Temple) Date: Thu, 2 Jun 2005 00:39:37 -0700 Subject: Moving Places, Subtracting from slices/lists In-Reply-To: <429EB16C.1090509@snow.email.ne.jp> References: <429EACCE.8050101@snow.email.ne.jp> <429EB16C.1090509@snow.email.ne.jp> Message-ID: On Jun 2, 2005, at 12:12 AM, Mark Sargent wrote: > Hi All, > > getting closer, me thinks. > > >>>> hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin'] >>>> for x in hotcat[:]: >>>> > ... if x == 'roof': hotcat.insert(6,x) > ... del hotcat[x] > ... > Traceback (most recent call last): > File "", line 3, in ? > TypeError: list indices must be integers > > How do I get that x to be an integer b4 it is entered into the > indice.? > Cheers. if you add "print x" to the loop you will see that X is the various words. to get an integer, you could search the list for the index of x. but that's lame. btw hotcat[:] is a *copy* of hotcat, so just leave out "[:]" enumerate is a function that adds indexes to a list. observe: hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin'] for index, word in enumerate(hotcat): if word == 'roof': del hotcat[index] you could also use a list comprehension hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin'] hotcat = [x for x in hotcat if x != 'roof'] -- Elliot Temple http://www.curi.us/ --- [This E-mail scanned for viruses by Declude Virus] From mwm at mired.org Wed Jun 22 17:31:26 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 22 Jun 2005 17:31:26 -0400 Subject: import search path References: Message-ID: <86acli13kh.fsf@guru.mired.org> "SHELTRAW, DANIEL" writes: > Hello Python list > > If a Python program has an import statement like: > > import FFT > > how do I determine the path to the imported file? guru% python Python 2.4.1 (#2, Apr 25 2005, 21:42:44) [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5 Type "help", "copyright", "credits" or "license" for more information. py> import FFT py> import sys py> sys.modules['FFT'].__file__ '/usr/opt/lib/python2.4/site-packages/Numeric/FFT/__init__.pyc' http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From spam.csubich+block at block.subich.spam.com Tue Jun 14 00:20:14 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 14 Jun 2005 00:20:14 -0400 Subject: implicit variable declaration and access In-Reply-To: <6kj1o2-13e.ln1@lairds.us> References: <877jgy88do.fsf@hector.domek> <6kj1o2-13e.ln1@lairds.us> Message-ID: <1Qsre.83795$lQ3.77274@bignews5.bellsouth.net> Cameron Laird wrote: > cleaner algorithm somewhere in the neighborhood. In general, > "application-level" programming doesn't need exec() and such. > > PyPy and debugger writers and you other "systems" programmers > already know who you are. Out of curiosity, where would you classify interpreters for secondary app-specific programming languages? Specifically, mud-client stored procedures (triggers, timed events) seem to correspond very naturally to generating the python code required to execute them in advance, then compile()ing and storing the compiled code for repeated execution. From wookiz at hotmail.com Sun Jun 12 04:35:21 2005 From: wookiz at hotmail.com (wooks) Date: 12 Jun 2005 01:35:21 -0700 Subject: Python Developers Handbook - Mistake done and corrected. In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <1118399995.306455.161220@o13g2000cwo.googlegroups.com> <1118404332.349662.82650@g44g2000cwa.googlegroups.com> Message-ID: <1118565321.469787.81700@f14g2000cwb.googlegroups.com> I am not mistaken at all and the use of hyperbole (2 billion!!!!) doesn't make your point . A post that piques the interest of even 50 people in an NG is a valid one. No doubt some people would be annoyed about a job posting of a Python vacancy... others would be interested in it... The original complainer expanded his complaint to say that I had not included sufficient information. I addressed that and apologised. For many that would have been the end of the matter. Since you want to talk about Usenet at large 1. I have made similar posts regarding books in my library to other NG's. 2. This is the only NG where anybody has complained (apart from your postage/starting price is too high). 3. This book has achieved the highest number of hits (179) than any other book I have promoted in this way. More even than a football book on the history of the Arsenal v Spurs fixture that I posted to both the Arsenal and Spurs NG (only managed 160). So the only NG that complained is the one that showed the most interest. What is far more off-topic for this NG are the posts pontificating about netiquette and usenet when really they are just whinges. From ewill at sirius.athghost7038suus.net Wed Jun 1 22:00:09 2005 From: ewill at sirius.athghost7038suus.net (The Ghost In The Machine) Date: Thu, 02 Jun 2005 02:00:09 GMT Subject: * * * Please Read And/Or Print This! * * * Press [Ctrl][P] Keys On Your Keyboard To Print >> June 1, 2004 8:23:43 pm >> http://115639.aceboard.net/forum2.php?rub=158&cat=61&login=115639&page=0#id96 << * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * References: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> Message-ID: In comp.os.linux.advocacy, eprint10108 at yahoo.com wrote on 1 Jun 2005 17:23:05 -0700 <1117671785.262410.76790 at o13g2000cwo.googlegroups.com>: > * * * Please ... ... go jump in a lake. [rest snipped] -- #191, ewill3 at earthlink.net It's still legal to go .sigless. From ptmcg at austin.rr.com Mon Jun 27 12:08:34 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Jun 2005 09:08:34 -0700 Subject: Beginner question: Converting Single-Element tuples to list References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <3i9jdvFkhd21U1@individual.net> <11c02rpkqriad6c@news.supernews.com> Message-ID: <1119888514.041655.18640@g49g2000cwa.googlegroups.com> John - I just modified my test program BNF to use ZeroOrMore instead of OneOrMore, and parsed an empty string. Calling list() on the returned results gives an empty list. What version of pyparsing are you seeing this None/object/list behavior? -- Paul From jbellis at gmail.com Sun Jun 12 12:35:16 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 12 Jun 2005 09:35:16 -0700 Subject: Capture close window button in Tkinter References: Message-ID: <1118594116.113290.26070@g47g2000cwa.googlegroups.com> William Gill wrote: > I am trying to make a simple data editor in Tkinter where each data > element has a corresponding Entry widget. I have tried to use the > FocusIn/FocusOut events to set a 'hasChanged' flag (if a record has not > changed, the db doesn't need updating). This seems to work fine except > that when the user finishes and clicks a 'done' button or the close > window button (in the root widget) no FocusOut event is triggered. I > can trigger a FocusOut event if the 'done' button opens another window > (i.e. a messagebox) that takes focus. Enter and Leave follow the mouse, > but don't trigger when the user tabs between fields. > > Is there a better way to monitor 'hasChanged'? I'd go with monitoring keypresses in the Entry widget. > Also, how do I capture > the root window close button? root = Tk() root.protocol("WM_DELETE_WINDOW", onexit) From prabapython at yahoo.co.in Tue Jun 21 02:26:43 2005 From: prabapython at yahoo.co.in (praba kar) Date: Tue, 21 Jun 2005 07:26:43 +0100 (BST) Subject: regarding cache clearing header in python cgi Message-ID: <20050621062643.74244.qmail@web8402.mail.in.yahoo.com> Dear All, In Php the following headers base we can clean the cache in the url "header('Cache-Control: no-store, no-cache, must-revalidate'); " I want to know Php equivalent headers in Python-cgi If anybody know regarding this kindly mail me. regards, Prabahar _______________________________________________________ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From shane at hathawaymix.org Wed Jun 22 00:14:07 2005 From: shane at hathawaymix.org (Shane Hathaway) Date: Tue, 21 Jun 2005 22:14:07 -0600 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <42B8E58F.2000102@hathawaymix.org> Remi Villatel wrote: > Hi there, > > There is always a "nice" way to do things in Python but this time I can't > find one. > > What I'm trying to achieve is a conditionnal loop of which the condition > test would be done at the end so the loop is executed at least once. It's > some way the opposite of "while". > > So far, all I got is: > > while True: > some(code) > if final_condition is True: > break > # > # > > What I don't find so "nice" is to have to build an infinite loop only to > break it. FWIW, my own experience is that the "while True" idiom is actually safer and better than alternatives like do/while. I used to write do/while loops all the time, but I wound up with more than my fair share of unintentionally infinite loops. I put too much trust in the syntax: I expected that since I was using the cleaner construct, I didn't have to worry about infinite loops. Now, I think of "while True" not as an infinite loop, but rather as a sign reminding me to be wary of looping infinitely in a particular spot. I feel like this has resulted in a lot fewer infinite loops in my own code. Now I believe that any loop that can't be represented well with "for" or a conditional "while" has enough inherent complexity to justify a warning sign, and "while True" has bright yellow flashing lights all over it. Thus I'm quite in favor of the status quo. Shane From davidb at mcs.st-and.ac.uk Wed Jun 1 19:24:08 2005 From: davidb at mcs.st-and.ac.uk (David Boddie) Date: 1 Jun 2005 16:24:08 -0700 Subject: scripting browsers from Python References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> <1117542360.436302.207150@o13g2000cwo.googlegroups.com> <1117616955.339925.90800@g43g2000cwa.googlegroups.com> Message-ID: <1117668248.781069.102790@f14g2000cwb.googlegroups.com> Michele Simionato wrote: > This looks interesting, but I need an example here. What would be the > command to open Konqueror to a given page and to post a form with given > parameters? Launch Konqueror, note the process ID (pid), and use the dcop command line tool to open the page at a specified URL: dcop konqueror- konqueror-mainwindow#1 openURL Unfortunately, I don't think it's possible to manipulate the page purely with DCOP, even with Python bindings, although I hope that someone can prove me wrong. > kde.org has tons a material, but I am getting lost and I don't find > anything relevant to my simple problem. A quick search revealed this discussion about using JavaScript with DCOP: http://lists.kde.org/?l=kfm-devel&m=103661664427286&w=2 This might be the best you can hope for with scripting outside the browser. I've been trying to enable support for in-browser scripting with Konqueror using KPart plugins, but this requires up to date versions of sip, PyQt and PyKDE: http://www.riverbankcomputing.co.uk If you want to pursue that route, let me know and I'll try and tidy up what I have. David From rossnixon at gmail.com Sun Jun 12 05:38:46 2005 From: rossnixon at gmail.com (ross) Date: 12 Jun 2005 02:38:46 -0700 Subject: What language to manipulate text files References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: <1118569126.540000.217730@o13g2000cwo.googlegroups.com> Roose wrote: > Why do people keep asking what language to use for certain things in the > Python newsgroup? Obviously the answer is going to biased. > > Not that it's a bad thing because I love Python, but it doesn't make sense > if you honestly want an objective opinion. > > R What usenet group is it best to ask in then? Is there one where people have good knowledge of many scripting languages? Ross From eurleif at ecritters.biz Thu Jun 16 03:18:25 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 16 Jun 2005 07:18:25 GMT Subject: Regex for repeated character? Message-ID: <5J9se.136$Q75.39412@newshog.newsread.com> How do I make a regular expression which will match the same character repeated one or more times, instead of matching repetitions of any (possibly non-same) characters like ".+" does? In other words, I want a pattern like this: >>> re.findall(".+", "foo") # not what I want ['foo'] >>> re.findall("something", "foo") # what I want ['f', 'oo'] From rkern at ucsd.edu Sat Jun 18 23:57:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 18 Jun 2005 20:57:25 -0700 Subject: Extensions on Linux: import without underscore? In-Reply-To: References: Message-ID: James Carroll wrote: > Hi, I'm creating an extension called _bright.so on linux. I can > import it with import _bright, but how can I import bright and get the > package? > > On windows, I've been able to import bright instead of import _bright, That has to be a bug. You shouldn't rely on that behavior. > but on Linux it seems to need the underscore. I'm tempted to create a > bright.py with from _bright import *, but I'm wondering if there's a > more direct way. Call it bright.so . > Also, I'm using scons to generate my lib, and it insists on prepending > the characters lib to my library name, so if I tell it to generate > _bright.so it gives me lib_bright.so. Is there a way of turning this > off so I don't have to rename it back to _bright.so? If at all possible, you should use distutils to build Python extensions. If you must use Scons, read http://www.scons.org/cgi-bin/wiki/PythonExtensions and use SharedLibrary(... SHLIBPREFIX="", ...) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From chinook.nr at tds.net Sun Jun 12 20:52:41 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 12 Jun 2005 20:52:41 -0400 Subject: case/switch statement? References: Message-ID: <0001HW.BED251190019755AF0284550@news.gmane.org> On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote (in article ): > Steven D'Aprano wrote: >> On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote: >>> If the case values are constants known to the compiler, it can generate >>> O(1) >>> code to take the correct branch. >>> It is precisely this behavior that is desired in many situations. >> >> Agreed. I certainly don't object to sensible optimizations! But the number >> of if...elif statements which can be optimised are a vanishingly small >> subset of the number of possible if...elif statements. >> >> And you can bet your last dollar that many people will use case statements >> even when doing so gives no advantage, in a mistaken opinion that it will >> be somehow magically faster. > > Case statements are actually more suitable in many cases even when > performance is not a goal for reasons of *readability*. > > When reading an if statement, you have to scan down through effective > each statement attempting to find the case in which you are interested. > Some cases can be compound. The nested ifs can get confused with the > surrounding ones (in Python or a language with explicit block > delimiters). The cases are often not written in any particular order, > or they are ordered *for* performance reasons, but in ways that make it > harder to "scan". > > A case statement, on the other hand, can be a message from the > programmer, saying in effect "here's code that represents a series of > _simple_ conditionals, ordered (usually) in a sensible way (e.g. > ascending numerical order), so just jump to the case you want and carry > on maintaining this nice code." > > In current Python the equivalent approach is, of course, a dictionary of > some kind, though it's arguable whether this is as clean in many cases > as a case statement would be. > > -Peter > I'm new to Python, but I'm retired from a software engineering career that began in the early 60s. I'm not against case statements in the simplest syntactical context, but over the years I've seen so many abuses of such (i.e. difficult to follow code) that neither am I against their exclusion from Python. The thought being (in my mind) that such might force the programmer to rethink their approach to something more intuitively structured (whether module/function wise or OO wise or some combination), though I admit it is an idealistic view. The problem I do see is your apples and oranges argument. You are equating at the extreme, "compound" if conditions with "_simple_" case statement conditionals. Yet you are leaving out of your argument the transition from the former to the latter. If mapping one to the other is simple then the readability is no harder with if statements. An example might be in dealing with variably formated records where each record contains a record type flag. On the other hand if you were to map compound conditions to "_simple_" case statement conditionals, you need an intermediate translation that must be studied to understand the "_simple_" conditionals anyway. Such translations also promote an overabundance of status/flag variables to understand and follow which does not increase the readability of code. In my experience I've also seen where case statements promote overly long and partially repetitive code blocks, which would be better constructed in a top-down fashion. Admittedly, if statements could be used in a similar way but I've not seen the same level of abuse with such. So arguably, if the translation is pretty much one to one then the argument is mute :~) If on the other hand the translation is many to one, then one's skill in developing well structured readable code is really the issue, and again case statements are a mute point. Lee C From d at e.f Sun Jun 19 22:21:18 2005 From: d at e.f (D H) Date: Sun, 19 Jun 2005 21:21:18 -0500 Subject: Loop until condition is true In-Reply-To: References: <1119074614.700809@yasure> Message-ID: Joseph Garvin wrote: > Peter Otten wrote: > >> I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of >> "for >> (" in the Python 2.4 source, so using these rough estimates do-while >> still >> qualifies as "rarely used". >> >> Peter >> >> >> > That's 136 times you'd have to use an ugly hack instead. I definitely > wouldn't mind an until or do/while. Yeah a do while loop was proposed over 2 years ago, but nothing ever came of it: http://www.python.org/peps/pep-0315.html It's been discussed for many many years, and again recently: http://mail.python.org/pipermail/python-dev/2005-June/054167.html From roy at panix.com Sat Jun 11 22:22:59 2005 From: roy at panix.com (Roy Smith) Date: Sat, 11 Jun 2005 22:22:59 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: "Philippe C. Martin" wrote: > Yet, many issues that a future software engineer should know are > mostly hidden by Python (ex: memory management) and that could be > detrimental. I know I'm going out on a limb by asking this, but why do you think future software engineers should know about memory management? I used to worry about register allocation. Today, I don't even know how many registers any machine I work on has. I used to worry about word size, and byte order. I used to worry about whether stacks grew up or down and addressing modes and floating point formats. Sure, somebody's got to worry about those things, but most people who write software can be blissfully ignorant (or, at best, dimly aware) of these issues because somebody else (compiler writer, hardware designer, operating system writer, etc) has already done the worrying. There used to be a time when you had to worry about how many tracks to allocate when you created a disk file. When's the last time you worried about that? From rkern at ucsd.edu Mon Jun 13 14:22:01 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 13 Jun 2005 11:22:01 -0700 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: References: Message-ID: rbt wrote: > Here's the scenario: > > You have many hundred gigabytes of data... possible even a terabyte or > two. Within this data, you have private, sensitive information (US > social security numbers) about your company's clients. Your company has > generated its own unique ID numbers to replace the social security numbers. > > Now, management would like the IT guys to go thru the old data and > replace as many SSNs with the new ID numbers as possible. You have a tab > delimited txt file that maps the SSNs to the new ID numbers. There are > 500,000 of these number pairs. What is the most efficient way to > approach this? I have done small-scale find and replace programs before, > but the scale of this is larger than what I'm accustomed to. > > Any suggestions on how to approach this are much appreciated. I'm just tossing this out. I don't really have much experience with the algorithm, but when searching for multiple targets, an Aho-Corasick automaton might be appropriate. http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ Good luck! -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From duncan.booth at invalid.invalid Tue Jun 7 04:50:10 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 Jun 2005 08:50:10 GMT Subject: split up a list by condition? References: <3gjpk0FcrnknU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Hi, > > while writing my solution for "The python way?", I came across this > fragment: > > vees = [c for c in wlist[::-1] if c in vocals] > cons = [c for c in wlist[::-1] if c not in vocals] > > So I think: Have I overlooked a function which splits up a sequence > into two, based on a condition? Such as > > vees, cons = split(wlist[::-1], lambda c: c in vocals) > > Reinhold If you really are being charged by the number of newline characters in your code you could write: >>> wlist = list('The quick brown fox') >>> vowels = 'aeiuo' >>> cons = [] >>> vees = [ c for c in wlist if c in vowels or cons.append(c) ] >>> cons ['T', 'h', ' ', 'q', 'c', 'k', ' ', 'b', 'r', 'w', 'n', ' ', 'f', 'x'] >>> vees ['e', 'u', 'i', 'o', 'o'] >>> cons = [] >>> vees = [ c for c in wlist[::-1] if c in vowels or cons.append(c) ] >>> cons ['x', 'f', ' ', 'n', 'w', 'r', 'b', ' ', 'k', 'c', 'q', ' ', 'h', 'T'] >>> vees ['o', 'o', 'i', 'u', 'e'] but every penny you save writing a one liner will be tuppence extra on maintenance. From mg.mailing-list at laposte.net Mon Jun 20 02:44:10 2005 From: mg.mailing-list at laposte.net (mg) Date: Mon, 20 Jun 2005 08:44:10 +0200 Subject: catch argc-argv Message-ID: <42B665BA.4070108@laposte.net> Hello, I am writting bindings for a FEM application. In one of my function 'initModulename', called when the module is imported, I would like to get the argc and argv arguments used in the main function of Python. So, my question is: does the Python API containe fonctions like 'get_argc()' and 'get_argv()' ? Thanks, From efoda5446 at yahoo.com Sat Jun 11 13:30:53 2005 From: efoda5446 at yahoo.com (Lorn) Date: 11 Jun 2005 10:30:53 -0700 Subject: Dynamic Lists, or...? Message-ID: <1118511053.455332.231570@g44g2000cwa.googlegroups.com> I'm trying to figure out a way to create dynamic lists or possibly antother solution for the following problem. I have multiple lines in a text file (every line is the same format) that are iterated over and which need to be compared to previous lines in the file in order to perform some simple math. Each line contains 3 fileds: a descriptor and two integers. Here is an example: rose, 1, 500 lilac, 1, 300 lilly, 1, 400 rose, 0, 100 The idea is that the 0/1 values are there to let the program know wether to add or subtract the second integer value for a specific descriptor (flower in this case). So the program comes upon rose, adds the 500 to an empty list, waits for the next appearance of the rose descriptor and then (in this case) subtracts 100 from 500 and prints the value. If the next rose was a 1 then it would have added 100. I'm uncertain on how to approach doing this though. My idea was to somehow be able to create lists dynamically upon each new occurence of a descriptor that currently has no list and then perform the calculations from there. Unfortunately, the list of descriptors is potentially infinte, so I'm unable to previously create lists with the descriptor names. Could anyonw give any suggestions on how to best approach this problem, hopefully I've been clear enough? Any help would be very gratly appreciated. Best regards, Lorn From brianhray at gmail.com Tue Jun 14 16:38:03 2005 From: brianhray at gmail.com (brianhray at gmail.com) Date: 14 Jun 2005 13:38:03 -0700 Subject: CodeWarrior Automation with Python? Message-ID: <1118781483.644562.289400@g43g2000cwa.googlegroups.com> When looking for a pythonic way to convert some Mac codewarrior projects, I came across some files hidden deap into the Python.Framework under: plat-mac/lib-scriptpackages/CodeWarrior What is this stuff? Would any of this be helpful in my search for an automated conversions of the exported xml file generated by CodeWarrior 8, 9 into a project file? Brian Ray http://brianray.chipy.org From "myname" at example.invalid Fri Jun 10 17:08:57 2005 From: "myname" at example.invalid (VK) Date: Fri, 10 Jun 2005 23:08:57 +0200 Subject: bind in Tkinter In-Reply-To: References: Message-ID: <3guds3Fef8klU2@news.dfncis.de> Shankar Iyer (siyer at Princeton.EDU) wrote: > I believe the quit function is built in. Anyway, I get the same type of error if I substitute a function that I have defined. > > Shankar > > ----- Original Message ----- > From: VK > Date: Friday, June 10, 2005 4:53 pm > Subject: Re: bind in Tkinter > > >>Shankar Iyer (siyer at Princeton.EDU) wrote: >> >>>I have been trying to learn how to associate keyboard events with >> >>actions taken by a Python program using Tkinter. From what I've >>read online, it seems that this is done with the bind methods. In >>one of my programs, I have included the following: >> >>>self.enternumber = Entry(self) >>>self.enternumber.bind("",self.quit) >>>self.enternumber.pack({"side":"top"}) >>> >>>It seems to me that, as a result of this code, if the enternumber >> >>Entry widget is selected and then the key is pressed, then >>the program should quit. Indeed, it seems that the program does >>attempt to quit, but instead an error message appears claiming that >>quit() takes 1 argument but 2 are given. I get the same type of >>error if I replace self.quit with some function that I have >>written. I am not sure how to fix this problem and hope that >>someone here can spot my error. Thanks for your help. >> >>>Shankar >>> >>> >> >>Have you defined quit function? >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > for built-in you don't need *self* If you define yours, try def quit(self,event=0) From renwei at koal.com Tue Jun 28 21:13:33 2005 From: renwei at koal.com (renwei) Date: Wed, 29 Jun 2005 09:13:33 +0800 Subject: Creating Python wrapper for DLL References: <1119990428.163115.152440@g49g2000cwa.googlegroups.com> Message-ID: use ctype: http://starship.python.net/crew/theller/ctypes/ "Tim" ???? news:1119990428.163115.152440 at g49g2000cwa.googlegroups.com... > I have a DLL, and a C .h file that exports a bunch of functions from > the DLL. I would like to create a Python extension module for these > functions. > > I have read the "Extending and Embedding" documentation in the Python > 2.4 release. I understand how to extend C code for use in Python if I > have access to the C source code (I think). But... > > Will I be able to create Python extensions for my DLL functions if I do > not have access to the DLL source code? > From martin.witte at gmail.com Mon Jun 6 12:12:56 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 6 Jun 2005 09:12:56 -0700 Subject: Question about Object Oriented + functions/global vars? References: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> Message-ID: <1118074376.475660.183950@g44g2000cwa.googlegroups.com> Well, if you want to apply object orientatation techniques to your work you would get something like this. Polymorphism is used to distinct between the ftp method. Another concept is data encapsulation, see the filedescription class . A third technique is inheritance - ftp is derived from an existing object, the get classes are derived from my ftp class. But most of all it is a different way of organizing your work, for your code I think it makes sense to split the work between an ftp class and a filedescrition class - where you can add methods to record the status of the retrieval. #!/usr/bin/env python import ftplib import os.path import sys class ftp_err(Exception): pass class ftp(ftplib.FTP): def __init__(self, address, filedescription, user = None, password = None): ftplib.FTP.__init__(self, address) self.login(user, password) self.filedescription = filedescription def list(self): return self.nlst() def cd(self, directory): self.cwd(directory) def quit(self): self.quit() class ftp_get(ftp): def get(self): cmd = 'RETR %s' % self.filedescription.name self.retrlines(cmd, open(self.filedescription.name, 'w').write) class ftp_get_binary(ftp): def get(self): cmd = 'RETR %s' % self.filedescription.name self.retrbinary(cmd, open(self.filedescription.name, 'wb').write) class filedescription(object): def set_name(self, name): self.__name = name def get_name(self): return self.__name name = property(get_name, set_name) def _get_texttype(self): ext = os.path.splitext(self.name)[1] if ext in ('.txt', '.htm', '.html'): return True else: return False def get_texttype(self): return self._get_texttype() text = property(get_texttype) def get_binarytype(self): return not self._get_texttype() binary = property(get_binarytype) f1 = filedescription() f1.name = 'download.ht' f2 = filedescription() f2.name = 'download.html' ftp_site = 'ftp.python.org' ftp_dir = 'pub/docs.python.org' for i in (f1, f2): try: f = None if i.text: f = ftp_get(ftp_site, i) elif i.binary: f = ftp_get_binary(ftp_site, i) f.cd(ftp_dir) f.get() except Exception, e: print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) From listserver at tdw.net Sat Jun 18 09:23:13 2005 From: listserver at tdw.net (Tim Williams) Date: Sat, 18 Jun 2005 14:23:13 +0100 Subject: smtplib and TLS References: <1119034830.168876.26290@f14g2000cwb.googlegroups.com><7xmzposrod.fsf@ruckus.brouhaha.com><1119079978.179618.262380@o13g2000cwo.googlegroups.com> <7xmzpoyusq.fsf@ruckus.brouhaha.com> Message-ID: <000c01c57408$e15f3280$ccbefea9@twilliams> ----- Original Message ----- From: "Paul Rubin" "http://phr.cx"@NOSPAM.invalid > "Matthias Kluwe" writes: > > Hmm. I tried > > > > server.sock.realsock.shutdown(2) > > before server.quit() with the result of > > I don't think that's exactly what you want. You need to send a > specific TLS message BEFORE shutting down the socket, to tell the > other end that the TLS connection is ending. That tells the server > that it shouldn't accept a TLS session resumption later. The close > notify message is required because if you don't send it, an attacker > could truncate one of your TLS messages by cutting your connection. > > Basically the socket library's SSL implementation is pretty crude. > You might try http://trevp.net/tlslite for a pure-Python > implementation that's also still missing stuff, but is getting there. I have found problems with the TLS built into smtplib when you are doing something with sock elswhere in your app. eg for me using [something].sock.settimeout(x) or setting the default timeout anywhere broke TLS in smtplib. Have you verified that its your end that is broken, not gmail's, do other servers give the same response ? The following servers accept incoming TLS on port 25 e32.co.us.ibm.com mail.donkeyisland.com smtp.myrealbox.com And for quick tests you don't need to send an email (or authenticate), just use a NOOP after STARTTLS (and perhaps a RSET) then QUIT eg server = smtplib.SMTP(hostname [,port]) server.set_debuglevel(1) server.ehlo('x') server.starttls() server.ehlo('x') server.noop() server.rset() server.quit() Trevor's http://trevp.net/tlslite did the job nicely, solving my previous TLS problems (completely untested) from tlslite.api import * > > server = SMTP_TLS('smtp.gmail.com', 587) server.set_debuglevel(1) server.ehlo() settings = HandshakeSettings() server.starttls(settings=settings) server.ehlo() server.login('mkluwe at gmail.com', password) server.sendmail("mkluwe at gmail.com", toaddress, message) server.quit() HTH :) From rbt at athop1.ath.vt.edu Sun Jun 5 13:27:31 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 05 Jun 2005 13:27:31 -0400 Subject: How many threads are too many? Message-ID: This may be a stupid question, but here goes: When designing a threaded application, is there a pratical limit on the number of threads that one should use or is there a way to set it up so that the OS handles the number of threads automatically? I am developing on 32-bit x86 Intel systems with python 2.4.1. The OS will be Linux and Windows. I have an older app that used to work fine (254 threads) on early 2.3 Pythons, but now, I get this error with 2.4.1 and 2.3.5: Traceback (most recent call last): File "net_queue_and_threads.py", line 124, in ? thread.start() File "/usr/lib/python2.3/threading.py", line 416, in start _start_new_thread(self.__bootstrap, ()) thread.error: can't start new thread From mwm at idiom.com Mon Jun 20 19:35:32 2005 From: mwm at idiom.com (Mike Meyer) Date: 20 Jun 2005 16:35:32 -0700 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> <42AFB8FD.1060504@REMOVEMEcyber.com.au> <3hb8jbFgauajU1@individual.net> Message-ID: <5jmzpklhyz.fsf@idiom.com> "Claudio Grondi" writes: > > What has it all to do with Python? To be not fully off-topic, I > suggest here, that it is much easier to discuss programming > related matters (especially in case of Python :-) or mathematics > than any other subjects related to nature, because programming is > _so easy_ compared to what is going on in the "real world". > I see the reason for that in the fact, that programming is based > on ideas and rules developed by humans themselves, so it is > relatively easy to test and proove if statements are right or not. As a mathematician, I have to say "ugh". Not all statements are easy to test and prove. In fact, in any non-trivial mathematical system, there will be statements that *cannot* be proven to be either true or false. Some of those statements are interesting. The legends of mathematics are problems that aren't easy to test and prove: fermant's last theorem, the four color map theorem, and so on. Check out for a longer list. It's not clear that the ideas/rules were "developed" by humans. I'd say "discovered". In some cases in the past, mathematicians unhappy about some rule set out to show that it must be true (or false). In failing to show that, they invented a new branch of mathematics. I'd say programming is more like that. But I approach programming from a mathematicians viewpoint. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at REMOVETHIScyber.com.au Sat Jun 18 14:00:35 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 19 Jun 2005 04:00:35 +1000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> Message-ID: On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote: > Furthermore, protecting you from someone else making money off a copy of > your program is basically what licenses are for, and if you have noticed > they don't protect even Microsoft (see, for example, entire governments > like the Indonesian government, which has mass-pirated Microsoft > software for a long time). Please call it what it is: copyright infringement, not piracy. Piracy takes place in international waters, and involves one or more of theft, murder, rape and kidnapping. Making an unauthorized copy of a piece of software is not piracy, it is an infringement of a government-granted monopoly. In any case, there is a powerful argument for wanna-be Microsofts to turn a blind eye to copyright infringements. It worked for Microsoft and almost every other successful software company. The biggest barrier to success for software developers is getting people to even know your software exists. The second biggest barrier is encouraging them to try your software. The third is getting them to keep using your software once they've tried it. Actually collecting money from them is at the bottom of the list -- you can't expect people to pay you for using your software if they don't even know you exist. Apart from the occasional public rant (such as Bill Gates' plea to users not to make illegal copies of MS BASIC), in the early days Microsoft didn't go out of their way to chase copyright infringers. If they had, the users would have simply stopped using the MS software and used something else. Instead, people grabbed copies of Word or Excel from their friends, taking market share from WordPerfect, WordStar, Lotus etc. Eventually, they would need an upgrade, or find it more convenient to buy than to copy. Every so-called "pirated copy" had (at least) four benefits to Microsoft: it denied a sale to Microsoft's competitors; it increased users' familiarity and confidence with Microsoft's products; it built Microsoft's brand recognition among software purchasers and IT departments; and it was (usually) a future sale to Microsoft. It was only as Microsoft approached monopoly status that copyright infringement began to hurt them more than it gained them. With few if any competitors, the loss of revenue from unauthorized copies of Word or Excel or Windows became greater than the benefits. -- Steven. From jepler at unpythonic.net Thu Jun 2 14:03:24 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Jun 2005 13:03:24 -0500 Subject: TkInter Listbox Widget Formatting In-Reply-To: References: Message-ID: <20050602180324.GD19350@unpythonic.net> This isn't an option in the stock Tk listbox or any of the alternatives I know of offhand (bwidget ListBox, TixTList). The TkTable widget, which can also display multiple columns, can select different justifications, either for the whole table, or for single cells. I've never used TkTable with Python/Tkinter, however. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tjreedy at udel.edu Wed Jun 22 15:01:51 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Jun 2005 15:01:51 -0400 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net><11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:11bja5bienakv68 at corp.supernews.com... > I'm working on it. I should have said it's trivial if you have > access to the platforms to be supported. I've tested a fix > that supports pickle streams generated under Win32 and glibc. > That's using the "native" string representation of a NaN or > Inf. > > A perhaps simpler approach would be to define a string > representation for Python to use for NaN and Inf. Just because > something isn't defined by the C standard doesn't mean it can't > be defined by Python. I believe that changes have been made to marshal/unmarshal in 2.5 CVS with respect to NAN/INF to eliminate annoying/surprising behavior differences between corresponding .py and .pyc files. Perhaps these revisions would be relevant to pickle changes. TJR From http Wed Jun 8 18:17:02 2005 From: http (Paul Rubin) Date: 08 Jun 2005 15:17:02 -0700 Subject: Fast text display? References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> <7xll5ka7mv.fsf@ruckus.brouhaha.com> Message-ID: <7xvf4otrxd.fsf@ruckus.brouhaha.com> Christopher Subich writes: > Fair enough. At the moment, the expected user base for the program is > exactly one, but making it easy has its advantages. Since you've > obviously used it yourself, if I end up going with tkinter, are there > any performance gotchas on text rendering that I should be aware of? We're just talking about a scrolling text window that has to run at human reading and typing speeds, right? It shouldn't be a problem. I've used the text widget and found it to be fast enough for what I was doing, though I didn't exactly stress it. From mistobaan at gmail.com Wed Jun 1 13:00:21 2005 From: mistobaan at gmail.com (M1st0) Date: 1 Jun 2005 10:00:21 -0700 Subject: Information about Python Codyng Projects Ideas Message-ID: <1117645221.920027.224880@g14g2000cwa.googlegroups.com> Hi to All! I would like to join the Google summer code program (http://code.google.com/summerofcode.html). >From the sponsored links I have choose to help The Python Software Foundation, because I like a lot the language. I have read the proposed Ideas from http://wiki.python.org/moin/CodingProjectIdeas And the more interesting for me were those about Optimization. MemoryUsageProfiler ProfileReplacementProject SpeedUpInterpreterStartup But I many of this there are very few information or nothing about of what is really needed. I am taking a Master in Computer Science so I know many of the issues in this topics, but I would like some hints and every usefull information. I hope that here is the right place for this kind of discussion. Kind Regards From dalke at dalkescientific.com Tue Jun 14 03:53:35 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 14 Jun 2005 07:53:35 GMT Subject: "also" to balance "else" ? References: Message-ID: Terry Hancock wrote: > No, I know what it should be. It should be "finally". It's already > a keyword, and it has a similar meaning w.r.t. "try". Except that a finally block is executed with normal and exceptional exit, while in this case you would have 'finally' only called when the loop exited without a break. Andrew dalke at dalkescientific.com From usenet.20.evilspam at spamgourmet.com Sun Jun 12 14:06:46 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 18:06:46 GMT Subject: How to get/set class attributes in Python In-Reply-To: <42ac6b5b$0$27173$626a14ce@news.free.fr> References: <42ac6b5b$0$27173$626a14ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > And *this* is highly unpythonic. And un-OO too, since it makes foo() > dependant on *class* Bar, when it should most probably be enough that it > only depends on (probably part of) the *interface* of class Bar. I was providing the original poster with a simple way to ensure appropriate type. You can assert whatever aspect you wish. If you want to ensure compatibility with some other property simply use "assert blah" subsituting blah for whatever test you wish to perform (e.g. assert MyInterface.implementedBy(bar) to test for interface implementation). From ladasky at my-deja.com Sat Jun 18 11:07:04 2005 From: ladasky at my-deja.com (ladasky at my-deja.com) Date: 18 Jun 2005 08:07:04 -0700 Subject: Migrating from Windows to OS X In-Reply-To: <0001HW.BED99CB20042B4FEF0407550@news.individual.de> References: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> <0001HW.BED99CB20042B4FEF0407550@news.individual.de> Message-ID: <1119107224.205327.127150@g49g2000cwa.googlegroups.com> Kalle Anke wrote: > On Sat, 18 Jun 2005 09:26:23 +0200, ladasky at my-deja.com wrote > (in article <1119079582.973569.191490 at f14g2000cwb.googlegroups.com>): > > > I am sitting in front of a nice new PowerBook portable which has OS > > 10.4 installed. The Python.org web site says that Apple has shipped OS > > 10.4 with Python 2.3.5 installed. How exactly do I access this? I > > have searched through the Applications and Libraries folders. I found > > the site-packages directory, but nothing other than that. > > Launch Terminal (can be found in /Application/Utilities/) > > type python > > that's it O.K., I found it... thanks! I haven't been down to the UNIX prompt on the Mac before. How are the development tools for the Mac? I'll use IDLE if it's available, but I like Scintilla better. Repeating my thanks, John Ladasky From ggg at zzz.it Thu Jun 9 08:56:32 2005 From: ggg at zzz.it (deelan) Date: Thu, 09 Jun 2005 14:56:32 +0200 Subject: MySQLDBAPI In-Reply-To: References: Message-ID: <2tqln2-6c3.ln1@news.interplanet.it> Gregory Pi?ero wrote: > Hey guys, (...) > > My first question is if there is anything built into python as far as > a Database API that will work with MySQL. It seems like there should > be because Python without it is kinda useless for web development. If > there is then I'd probably prefer to use that instead. there is not. mysqldb module is the answer. (...) >>>cd MySQL-python-1.2.0 >>>python2.4 setup.py install --home=~ > > running install > running build > running build_py > running build_ext > building '_mysql' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall > -Wstrict-prototypes -fPIC -I/usr/local/include/python2.4 -c _mysql.c > -o build/temp.linux-i686-2.4/_mysql.o > -I'/usr/local/mysql/include/mysql' > _mysql.c:41:19: mysql.h: No such file or directory > _mysql.c:42:26: mysqld_error.h: No such file or directory > _mysql.c:43:20: errmsg.h: No such file or directory > error: command 'gcc' failed with exit status 1 you need mysql-devel package installed to compile the "_mysql" extension. just look a the release notes: HTH. -- deelan, #1 fan of adriana lima! From vb_dev2005 at yahoo.com Sat Jun 25 05:18:26 2005 From: vb_dev2005 at yahoo.com (vb_dev2005) Date: Sat, 25 Jun 2005 09:18:26 -0000 Subject: Excellent Site for Developers Message-ID: Excellent Site for Developers - you can ask any Question in VB6 or VB.NET - you can download the best VB Books - you can download ActiveX - you can visit the most powerfull VB sites http://www.mox-hosting.com/vbdevs/ From ivanlan at pauahtun.org Thu Jun 2 21:01:40 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 02 Jun 2005 19:01:40 -0600 Subject: REQ: Small Perl to Python conversion needed References: <020620052018031433%user@unknown.invalid> <429fa98b$1@news.eftel.com> Message-ID: <429FABF4.2BA3E4B2@pauahtun.org> Hi All-- John Machin wrote: > > > how to duplicate the following bit of code using Python dictionaries. > > > > [expletives deleted] > +1 QOTW Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From projecktzero at yahoo.com Fri Jun 24 14:03:53 2005 From: projecktzero at yahoo.com (projecktzero) Date: 24 Jun 2005 11:03:53 -0700 Subject: Getting binary data out of a postgre database Message-ID: <1119636233.488038.170240@z14g2000cwz.googlegroups.com> Well, I've managed to get an image into a postgre database, but now I'm having trouble getting it out. #! /usr/bin/env python from pyPgSQL import PgSQL def main(): connectdb = PgSQL.connect('server:port:database:username:password') cur = connectdb.cursor() sqlStatement = """SELECT image from images where image_id = 1""" cur.execute(sqlStatement) rec = cur.fetchone() # TODO make temp file name include image_id. # TODO use tempfile module # TODO clean up old temp files tempFileName = "1.jpg" tempFile = open(tempFileName, "w") tempFile.write(rec[0]) tempFile.close() cur.close() print "Content-type: text/html\n\n" print """" """ if __name__ == '__main__': main() Traceback (most recent call last): File "./dispimage.py", line 39, in ? main() File "./dispimage.py", line 16, in main tempFile.write(rec[0]) TypeError: argument 1 must be string or read-only character buffer, not instance So, rec[0] is an instance, but an instance of what? Since I needed to use the PgSQL.PgBytea method on the image before inserting it into the database, do I need to use a similar method to undo what PgBytea did to it, or am I incorrectly writing this binary data? I tried PgSQL.PgUnQuoteBytea(rec[0]), but that didn't work. Can anyone show me the TypeError of my ways? Is there a good example somewhere that shows getting binary data out of a database? Thanks. From agriff at tin.it Fri Jun 17 19:11:46 2005 From: agriff at tin.it (Andrea Griffini) Date: Fri, 17 Jun 2005 23:11:46 GMT Subject: What is different with Python ? References: <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> <3hg08rFh2tr3U1@individual.net> <1119015358.155954.92430@g47g2000cwa.googlegroups.com> Message-ID: On 17 Jun 2005 06:35:58 -0700, "Michele Simionato" wrote: >Claudio Grondi: ... >>From my >>overall experience I infer, that it is not only possible >>but has sometimes even better chances for success, >>because one is not overloaded with the ballast of deep >>understanding which can not only be useful but also >>hinder from fast progress. > >FWIW, this is also my experience. Why hinder ? Andrea From steve at REMOVETHIScyber.com.au Mon Jun 27 07:25:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 27 Jun 2005 21:25:19 +1000 Subject: Favorite non-python language trick? References: <200506260559.18488.hancock@anansispaceworks.com> Message-ID: On Sun, 26 Jun 2005 23:22:00 -0500, Terry Hancock wrote: >> You need to differentiate >> a = b = 1 >> from >> a = b == 1 > > Okay, I see what you mean. I can't ever recall having needed the > second form, though. > > Of course, you could still do assignment like this: > > a, b = (1,)*2 > > But I guess that's not exactly elegant. ;-) In general that is not the same thing as a = b = obj. py> a, b = ([], []) py> a.append(1) py> b [] py> a = b = [] py> a.append(1) py> b [1] -- Steven. From renting at astron.nl Thu Jun 16 11:32:11 2005 From: renting at astron.nl (Adriaan Renting) Date: Thu, 16 Jun 2005 17:32:11 +0200 Subject: pty code from 2.3.4 not working in 2.3.5 Message-ID: I hope you might be able to help me, as I can't find the cause of my problem. My sysadmin has upgraded Python from 2.3.4 (SuSE 9.2) to 2.3.5 (from python.org) Now my code for running an external program no longer works. My code is largely based on pexcpect.py and quite complex, but the example below reproduces my problem: ------------------------------------------------- import os, select, pty pid, fd = pty.fork() fd_eof = 0 if pid == 0: os.execvp('ls',['ls']) else: while not fd_eof: ready = select.select([fd], [], [], 0.25) if fd in ready[0]: text = os.read(fd, 1024) if text == '': fd_eof = 1 else: print text ------------------------------------------------------------- In 2.3.4 this exits with an exception OSError: [Errno 5] Input/output error after showing the 'ls' output, in 2.3.5 this just keeps running indefinately. In my own code I handle the OSError by setting fd_eof=1, after the while I do some waitpid, but this is all irrelevant to the problem I think. pty.py doesn't seem to have changed from 2.3.4 to 2.3.5 Do you have any idea what the cause of my program no longer finishing can be, and what I am doing wrong? Thank you, Adriaan Renting. From oren.tirosh at gmail.com Mon Jun 20 14:43:28 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 20 Jun 2005 11:43:28 -0700 Subject: Python choice of database In-Reply-To: References: Message-ID: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Philippe C. Martin wrote: > Hi, > > I am looking for a stand-alone (not client/server) database solution for > Python. > > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K How about using the filesystem as a database? For the number of records you describe it may work surprisingly well. A bonus is that the database is easy to manage manually. One tricky point is updating: you probably want to create a temporary file and then use os.rename to replace a record in one atomic operation. For very short keys and record (e.g. email addresses) you can use symbolic links instead of files. The advantage is that you have a single system call (readlink) to retrieve the contents of a link. No need to open, read and close. This works only on posix systems, of course. The actual performance depends on your filesystem but on linux and BSDs I find that performance easily rivals that of berkeleydb and initialization time is much faster. This "database" also supports reliable concurrent access by multiple threads or processes. See http://www.tothink.com/python/linkdb Oren From http Tue Jun 28 15:08:58 2005 From: http (Paul Rubin) Date: 28 Jun 2005 12:08:58 -0700 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> Message-ID: <7x3br2z4c5.fsf@ruckus.brouhaha.com> Reinhold Birkenfeld writes: > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? How about the win32 shell extension that allows stuff like reading the registry? I'm not sure if that's the same as win32com.shell. From chinook.nr at tds.net Sat Jun 18 15:43:24 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 18 Jun 2005 15:43:24 -0400 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> Message-ID: <0001HW.BED9F19C000A4E1DF0284550@news.gmane.org> On Sat, 18 Jun 2005 14:00:35 -0400, Steven D'Aprano wrote (in article ): > On Sat, 18 Jun 2005 12:05:59 -0400, Peter Hansen wrote: > >> Furthermore, protecting you from someone else making money off a copy of >> your program is basically what licenses are for, and if you have noticed >> they don't protect even Microsoft (see, for example, entire governments >> like the Indonesian government, which has mass-pirated Microsoft >> software for a long time). > > Please call it what it is: copyright infringement, not piracy. Piracy > takes place in international waters, and involves one or more of theft, > murder, rape and kidnapping. Making an unauthorized copy of a piece of > software is not piracy, it is an infringement of a government-granted > monopoly. > > In any case, there is a powerful argument for wanna-be Microsofts to > turn a blind eye to copyright infringements. It worked for Microsoft and > almost every other successful software company. > > The biggest barrier to success for software developers is getting people > to even know your software exists. The second biggest barrier is > encouraging them to try your software. The third is getting them to keep > using your software once they've tried it. Actually collecting money from > them is at the bottom of the list -- you can't expect people to pay you > for using your software if they don't even know you exist. > > Apart from the occasional public rant (such as Bill Gates' plea to users > not to make illegal copies of MS BASIC), in the early days Microsoft > didn't go out of their way to chase copyright infringers. If they had, the > users would have simply stopped using the MS software and used something > else. Instead, people grabbed copies of Word or Excel from their friends, > taking market share from WordPerfect, WordStar, Lotus etc. Eventually, > they would need an upgrade, or find it more convenient to buy than to > copy. Every so-called "pirated copy" had (at least) four benefits to > Microsoft: it denied a sale to Microsoft's competitors; it increased > users' familiarity and confidence with Microsoft's products; it built > Microsoft's brand recognition among software purchasers and IT > departments; and it was (usually) a future sale to Microsoft. > > It was only as Microsoft approached monopoly status that copyright > infringement began to hurt them more than it gained them. With few if any > competitors, the loss of revenue from unauthorized copies of Word or Excel > or Windows became greater than the benefits. > > Steven, Your weigh-in on semantics is misleading, but your elaboration of the aspect is very well put. As to semantics, piracy is to the originator what freedom fighter is to those that perceive themselves as oppressed. On the other hand, your elaboration is a very good example of the altered consciousness of human nature. That is, the acceptance of shades of complicity divorced from shades of guilt. Of course, one can see (if they so chose) many more obvious examples in business, let alone government and religion :~) Lee C From P.Schnizer at nospam.gsi.de Thu Jun 2 05:15:46 2005 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 02 Jun 2005 11:15:46 +0200 Subject: wxpython or PyQT to make a simulink clone ? References: <1117699017.376196.37930@f14g2000cwb.googlegroups.com> Message-ID: <873bs1xgot.fsf@smtp.gsi.de> cravephi at hotmail.com writes: > I would like to make a software like simulink: > http://www.mathworks.com/cmsimages/sl_mainpage_wl_7488.gif > > using python. > In order of bulding the interface (drag&drop block, link system between > the blocks, run the simulation, double click on a block to open its > properties, ...) which library will make my job easyer, PyQT or > WxPython ? > VIPER is perhaps the tool to look for http://www.scripps.edu/~sanner/python/viper/index.html Here the presentation at SciPy: http://www.scipy.org/documentation/Workshops/SciPy02presentations/sanner_viper.pdf There where some rumours that it will be released under some free License, but I never heared anything about that. I did myself a very simple visual interface based on some work of Matt Kimball. See http://truffaldino.sf.net Here I concentrated on all the stuff behind and on the simulation stuff. This uses wxPython for the graphical interface. That could be perhaps a starting point if you want to do something on your own. In my belief you would have to make it far more eyecandy ... Hope that helps a bit. Pierre -- Remove the nospam for direct reply From gsakkis at rutgers.edu Sun Jun 12 22:46:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jun 2005 19:46:50 -0700 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: <1118630810.633182.63450@f14g2000cwb.googlegroups.com> "Mike Meyer" wrote: > Andrea Griffini writes: > > On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen > > wrote: > > Also concrete->abstract shows a clear path; starting > > in the middle and looking both up (to higher > > abstractions) and down (to the implementation > > details) is IMO much more confusing. > > So you're arguing that a CS major should start by learning electronics > fundamentals, how gates work, and how to design hardware(*)? Because > that's what the concrete level *really* is. Start anywhere above that, > and you wind up needing to look both ways. This may sound as a rhetorical question, but in fact as an Informatics undergrad I had to take courses in electronics, logic design, signals and systems and other obscure courses as far CS is concerned (http://www2.di.uoa.gr/en/lessons.php). Although these are certainly useful if one is interested in hardware, architecture, realtime and embedded systems, etc., I hardly find them relevant (or even more, necessary) for most CS/IT careers. Separation of concerns works pretty well for most practical purposes. George From jrastrick at student.usyd.edu.au Tue Jun 28 07:01:04 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 28 Jun 2005 04:01:04 -0700 Subject: Boss wants me to program In-Reply-To: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: <1119956464.362328.290370@o13g2000cwo.googlegroups.com> The problem with all posts that say "Use Visual Basic, its easy for small programs" is that small programs, seemingly inevitably, become bigger programs (unless they become dead, unmaintained programs). If your users - you, your boss, coworkers, whoever - find your software useful, and you start to get even remotely enthusiastic for the project, then you'll find yourself extending and developing new features, as well as having to fix problems in your existing code. And while I'm personally no expert at language design, I've noticed it seems to be a pretty solid consensus among the actual experts that VB is one of the most atrociously designed mass market programming languages in existence. Fine for small programs, sure. But if you ever want to even think about doing bigger programs, or extending those useful smaller programs to do more, or even maintain and fix bugs in your existing code, then VB is not going to be your friend. The major traditional advantage of VB is that it integrates very smoothly and easily with Windows, and it has powerful and simple GUI building tools. However, Microsoft have essentially displaced VB from lone occupancy of this niche with .NET. And part of the point of .NET is that its not forcing you into one particular choice of language. So there's no advantage to be had from using Visual Basic; youre better off using a language that might give you some sort of insight into good programming practice, not to mention one that'll allow you to develop a serious application if you ever need to. Ultimately, if you want a current, supported version of VB, you have to use VB .NET anyway, and if you're going to use .NET, why use VB at all? If you have some C++ experience, C# is probably a good bet, as has been pointed out. You get all the advantages that VB used to provide, with far fewer of the drawbacks, and it'll stand you in good stead to learn Java. Theres even a version of Python for .NET, called IronPython. The major advantage of this is that you get to program in Python, which I can tell you from experience is a lot more enjoyable and pain-free than C, C++, Fortran, or Java (and, I would highly suspect, VB and C#). But apparently the available GUI builders aren't as good for Python - having not done a whole lot of GUI building in general, I'll leave this for more experienced people to judge. xeys_00 at yahoo.com wrote: > I'm a manager where I work(one of the cogs in a food service company). > The boss needed one of us to become the "tech guy", and part of that is > writing small windows programs for the office. He wants the development > work done in house, and he knows I am in school for a CS minor. I know > basic C++(Part 2 of that is in the fall), and I will be taking Java 1 > in the fall also. What is the easiest way for me to make windows > programs that will do basic things like(Inventory, Menu Management, > etc...)? I have heard visual basic is where it's at. I want to keep an > open mind though, so I am wondering if python could be an option. The > programs have > no speed requirement. But they must be pretty, and not confuse my > boss. Plus he wants well documented help for each function. I asked the > windows programming group, but I thought I would ask here also. Thanks. > > Xeys From cam.ac.uk at mh391.invalid Tue Jun 14 18:00:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 14 Jun 2005 23:00:37 +0100 Subject: Cause for using objects? In-Reply-To: References: Message-ID: John Heasly wrote: > Given: > [{"mugshot": "nw_gradspeaker4_0608", "width": 67.0, "height": 96.0}, \ > {"mugshot": "nw_gradspeaker2_0608", "width": 67.0, "height": 96.0}, \ > {"freehand": "b1.developreport.0614", "width": 154.0, "height": > 210.0}, \ > {"graphic": "bz_cafeparadiso_0613", "width": 493.0, "height": 341.0}] > > Return: > {"mugshot1": "nw_gradspeaker4_0608", "mugshot1.width": 67.0, > "mugshot1.height": 96.0,\ > "mugshot2": "nw_gradspeaker2_0608", "mugshot2.width": 67.0, > "mugshot2.height": 96.0, \ > "freehand1": "b1.developreport.0614", "freehand1.width": 154.0, > "freehand1.width": 210.0, \ > "graphic1": "bz_cafeparadiso_0613", "graphic1.width": 493.0, > "graphic1.height": 341.0} > > I'm trying to teach myself some OOP. Does grinding the Given above into > the Return seem like a good candidate? If that's all you're doing, and you must use that output format, then I'd say no. OOP is not a panacea. Now if you're going to *do* something with the return information, then I would say yes. But in that case, don't use a single dict as a return, use objects. -- Michael Hoffman From snail at objmedia.demon.co.uk Thu Jun 30 04:21:57 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Thu, 30 Jun 2005 09:21:57 +0100 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> <42BF6995.1050606@boonthavorn.com> <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> <0CuRDhE1HnwCFwl9@objmedia.demon.co.uk> Message-ID: In message , Markus Wankus writes >just think it is silly not to benefit from them. In which case you misunderstood me - I never said people should not use them, just that they should not be relied on for productivity improvements. They must factor in at a fraction of 1% of productivity. I don't really class improvements at that level as much to be shouted about :-) Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From philippe at philippecmartin.com Sun Jun 12 15:08:54 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sun, 12 Jun 2005 19:08:54 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42ABAB62.4040205@lexicon.net> Message-ID: Taking stuff for granted in unrelated to progress. I agree that the "trade" of software engineering evolves and that, thanks to hardware advances, we _usually_ can now "object orient" our software, add billions of abstraction layers, and consume memory without a second thought. But the trade evolves in the sense "sub"-trades are created, one person becomes a database experts while another will html all of his/her life (I personally find that sad). I'm being redundant here: The reason we can use Python and take many issues for granted is because some very skilled people handle the issues we find cumbersome. Roy Smith wrote: > The point I was trying to make was that as computer science progresses, > stuff that was really important to know a lot about becomes more and more > taken for granted. This is how we make progress. From duncan.booth at invalid.invalid Wed Jun 8 04:31:34 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 Jun 2005 08:31:34 GMT Subject: file permissions on windows XP (home) References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> <1118178009.923372.160210@g44g2000cwa.googlegroups.com> Message-ID: barney wrote: > I realise that theses are windows rather than python issues but I would > expect there would be some reliable way of changing the file > permissions from within python. I'm updating ID3 tags in MP3 file to > give some context. If I use something like winamp to make the change to > the ID3 tag then the file is updated with no permission errors so there > must be a way.... > So it looks as though you have been using cygwin to set the file's access permissions and cygwin uses a complex mapping of unix's permission bits onto file security, whereas Python uses the more common, but incomplete mapping as implemented by the C runtime library. The relationship between commands is that Python's chmod is equivalent to using the command line ATTRIB command, but Cygwin's chmod is equivalent to using both ATTRIB and CACLS. I can think of three options open to you: a) Let cygwin fix what cygwin broke: os.system('\\cygwin\\bin\\chmod u+rwx ' + filename) b) Use cacls to fix it: os.system('cacls %s /P %s:F' % (filename, username)) c) Use win32security.SetFileSecurity() See http://mail.python.org/pipermail/python-win32/2004-July/002111.html for a thread on using this api. From gsakkis at rutgers.edu Thu Jun 23 01:56:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 22 Jun 2005 22:56:08 -0700 Subject: Does a function like isset() exist in Python? References: Message-ID: <1119506168.356745.207790@g47g2000cwa.googlegroups.com> "Patrick Fitzsimmons" wrote: > Hi, > > I'm sure I should know this, but I can't find it in the manual. > > Is there a function in Python like the function in PHP isset()? It > should take a variable name and return True or False depending on > whether the variable is initialized. > > Thanks for any help, > Patrick There are no unitialized variables in python; if you try to access an undefined name, a NameError exception is raised: try: print "foo is", foo except NameError: print "foo is undefined" To undefine a defined name, use del: >>> foo=None >>> print foo None >>> del foo >>> print foo NameError: name 'foo' is not defined George From DaleWKing at insightbb.nospam.com Sun Jun 5 00:47:08 2005 From: DaleWKing at insightbb.nospam.com (Dale King) Date: Sun, 05 Jun 2005 04:47:08 GMT Subject: What are OOP's Jargons and Complexities? In-Reply-To: References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> Message-ID: Anno Siegel wrote: > Tassilo v. Parseval wrote in comp.lang.perl.misc: > >>Also sprach Dale King: >> >> >>>David Formosa (aka ? the Platypus) wrote: >>> >>>>On Tue, 24 May 2005 09:16:02 +0200, Tassilo v. Parseval >>>> wrote: >>>> >>>> >>>>>[...] I haven't yet come across a language that is both statically and >>>>>strongly typed, in the strictest sense of the words. I wonder whether >>>>>such a language would be usable at all. >>>> >>>> >>>>Modula2 claims to be both statically typed and strongly typed. And >>>>your wonder at its usablity is justified. >>> >>>I used a variant of Modula-2 and it was one of the best languages I have >>>ever used. That strong, static type checking was a very good thing. It >>>often took a lot of work to get the code to compile without error. >>>Usually those errors were the programmers fault for trying to play fast >>>and loose with data. But once you got it to compile it nearly always worked. >> >>I am only familiar with its successor Modula-3 which, as far as I >>understand, is Modula-2 with uppercased keywords and some OO-notion >>bolted onto it (I still recall 'BRANDED' references). >> >>I have to say that doing anything with this language was not exactly a >>delight. > > > I've been through Pascal, Modula2 and Oberon, and I agree. > > These languages had an axe to grind. They were designed (by Niklas > Wirth) at a time of a raging discussion whether structured programming > (goto-less programming, mostly) is practical. Their goal was to prove > that it is, and in doing so the restrictive aspects of the language > were probably a bit overdone. I fail to see how they were that different in terms of structured programming than C. The main benefit I was talking had more to do with types. It had types that were not compatible just because they had the same base type. For example you could have a type inches that was an integer and a type ounces that was also integral. Just because they were both integral did not make them type compatible. You couldn't just assign one to the other without you as the programmer explicitly saying that it was OK (by casting). In the environment I was programming in (engine controls for cars) where safety was a critical thing and a programming bug could kill people that safety was a very good thing. I think that also has a lot to do with why the government uses Ada. > In the short run they succeeded. For a number of years, languages of > that family were widely used, primarily in educational programming > but also in implementing large real-life systems. > > In the long run, the languages have mostly disappeared from the scene. I've posted before that hardly any language that has ever been somewhat popular has actually died (depending on your definition of that word). When asked for someone to name one once I got Simula for example (the forerunner of OO languages). Turns out that it continues to actually grow in popularity. > It has been discovered that "structured programming" is possible in > about any language. It turns out that programmers prefer the > self-discipline it takes to do that in a liberal language over the > enforced discipline exerted by Papa Pascal and his successors. There are lots of reasons they have not taken over, although Ada is still in wide use. It seems to me that too many people like playing with dangerous power tools without the guards in place. -- Dale King From d at e.f Fri Jun 24 10:57:30 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 09:57:30 -0500 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: Dave Brueck wrote: > Please keep the discussion civil; please help keep c.l.py a nice place > to visit. You didn't see Peter Hansen's previous post to which I made my reply, so I'd like to extend your recommendation to *everyone* here. Peter Hansen wrote: > Doug, please stop making an idiot of yourself ...[snipped more flames] From Scott.Daniels at Acm.Org Wed Jun 22 13:51:05 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Jun 2005 10:51:05 -0700 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <42b99da2$1@nntp0.pdx.net> Magnus Lycka wrote: > In some cases, "==" and "is" happens to give the same result. > >>> a = 1 > >>> b = 1 > >>> a == b > 1 > >>> a is b > 1 > > But often not. > > >>> c = 123456789 > >>> d = 123456789 > >>> c == d > 1 > >>> c is d > 0 > ... > First of all, a lot of Python values except 1 (a.k.a. True) > are logically true in a Python expression.... Actually, True and 1 are interesting examples. >>> a, b = 1, True >>> a == b True >>> a is b False I suspect you simply forgot this fact. --Scott David Daniels Scott.Daniels at Acm.Org From petr at tpc.cz Thu Jun 16 19:02:49 2005 From: petr at tpc.cz (McBooCzech) Date: 16 Jun 2005 16:02:49 -0700 Subject: New WYSIWYG Python IDE in the works References: Message-ID: <1118962969.649951.152730@g14g2000cwa.googlegroups.com> sorry for bothering you with my comment. From my point of view, the situation on the IDE (GUI??) development field for Python is really strange. Just try to imagine the same situation around the Python. Plenty of different approaches, versions, philosophies etc. Why people they really know the ways how to develop really good, prime and functional SW (I mean different developers of IDEs) do not do it together as a team (like in Python)? It is really strange to me? May be I am missing something (I am a Python newbie), but the way to the Eric3 was really painful to me. Petr From jan.danielsson at gmail.com Wed Jun 29 16:24:18 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 29 Jun 2005 22:24:18 +0200 Subject: Graphs/statistics using wxPython In-Reply-To: References: <42c2df8b$1@griseus.its.uu.se> <42c2e859$1@griseus.its.uu.se> <42c2f21a$1@griseus.its.uu.se> Message-ID: <42c3021f$1@griseus.its.uu.se> Robert Kern wrote: >> [---] >> >>> It's okay. Just about every Pythonista in the sciences has, at one time >>> or another, started a plotting library. It's a rite of passage. Welcome >>> to the club. :-) >> >> >> Question: I need to install SciPy in order to use matplotlib, > > No you don't. Ah.. I misread. I read http://matplotlib.sourceforge.net/installing.html, the section which describes what "enthought python" contains, and thought it meant "this is relevant to matplot lib". >> but on >> the download page I see that there are versions for Python 2.2.x and >> 2.3.x. I use 2.4.1 -- will bad things happen if I try to use the build >> for 2.3.x? > > Yes. Scipy has many extension modules; such modules built for 2.3.x > won't work for 2.4.x, etc. So, for future reference: I should *never* mix x and y versions in verion: x.y.z. I've wondered why there are versions of libraries for different versions of Python.. From rrr at ronadam.com Mon Jun 13 20:00:39 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 14 Jun 2005 00:00:39 GMT Subject: "also" to balance "else" ? Message-ID: There seems to be a fair amount of discussion concerning flow control enhancements lately. with, do and dowhile, case, etc... So here's my flow control suggestion. ;-) It occurred to me (a few weeks ago while trying to find the best way to form a if-elif-else block, that on a very general level, an 'also' statement might be useful. So I was wondering what others would think of it. 'also' would be the opposite of 'else' in meaning. And in the case of a for-else... would correct what I believe to be an inconsistency. Currently the else block in a for loop gets executed if the loop is completed, which seems backwards to me. I would expect the else to complete if the loop was broken out of. That seems more constant with if's else block executing when if's condition is false. 'also' would work like this. for x in : BLOCK1 if : break # do else block also: BLOCK2 else: BLOCK3 where the also block is executed if the loop completes (as the current else does), and the else block is executed if it doesn't. while : BLOCK1 if : break # jump to else also: BLOCK2 else: BLOCK3 Here if the while loop ends at the while , the BLOCK2 executes, or if the break is executed, BLOCK3 executes. In and if statement... if : BLOCK1 elif : BLOCK2 elif : BLOCK3 also: BLOCK4 else: BLOCK5 Here, the also block would execute if any previous condition is true, else the else block would execute. And 'tentatively', there is the possible 'alif', (also-if), to be used this way. if : BLOCK1 alif : BLOCK2 break # skip to also block alif : BLOCK3 alif : BLOCK4 also: # at lease one condition was true BLOCK5 else: # no conditions evaluated as true BLOCK6 Where only one elif will ever evaluate as true, any or all 'alif's could evaluate as true. This works similar to some case statements except all alif conditions may be evaluated. Not a true case statement, but a good replacement where speed isn't the main concern? I'm not sure if 'elif's and 'alif's could or should be used together? Maybe a precedence rule would be needed. Or simple that all also's and alif's must precede any elif's. Then again maybe alif's between elif's could be useful? For example the alif could be and 'elif' instead, so the break above would't be needed. 'also' can be used without the else in the above examples, and of course the 'else' doesn't need an 'also'. I think this gives Pythons general flow control some nice symmetrical and consistent characteristics that seem very appealing to me. Anyone agree? Any reason why this would be a bad idea? Is there an equivalent to an also in any other language? (I haven't seen it before.) Changing the for-else is probably a problem... This might be a 3.0 wish list item because of that. Is alif too simular to elif? On the plus side, I think this contributes to the pseudocode character of Python very well. Cheers, Ron From devlai at gmail.com Sun Jun 26 02:40:26 2005 From: devlai at gmail.com (Devan L) Date: 25 Jun 2005 23:40:26 -0700 Subject: noob question In-Reply-To: References: Message-ID: <1119768026.153694.164550@g44g2000cwa.googlegroups.com> To recognize variables that you have assigned, just look for assignment. If your code is readible, and you know it well, you shouldn't need the $ sign in front of everything. From onurb at xiludom.gro Fri Jun 17 11:07:55 2005 From: onurb at xiludom.gro (bruno modulix) Date: Fri, 17 Jun 2005 17:07:55 +0200 Subject: Back to the future - python to C++ advice wanted In-Reply-To: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> References: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> Message-ID: <42b2e74d$0$8916$636a15ce@news.free.fr> George Sakkis wrote: > During the last 18 months or so I have indulged in the joy of learning > and using python for almost everything, but I may have to go back to > C/C++ at work. (snip) > So, I wonder what have others who have gone the same path done and > learned in similar situations. How one can avoid the frustration of > having to work with a low level language once he has seen the Light ? > Well, I'm lucky enough to not to have to use C++ again, so I can't answer directly. But I think this might interest you: http://www.boost.org/ (NB : never tried it myself, but seems to be a nice job) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From greg_miller at nexpress.com Wed Jun 29 10:04:01 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 29 Jun 2005 07:04:01 -0700 Subject: COM problem .py versus .exe In-Reply-To: References: Message-ID: <1120053841.209150.69670@g43g2000cwa.googlegroups.com> I didn't see the earlier post, thanks for the resend. The firefighting is just about over, I have to find the machine owner to get permission to try the code. Then back to the dll version battle. If I can keep away from dealing with the ctypes code I will. I'll see how this works for me. Thanks again. From idontneednostinkinid at yahoo.com Wed Jun 1 18:37:01 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 15:37:01 -0700 Subject: any macro-like construct/technique/trick? Message-ID: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Is there a way to mimic the behaviour of C/C++'s preprocessor for macros? The problem: a lot of code like this: def foo(): # .... do some stuff if debug: emit_dbg_obj(DbgObjFoo(a,b,c)) # .... do more stuff if debug: emit_dbg_obj(DbgObjBar(d,e)) # ... and so on ... Notes: * the two-lines of debug conditional tend to really break up the flow of the surrounding code * in C you could wrap them with a macro so you could do DEBUG_EMIT(DbgObjFoo(a,b,c)), etc, with the macro only instantiating the object and processing it if the debug flag was set. The one-liner is MUCH less disruptive visually when reading code * using def debug_emit(obj): if debug: emit_dbg_obj(obj) is a poor solution, because it *always* instantiates DbgObj*, even when not needed; I want to avoid such unnecessary waste From jstroud at mbi.ucla.edu Mon Jun 20 20:09:39 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 20 Jun 2005 17:09:39 -0700 Subject: Tuple Unpacking in raise Message-ID: <200506201709.39961.jstroud@mbi.ucla.edu> Hello All, Is this a bug? Why is this tuple getting unpacked by raise? Am I missing some subtle logic? Why does print not work the same way as raise? Both are statements. Why does raise need to be so special? py> sometup = 1,2 py> print sometup (1, 2) py> print 1,2,3, sometup 1 2 3 (1, 2) py> class MyErr(Exception): ... def __init__(self, atup): ... Exception.__init__(self, "Error with %s-%s" % atup) ... py> raise MyErr, sometup Traceback (most recent call last): File "", line 1, in ? TypeError: __init__() takes exactly 2 arguments (3 given) py> e = MyErr(sometup) py> print e Error with 1-2 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From anonymousnerd at gmail.com Sat Jun 25 02:29:51 2005 From: anonymousnerd at gmail.com (anonymousnerd at gmail.com) Date: 24 Jun 2005 23:29:51 -0700 Subject: How does one write a function that increments a number? In-Reply-To: References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> Message-ID: <1119680991.148977.98000@o13g2000cwo.googlegroups.com> Thank you all for your helpful replies. Regards, Vaibhav From tim.golden at viacom-outdoor.co.uk Thu Jun 23 08:32:08 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Jun 2005 13:32:08 +0100 Subject: os.system(cmd) isn't working Message-ID: <9A28C052FF32734DACB0A288A3533991EBB92B@vogbs009.gb.vo.local> [Michael P. Soulier] | On 23/06/05 Tim Golden said: | | > This is only half an answer, but I personally find faffing | > about with the double-quote / double-backslash stuff between | > Python and Windows a pain in the neck, so where I can I avoid it. | | Indeed. I believe this is why Python has os.sep. | | Mike Well, true, but if you were trying to enter a particular file path as the OP was (c:\program files\ etc.) would you really want to have "c:" + os.sep + "program files"... or os.path.join ("c:", "program files"...)? And where do the double-quotes go etc? I'm not saying all these things aren't possible; my only point is that rather than try to remember / work it out, I generally try to avoid the issue. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From newsgroups at jhrothjr.com Tue Jun 14 09:05:30 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 14 Jun 2005 07:05:30 -0600 Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: <11atlh1a4htth78@news.supernews.com> "Andrew Dalke" wrote in message news:pan.2005.06.14.07.20.19.532887 at dalkescientific.com... > Ron Adam wrote: >> True, but I think this is considerably less clear. The current for-else >> is IMHO is reversed to how the else is used in an if statement. > > As someone else pointed out, that problem could be resolved in > some Python variant by using a different name, like "at end". > Too late for anything before P3K. I don't think it has to wait. There seems to be a movement toward putting new things in the next couple of releases, and then waiting until 3.0 to remove the old way of doing things. So "at end" or "on normal exit" could be put in any time; the use of "else" in that context wouldn't go away until 3.0. The real question is whether it's worth doing at all. I consider it a fairly minor issue, all told. John Roth > > > Andrew > dalke at dalkescientific.com > From hongqn at gmail.com Tue Jun 14 05:40:19 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Tue, 14 Jun 2005 17:40:19 +0800 Subject: collect data using threads Message-ID: <42AEA603.5030903@gmail.com> A class Collector, it spawns several threads to read from serial port. Collector.get_data() will get all the data they have read since last call. Who can tell me whether my implementation correct? class Collector(object): def __init__(self): self.data = [] spawn_work_bees(callback=self.on_received) def on_received(self, a_piece_of_data): """This callback is executed in work bee threads!""" self.data.append(a_piece_of_data) def get_data(self): x = self.data self.data = [] return x I am not very sure about the get_data() method. Will it cause data lose if there is a thread is appending data to self.data at the same time? Is there a more pythonic/standard recipe to collect thread data? -- Qiangning Hong _______________________________________________ < Those who can, do; those who can't, simulate. > ----------------------------------------------- \ ___-------___ \ _-~~ ~~-_ \ _-~ /~-_ /^\__/^\ /~ \ / \ /| O|| O| / \_______________/ \ | |___||__| / / \ \ | \ / / \ \ | (_______) /______/ \_________ \ | / / \ / \ \ \^\\ \ / \ / \ || \______________/ _-_ //\__// \ ||------_-~~-_ ------------- \ --/~ ~\ || __/ ~-----||====/~ |==================| |/~~~~~ (_(__/ ./ / \_\ \. (_(___/ \_____)_) From rkern at ucsd.edu Wed Jun 29 14:13:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 29 Jun 2005 11:13:36 -0700 Subject: Graphs/statistics using wxPython In-Reply-To: <42c2df8b$1@griseus.its.uu.se> References: <42c2df8b$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Hello all, > > I wanted to plot some statistics, so I wrote a simple wxPython class > to do it. Then I realized that I would like to draw bar graphs, so I > added that too. > > Since I'm a complete Python newbie, I haven't done much of it the > "Python way", I suspect. So, I'm wondering if someone would like to show > me some of the tricks I should have used. Trick #1: import matplotlib ;-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From flyingfred0 at gmail.com Thu Jun 9 22:25:34 2005 From: flyingfred0 at gmail.com (flyingfred0) Date: Fri, 10 Jun 2005 02:25:34 GMT Subject: Embedding: many interpreters OR one interpreter with many thread states ? In-Reply-To: <3gppn9FdnnldU1@individual.net> References: <1118239578.831376.218370@o13g2000cwo.googlegroups.com> <3gppn9FdnnldU1@individual.net> Message-ID: Of course, with multiple threads in one process, it's important to know about the dreaded global interpreter lock (GIL) -- http://docs.python.org/api/threads.html With one instance of the interpreter, only one Python thread will be running at a time, no matter how many CPUs you have in the system. Greg Ewing wrote: > adsheehan at eircom.net wrote: > >> - creating many sub-interpreters (Py_NewInterpreter) with a thread >> state each >> >> Or >> >> - creating one interpreter with many thread states (PyThreadState_New) > > > My understanding is that using multiple interpeters isn't > really supported properly, despite there being apparent > support in the API. So I suggest using a single interpeter > with multiple threads. > From gsakkis at rutgers.edu Sun Jun 26 22:16:59 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 26 Jun 2005 19:16:59 -0700 Subject: unittest: collecting tests from many modules? References: Message-ID: <1119838619.250043.85750@g44g2000cwa.googlegroups.com> "Robert Brewer" wrote: > Anyway, use normal os.walk() calls to gather the files which start with > "test_"; then use the TestLoader.loadTestsFromName method to instruct > unittest to test them as a group. Hi Robert, this makes much more sense; os.walk and TestLoader.loadTestsFromName improve the readability of the code significantly. I rewrote almost from scratch my test script (http://rafb.net/paste/results/ekTqAV72.html) and it works fine, with one exception: it fails on test files that run unittest.main() with non-empty argument list. In my case, some tests define a suite as defaultTest in unittest.main. The easiest (if not the only) way to run the unittest with the specified arguments is through execfile() (after messing with sys.modules to rebind __main__ for each file). By the way, there would be no need for me specifying a defaultTest if unittest.main() was looking also for TestSuites in addition to TestCases within each module. Is this a design choice ? Regards, George From cdkrug at worldnet.att.net Mon Jun 20 13:17:18 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Mon, 20 Jun 2005 17:17:18 GMT Subject: Couple functions I need, assuming they exist? References: Message-ID: On 20 Jun 2005 15:51:07 GMT, Duncan Booth wrote: > Peter Hansen wrote: > >>> The target of the problems (my daughter) would prefer that the thousands >>> be delimited. Is there a string function that does this? >> >> You refer to something like putting a comma between groups of three >> digits, as in 1,000? This is locale-specific, and there's a "locale" >> module that should have what you need. > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, '') > 'English_United Kingdom.1252' >>>> print locale.format("%d", 1000000, True) > 1,000,000 Perfect! Thanks. Sometimes "hard part" is figuring out which package already does the thing I need done. Charles. From fumanchu at amor.org Sun Jun 26 17:59:47 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 26 Jun 2005 14:59:47 -0700 Subject: unittest: collecting tests from many modules? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E37724BC@exchange.hqamor.amorhq.net> "Jorgen Grahn" wrote: > I have a set of tests in different modules: test_foo.py, > test_bar.py and so on. All of these use the simplest > possible internal layout: a number of classes containing > test*() methods, and the good old lines at the end: > >> > >> if __name__ == "__main__": > >> unittest.main() > >> > This is great, because each of the modules are runnable, > and I can select classes or tests to run on the commandline > if I want to. However, running all the tests from e.g. > a Makefile is not that fun; I don't get a single pass/fail > summary across the modules. > > What's the best way of creating a test.py which > - aggregates the tests from all the test_*.py modules? > - doesn't require me to enumerate all the test classes in test.py > (forcing each module to define test_foo.theSuite or > someting would be OK though) > - retains the ability to select tests and verbosity (-q, > -v) from the > command line? I missed the first post somehow; hope this gets in the conversation in the right place. Anyway, use normal os.walk() calls to gather the files which start with "test_"; then use the TestLoader.loadTestsFromName method to instruct unittest to test them as a group. If you want a working example, see the CherryPy test loader at: http://www.cherrypy.org/file/trunk/cherrypy/test/test.py (In that example, I overrode loadTestsFromName in a subclass, in order to be less verbose in exactly the way I wanted, but the default works just as well). Robert Brewer System Architect Amor Ministries fumanchu at amor.org From Scott.Daniels at Acm.Org Tue Jun 14 10:15:46 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 14 Jun 2005 07:15:46 -0700 Subject: Going crazy... In-Reply-To: <42aed582$1@griseus.its.uu.se> References: <42ae2729$1@griseus.its.uu.se> <42aed582$1@griseus.its.uu.se> Message-ID: <42aedf66$1@nntp0.pdx.net> Jan Danielsson wrote: > Gary Herron wrote: >>... a more recent addition to the language is Sets, ... >>>>>from sets import Set >>>>>Set([1,2,3,4,5,6]) - Set([2,3,6]) >> >>Set([1, 4, 5]) If you are using 2.4 or later, you can simply use "set" without importing anything. set(['apple', 'orange', 5]) - set([5]) --Scott David Daniels Scott.Daniels at Acm.Org From adurdin at gmail.com Tue Jun 28 20:40:18 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 29 Jun 2005 10:40:18 +1000 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <59e9fd3a05062817404d438b73@mail.gmail.com> On 6/29/05, Rocco Moretti wrote: > > Sorry, thought of one more thing Python has going for it vs. Forth - > reference material. Check the catalog of your local library. I'd guess > that there is more choice for Python programming books vs. Forth > programming books. I just checked, and you're quite right: the State Library of Tasmania has only one Forth book -- but it has two Python books (Python Essential Reference and Python Pocket Reference). Not that the local booksellers are any better -- I've only found one place that had anything better than the dreadful "Teach yourself Python in 24 hours", and since I bought Python in a Nutshell from them a year ago, they've not got any more in stock. Thank goodness for Amazon, especially as it's cheaper to order from Amazon than to get the bookstore to order a book in for me... From chinook.nr at tds.net Tue Jun 28 07:49:17 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 07:49:17 -0400 Subject: OO refactoring trial ?? References: <0001HW.BEE6AC5F00035045F0407550@news.gmane.org> Message-ID: <0001HW.BEE6B17D00048355F0407550@news.gmane.org> On Tue, 28 Jun 2005 07:31:43 -0400, Chinook wrote (in article <0001HW.BEE6AC5F00035045F0407550 at news.gmane.org>): > [[ This message was both posted and mailed: see > the 'To' and 'Newsgroups' headers for details. ]] > Sorry for the duplication. I'm trying Hogwasher on OS X and it seems I better look around some more. From timh at zute.net Mon Jun 20 08:54:45 2005 From: timh at zute.net (Tim Hoffman) Date: Mon, 20 Jun 2005 20:54:45 +0800 Subject: Using print with format to stdout generates unwanted space In-Reply-To: <3hmt4rFhnn89U1@individual.net> References: <3hmt4rFhnn89U1@individual.net> Message-ID: <42b6bc99@news.highway1.com.au> Hi Paul Based on your description of what you want to do, print is probably not the correct method of controlling output format. You should use write() method of the file handle to get unadulterated output. print is working as documented . From the Python 2.3 documentation, Section 6.6 The Print statement. "print evaluates each expression in turn and writes the resulting object to standard output (see below). If an object is not a string, it is first converted to a string using the rules for string conversions. The (resulting or original) string is then written. A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is "\n", or (3) when the last write operation on standard output was not a print statement." As you can see a space char is written and is correct as per the docs. Rgds Tim Paul Watson wrote: > #!/usr/bin/env python > > # Using a print statement to stdout results in an > # unwanted space character being generated at the > # end of each print output. Same results on > # DOS/Windows and AIX. > # > # I need precise control over the bytes that are > # produced. Why is print doing this? > # > import sys > > # If this is a DOS/Windows platform, then put stdout > # into binary mode so that only the UNIX compatible newline > # will be generated. > # > try: > import msvcrt, os > msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) > except: > print 'This is not an msvcrt platform.' > pass > > # Using print with newline suppressed generates a space at the > # end of each print statement. > # > for i in range(3): > print '%d,60,' % (i), > for j in range(10): > print '%d,' % (j), > print '' > > # Using a list and doing a join does not result in the space > # character being generated. > # > for i in range(3): > alist = [] > alist.append('%d,60,' % (i)) > for j in range(10): > alist.append('%d,' % (j)) > print ''.join(alist) > > sys.exit(0) > > From grante at visi.com Thu Jun 9 17:30:29 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 09 Jun 2005 21:30:29 -0000 Subject: A question about time References: <42a8ac25@griseus.its.uu.se> <11ahc8fntjhiad5@corp.supernews.com> Message-ID: <11ahd7lscvf9b23@corp.supernews.com> On 2005-06-09, Grant Edwards wrote: > On 2005-06-09, Jan Danielsson wrote: > >> In C, I would do this: >> >> server.invalidUntil = time(NULL) + 5*60; // five minute delay > > In Python, I would do this: > > server.invalidUntil = time.time() + 5*60 # five minute delay > >> ..and the check: >> >> if(time(NULL) > server.invalidUtil) >> { >> // use server >> } > > if time() > server.invalidUntil: > # user server Um, that should have been if time.time() > server.invalidUntil: # use server >> So the whole thing very simple... > > Yup. Not quite simple enough that I could get it right the first time. -- Grant Edwards grante Yow! I need to discuss at BUY-BACK PROVISIONS visi.com with at least six studio SLEAZEBALLS!! From jarrod.roberson at gmail.com Sat Jun 11 00:49:55 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 10 Jun 2005 21:49:55 -0700 Subject: Dealing with marketing types... In-Reply-To: References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <1118465395.191165.21950@f14g2000cwb.googlegroups.com> i think he was actually referering the the architecture astronauts that Joel Spolskyl was talking about From Holger.Joukl at LBBW.de Thu Jun 9 08:00:38 2005 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Thu, 9 Jun 2005 14:00:38 +0200 Subject: XML + SOAP + Webservices In-Reply-To: <30081171.1118317763136.JavaMail.tbone@ssmg102> Message-ID: Hi there, just about now I?ve started to write a little howto for the first steps with a python ZSI-based webservice to be consumed from C++ clients (gSOAP) and an Excel XP spreadsheet. More or less I am just documenting what I did, and I am by no means an expert on the subject, but still...might be helpful to you. I can probably post the first part this afternoon or tomorrow morning (will not be finished by then). Meanwhile, you might also want to check out the pywebsvcs mailing list on sourceforge. Cheers, H. Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From sergey at fidoman.ru Sat Jun 18 18:23:14 2005 From: sergey at fidoman.ru (Sergey Dorofeev) Date: Sun, 19 Jun 2005 02:23:14 +0400 Subject: struct.(un)pack and ASCIIZ strrings Message-ID: I can use string.unpack if string in struct uses fixed amount of bytes. But is there some extension to struct modue, which allows to unpack zero-terminated string, size of which is unknown? E.g. such struct: long, long, some bytes (string), zero, short, short, short. From renato.ramonda at gmail.com Thu Jun 9 18:01:27 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Fri, 10 Jun 2005 00:01:27 +0200 Subject: Fast text display? In-Reply-To: References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> <7xll5ka7mv.fsf@ruckus.brouhaha.com> Message-ID: Riccardo Galli ha scritto: > GUI cross platform need external support, in a OS or in another. Sure, but using win32 versions of gtk and glade plus py2exe and InnoSetup (if you want to build a fancy installer) will give you a self contained gui program in windows. Big, sure, but self contained :-D -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From devlai at gmail.com Thu Jun 30 23:14:39 2005 From: devlai at gmail.com (Devan L) Date: 30 Jun 2005 20:14:39 -0700 Subject: Escaping commas within parens in CSV parsing? In-Reply-To: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> Message-ID: <1120187679.811723.242530@g47g2000cwa.googlegroups.com> Try this. re.findall(r'(.+? \(.+?\))(?:,|$)',yourtexthere) From k04jg02 at kzoo.edu Sat Jun 18 20:57:12 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Sat, 18 Jun 2005 18:57:12 -0600 Subject: Loop until condition is true In-Reply-To: References: <1119074614.700809@yasure> Message-ID: <42B4C2E8.4080805@kzoo.edu> Peter Otten wrote: >I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for >(" in the Python 2.4 source, so using these rough estimates do-while still >qualifies as "rarely used". > >Peter > > > That's 136 times you'd have to use an ugly hack instead. I definitely wouldn't mind an until or do/while. From ken.miller at entouch.net Wed Jun 8 02:35:15 2005 From: ken.miller at entouch.net (Kenneth Miller) Date: Wed, 08 Jun 2005 01:35:15 -0500 Subject: Matplotlib w/ TK Backend. Message-ID: Hello All, I need a python module to do real time graphs so I chose Matplotlib. I am trying to compile matplotlib at the moment and I have some problems, well not really. It compiles fine, it's how it compiles that's the problem. I am attempting to build it with the Tkinter backend as opposed to the GTK+ backend. Whenever I build, install, and then try to import I receive an error stating that my version of PyGTK needs to be updated. Logically it shouldnt be looking for PyGTK if it is using the TKinter backend? Any help would be appreciated. Regards, Kenneth Miller From guy.lateurNNOOSSPPAAMM at pandora.be Tue Jun 14 17:15:29 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Tue, 14 Jun 2005 21:15:29 GMT Subject: Where is Word? References: Message-ID: Thanks for all the feedback, everyone. What a helpfull community this is! It's actually kinda hard keeping up with y'all.. Cheers, g "Guy Lateur" schreef in bericht news:uFxre.120359$sR7.6729742 at phobos.telenet-ops.be... > Hi all, > > I need a way to get the path where MS Word/Office has been installed. I > need to start Word from a script (see earlier post), but it doesn't work > if I don't know its path. So "os.system("winword.exe %s" % fileName)" > doesn't always work; I need to say "os.system("C:\Program Files\Microsoft > Office\Office10\winword.exe %s" % fileName)". > > Any ideas? > > TIA, > g > From fperez.net at gmail.com Wed Jun 1 21:30:43 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 01 Jun 2005 19:30:43 -0600 Subject: plotting with Python References: <429aeac6$1@news.fhg.de> Message-ID: Rolf Wester wrote: > Hi, > > I have a Python console application that is intended to be used > interactively and I have to add plotting capabilities (multiple XY plots > and if possible 2D-surface plots). I'm loocking for a reasonably fast > plotting library (not GPL'ed, needs not be for free) that can be used > under Windows. An alternative would also be a standalone application > that can be controlled via TCP/IP from my Python application. I tried > matplotlib but this is not fast enough (especially under Windows). I > considered PyQwt but this is GPL'ed. So I would be very appreciative for > any help. Have a look at matplotib, which provides already embeddable widgets for most common toolkits. It lacks surface plotting, for which VTK/mayavi can come in handy. If you want interactive console support, IPython can be embedded/extended, and it handles automatically thread coordination with matplotlib with Tk, GTK, WX and Qt (windows, linux and osx). Both come with a BSD license. Regards, f From none at no.chance Wed Jun 29 14:43:44 2005 From: none at no.chance (Peter Tillotson) Date: Wed, 29 Jun 2005 18:43:44 +0000 Subject: importing packages from a zip file In-Reply-To: References: Message-ID: solution: have to add the zip archives to the PYTHONPATH, can be done in the env but also as below import sys, os.path zipPackages=['base.zip'] for package in zipPackages: sys.path.insert(0,os.path.join(sys.path[0],package)) import base.branch1.myModule Peter Tillotson wrote: > Hi all, > > I was wondering if this is possible. In python v2.3 the import systems > was extended via PEP302 to cope with packages. *.py files in a directory > hierarchy can be imported as modules each level in the directory > hierarchy needs to contain at least an empty __init__.py file. > > eg. With the file system > > base/ > __init__.py > branch1/ > __init__.py > myModule.py > > I can import myModule as follows > > import base.branch1.myModule > > At the same time its possible to store modules in a flat zip-file and > import modules with the following. > > from myZip.zip import myModule.py > > but is there a way to do both at the same time? eg. > > from myZip.zip import base.branch1.myModule > > I'm interested in this in the development of mobile code for some Grid > applications :-) > > thanks in advance > > p From t-meyer at ihug.co.nz Sun Jun 12 22:20:00 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 13 Jun 2005 14:20:00 +1200 Subject: inactive Spambayes w/ Outlook In-Reply-To: Message-ID: > I had installed spambayes with outlook 2003 a while ago and > it worked great. Then I did who know what it stopped working. If Peter's link doesn't help, I suggest you try the spambayes mailing list: =Tony.Meyer From tim.golden at viacom-outdoor.co.uk Mon Jun 27 04:39:15 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 27 Jun 2005 09:39:15 +0100 Subject: Using MSMQ on Windows (and Navision) Message-ID: <9A28C052FF32734DACB0A288A3533991EBB935@vogbs009.gb.vo.local> [Andrew Gordon] | | I'm investigating getting Microsoft Navision to do stuff from | a Python script. [... snip ...] No help here, I'm afraid. | 2) Every character in the body of messages sent from send.py has a 0 | value character after them (ie in hex 48 00 65 00 6C 00 6C 00 | 6F 00 20 | 00 57 00 00 6F 00 72 00 6C 00 64 00 21 00) That looks to me like Hello World! in utf16. Quick test: # # Removed what looks like a spurious double zero after the 57 # original = "48 00 65 00 6C 00 6C 00 6F 00 20 00 57 00 6F 00 72 00 6C 00 64 00 21 00" as_numbers = [int (i, 16) for i in original.split ()] as_string = "".join ([chr (i) for i in as_numbers]) as_unicode = as_string.decode ("utf_16") # guess print as_unicode # # Sure enough, Hello World! # Not adding much, I know, but at least confirming your suspicions. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From mwm at mired.org Thu Jun 30 17:38:11 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 30 Jun 2005 17:38:11 -0400 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <86wtoba5ks.fsf@bhuda.mired.org> roy at panix.com (Roy Smith) writes: > There's a reprint this morning on slashdot of a 1984 review Byte did > on the brand-new Macintosh (executive summary: cool machine, needs > more memory). The first four software packages available for the new > machine? > > MacWrite/MacPaint (they seem to count this as one package) > Microsoft Multiplan > Microsoft BASIC > CSI MacForth > > No mention of Python :-( That's because the time machine doesn't work that far into the past. It's primary use is to retroactively fix bugs in Python, so the design spec only called for the ability to go back to the first public release of Python. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From li.qj at 126.com Wed Jun 1 20:50:47 2005 From: li.qj at 126.com (jerky) Date: Thu, 2 Jun 2005 08:50:47 +0800 Subject: Pressing A Webpage Button References: Message-ID: hi, urllib does not work when search from google.com, since google.com have some limitations to developer , you can get more details from www.google.com/apis/ "Elliot Temple" ??????:mailman.335.1117645705.18027.python-list at python.org... > How do I make Python press a button on a webpage? I looked at urllib, > but I only see how to open a URL with that. I searched google but no > luck. > > For example, google has a button how would i make a script to press that button? > > Just for fun, is there any way to do the equivalent of typing into a text > field like the google search field before hitting the button? (I don't > actually need to do this.) > > If someone could point me in the right direction it'd be appreciated. > > -- Elliot Temple > http://www.curi.us/ > > > --- > [This E-mail scanned for viruses by Declude Virus] > From dale_huffman at steris.com Fri Jun 3 13:35:37 2005 From: dale_huffman at steris.com (dale) Date: 3 Jun 2005 10:35:37 -0700 Subject: ANN: Cleveland Area Python Interest Group In-Reply-To: References: Message-ID: <1117820137.083469.313940@g49g2000cwa.googlegroups.com> Is the first meeting on June 6th, I only ask due to short notice. If so I'll be there. From sub1ime_uk at yahoo.com Fri Jun 24 12:19:08 2005 From: sub1ime_uk at yahoo.com (sub1ime_uk at yahoo.com) Date: 24 Jun 2005 09:19:08 -0700 Subject: Running Python scripts under W2K with I/O redirection Message-ID: <1119629947.977882.174830@g49g2000cwa.googlegroups.com> I apologise if this is a well known problem. I've searched and can't find a clear description or fix. Hope someone can help. I am running my Python scripts under Windows 2000 using Python 2.4 Build 243 from Activestate. If I want to specify a file as standard input to my script I can just enter a command like: H:\> pyscript.py file.inp and that's what I get. All ok so far. However if I enter commands like: H:\> type file.inp | pyscript.py or H:\> pyscript.py < file.inp It doesn't work. I've also tried the variant of parsing for a command line argument of '-' or 'filename' and then specifically either copying the sys.stdin file object or opening the file specified, then using that file object. Same problem. Interestingly enough, if I specify my commands as: H:\> type file.inp | python pyscript.py or H:\> python pyscript.py < file.inp It all works the (unix-like) way I wanted it to. This leads me to suspect there is something wrong in the way that Python is being invoked by Windows in my problem situation rather than an inherent fault within Python itself. Does anyone have any idea what the problem could be and how to fix it? I know its a really minor niggle but it'd make this poor deprived unix-guy-forced-into-windows-servitude very happy. Thanks, sub1ime_uk sub1ime_uk (at) yahoo (dot) com From max at alcyone.com Sat Jun 4 20:55:51 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 04 Jun 2005 17:55:51 -0700 Subject: method = Klass.othermethod considered PITA In-Reply-To: References: <87oeallp44.fsf@pobox.com> Message-ID: <6qmdnR7ry4wF0D_fRVn-hA@speakeasy.net> Steven Bethard wrote: > John J. Lee wrote: > >> It seems nice to do this >> >> class Klass: >> >> def _makeLoudNoise(self, *blah): >> ... >> >> woof = _makeLoudNoise > > Out of curiosity, why do you want to do this? There aren't too many clear use cases, but I've found it useful from time to time. Usually it comes in handy when you're specializing some predefined behavior, often when relying on introspection in some fashion. For instance, for a chat network bot framework, a certain form of bot will look for any attribute in its instance that starts with verb_ and a command and execute it when it hears it spoken: def verb_hello(self, convo): "Respond to a greeting." convo.respond(random.choice(self.greetings)) If you'd like it to respond to more than one word like this, then you only need to assign the additional verbs, rather than redefine them: verb_hi = verb_hello verb_yo = verb_hello verb_wazzup = verb_hello It actually does more than this, where a builtin help system (verb_help) which relies on the docstrings of the verb_... methods will allow you to get help on any defined verb automatically, and list the known verbs when supplied without arguments. But this would list duplicate verbs for the aliases (hi, yo, wazzup) above, which isn't optimal. So instead I have another prefix, alias_, which acts as a verb, but won't be automatically scanned as a verb when help is finding the list of valid verbs: alias_hi = verb_hello ... That way, you get maximum effectiveness for minimum clutter. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Things are as they are because they were as they were. -- Thomas Gold From nidoizo at yahoo.com Sun Jun 5 12:44:40 2005 From: nidoizo at yahoo.com (Nicolas Fleury) Date: Sun, 05 Jun 2005 12:44:40 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Steven Bethard wrote: > Can you do the same thing for your proposal? As I understand it you > want some sort of implicitly-defined BLOCK that starts the line after > the with statement and runs to the end of the current block... Yes. I totally agree with the syntax in the PEP, it provides a necessary feature. I'm just suggesting to make the indentation *optional*, because most of the time it is not necessary. > Do you think the benefit of less indentation outweighs the added > complexity of explaining the construct? I still can't think of a good > way of explaining the semantics you want. If you could provide an > explanation that's simple and as explicit as Guido's explanation in PEP > 343, I think that would help your case a lot. Since the current syntax would be there, the no-indentation syntax can be explained in terms of the indentation syntax: """ To avoid over-indentation, a with-statement can avoid defining a new indentation block. In that case, the end of the with block is the end of the current indentation block. with EXPR as VAR REST OF BLOCK is equivalent to with EXPR as VAR: BLOCK """ What do you think? I fail to see the complexity... > P.S. I think it's a great sign that people are mainly squabbling about > syntax here. More likely than not, Guido's already made his mind up > about the syntax. So, since no one seems to have any real problems with > the semantics, I'm hopeful that we'll get a direct implementation of PEP > 343 in the next Python release. =) It's important to note that nobody is against the PEP syntax. We are only talking about adding things to it (optional indentation, or multiple-as as with import). All these changes can also be made later, so no proposition should slow down the implementation of the PEP. Regards, Nicolas From Oyvind.Ostlund at cern.ch Mon Jun 27 05:10:09 2005 From: Oyvind.Ostlund at cern.ch (Oyvind Ostlund) Date: Mon, 27 Jun 2005 11:10:09 +0200 Subject: Downloading files using URLLib Message-ID: <9D1BA87B48D4F440A0D9E371471F45A53263AE@cernxchg21.cern.ch> Hello, I have to download a lot of files. And at the moment i am trying with URLLib. But sometimes it doesn't download the whole file. It looks like it stops half way through or something. Is it possible to ask for the file size before you download, and then test afterwards if the whole file was read? If so please guid me a bit here. Thanks - ?? - From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue Jun 14 09:21:20 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 14 Jun 2005 15:21:20 +0200 Subject: Show current ip on Linux In-Reply-To: References: Message-ID: <3h83ugFddjmuU1@news.dfncis.de> David Van Mosselbeen schrieb: > > Thanks for support. > I have read the refered page you show above. I try some piece of code that > im have copy and paste it into a blank file that i give the name > "ip_adress.py" to test it. > > > THE SOURCE CODE : > ----------------- > > import commands > > ifconfig = '/sbin/ifconfig' > # name of ethernet interface > iface = 'eth0' > # text just before inet address in ifconfig output > telltale = 'inet addr:' > > def my_addr(): > cmd = '%s %s' % (ifconfig, iface) > output = commands.getoutput(cmd) > > inet = output.find(telltale) > if inet >= 0: > start = inet + len(telltale) > end = output.find(' ', start) > addr = output[start:end] > else: > addr = '' > > return addr > # End python code > > But now, it's fine to have some piece of code but this wil not work on my > computer. I'm sure that y do somethings bad. > To run the python script on a Linux machine. How to proceed it ? > > 1) I have open a terminal > 2) then i type "python ip_adress.py" (to run the script) > > But nothings, i not view the current ip of my computer. > What happend ? > You have defined a function, but you never call this function. Running a script won't do anything, if this script consists only of function (or class) definitions. You can either - open the interactive python interpreter and type: import ip_adress ip_adress.my_addr() or, probably simpler, - add the following two lines to your script, after the definition of your function: if __name__ == '__main__': print my_addr() Then run your script just as you did before. Now you are calling the function and printing the value it returns. -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From sjmachin at lexicon.net Wed Jun 1 18:46:30 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 08:46:30 +1000 Subject: bug with isinstance() ? In-Reply-To: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> References: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> Message-ID: <429e3ac6@news.eftel.com> Mac wrote: > Under certain circumstances isinstance() seems to return incorrect > value for me. I'm using Python 2.3 (latest from Debian's unstable). > Here's a sample program... the multi-module nature of the code is key. Yes, it has the multi-module nature. What it needs, though, is the Buddha nature :-) > > > === test.py === > > class Foo: > pass 'print' and 'repr()' are your friends. Use them. Add this: print '*** Have just made class Foo:', repr(Foo) > > def test(): > from test2 import make_me_a_foo > foo = make_me_a_foo() Add these lines: print 'foo is an instance of', foo.__class__ print 'In test, Foo is', repr(Foo) > if isinstance(foo, Foo): > print "is a Foo" > else: > print "is NOT a Foo!" > > if __name__ == "__main__": > test() > > > === test2.py === > > from test import Foo > > def make_me_a_foo(): Add this: print "In test2, Foo is", repr(Foo) > return Foo() > > > --8<-- > > When I run "python test.py", I get "is NOT a Foo!", when the object > clearly IS a Foo! Indeed foo is an instance of a class named Foo, but it is not the Foo you are looking for. You have created *TWO* Foo classes. A class is created when its source is executed. This has happened twice, once when you ran the test.py script, and again when test2.py imported test. Circular imports are big trouble (in any language). If you think you need them, you are wrong; refactor until they go away. Circularly importing all or some objects from your __main__ script is double trouble. HTH, John From claudio.grondi at freenet.de Sun Jun 5 18:26:06 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 5 Jun 2005 22:26:06 -0000 Subject: what can happen if Python wents commercial ;-) ... Message-ID: <3gh5gaFc82m3U1@individual.net> don't click the following link if you are not at least 18 years old (or don't like sexual related content): http://www.python.com/ Claudio From lonetwin at gmail.com Sat Jun 25 01:37:09 2005 From: lonetwin at gmail.com (Steve) Date: Sat, 25 Jun 2005 11:07:09 +0530 Subject: Favorite non-python language trick? In-Reply-To: <42BBAE6A.1040100@kzoo.edu> References: <42BBAE6A.1040100@kzoo.edu> Message-ID: <5a309bd305062422375e7f007a@mail.gmail.com> Hi, > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? One thing that I miss every once in a while is "pre-processing". I'm wondering if I'm the only one here, since nobody seems to have brought that up. For example, after testing is done and I need to release some bit of code in production, I would like create the .pyc/.pyo, like so: # pycompile -DMAX_FOO=100 -D__version__=1.0 -D__release__=1.stable foo_module.py where pycompile, is an home baked script that maybe uses compile/compileall. I know, I can do the preprocessing myself in pycompile, but this would be a nice to have. Regards Steve On 6/24/05, Joseph Garvin wrote: > As someone who learned C first, when I came to Python everytime I read > about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > getattr/setattr, the % operator, all of this was very different from C. <...snip...> From ascoteric at hotmail.com Wed Jun 1 15:19:37 2005 From: ascoteric at hotmail.com (Ascoteric) Date: Wed, 1 Jun 2005 21:19:37 +0200 Subject: Test Message-ID: From markus_GETRIDOFALLCAPSwankus at hotmail.com Wed Jun 29 20:25:35 2005 From: markus_GETRIDOFALLCAPSwankus at hotmail.com (Markus Wankus) Date: Wed, 29 Jun 2005 20:25:35 -0400 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: <0CuRDhE1HnwCFwl9@objmedia.demon.co.uk> References: <11bs1bc5jotvg9c@news.supernews.com> <42BF6995.1050606@boonthavorn.com> <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> <0CuRDhE1HnwCFwl9@objmedia.demon.co.uk> Message-ID: Stephen Kellett wrote: > In message , Markus Wankus > writes > >> Have you ever tried anything that provides real, usable refactoring >> like Eclipse does with Java? I guarantee if you used it more than a >> few times your view would most likely change. > > > I was forced to use Eclipse recently. Dreadful. I really disliked it. I > never got as far as wanting to refactor things. I couldn't wait to stop > using it. > >> The fact is, code evolves. You simply cannot write high-quality >> software in one pass. > > > Total agreement. My point is that productivity gains from refactoring > tools are the least of your worries. Hiring good staff that know how to > write, test and debug software is very much more important than the > amount of time a refactoring tool will save. > > Stephen Well, I have been using it for 2 years now, and while I still prefer Python "big-time" to Java, I have really grown to love Eclipse. To each his own I guess. I agree you shouldn't bank on productivity gains from refactoring tools. And I agree they are definitely no kind of replacement for good people. I just think it is silly not to benefit from them. M. From peter at engcorp.com Fri Jun 10 08:03:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Jun 2005 08:03:28 -0400 Subject: match groups: optional groups not accessible In-Reply-To: <1118403410.852579.24710@z14g2000cwz.googlegroups.com> References: <1118403410.852579.24710@z14g2000cwz.googlegroups.com> Message-ID: <2LCdndztfdImHzTfRVn-pg@powergate.ca> david.reitter at gmail.com wrote: > Why does the following result in an IndexError? > I try to match an optional group, and then access it via its group > name. The group happens to not participate in the match, but is > obviously defined in the pattern. > >>>>m = re.match('(?Pmaybe)?yes', "yes") Uh, don't you need to actually *group* the first "yes" part, with parentheses, to make it a group? Otherwise you aren't going to be treating it as other than text-between-groups-that-can-be-skipped. -Peter From bogus@does.not.exist.com Tue Jun 28 15:15:02 2005 From: bogus@does.not.exist.com () Date: Tue, 28 Jun 2005 19:15:02 -0000 Subject: No subject Message-ID: #! rnews 2994 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 57 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1119898281.201400.85040 at o13g2000cwo.googlegroups.com> <1119956464.362328.290370 at o13g2000cwo.googlegroups.com> Mime-Version: 1.0 Date: Tue, 28 Jun 2005 18:58:08 GMT Xref: news.xs4all.nl comp.lang.python:383798 phil writes: > > > > You are quite correct to point out how much better it is to know what is > > going on behind the scenes. But heck, once you know how to extract square > > roots - you need to let the computer do it! > > GUI interfaces should be the same deal! > > Thomas Bartkus > > > I think I pretty much agree. I essentially code my own gui builder > > but in text files. > > I just think it is really important to emphasise the operative > "but once you know how" in your comments. > > Then some would counter with "oh, so we should code everthing > in assembler?" Ouch. No, I will admit there is judgement > required. Everything should be done the easiest way, with the > qualification that you need to understand how using someone > else's shortcut leaves you vulnerable. I agree with your comments on Python and java and IDEs. I'd like to expand on the "code in assy" complaint. Compiled-to-assy-to-machine-to-execution is understood and algorithmic. Any one person may no know it al,l but every step of the way has been thought out and optimized by someone who knew what he/she was doing. There are very few places where anyone has to dive down into assy, much less microcode or VLSI layouts. Therefore, we can trust the abstract model provided by the programming language, and can stay in that model. This is not the case for GUIs. We can't safely stay in the abstract GUI IDE. In fact, most require you to dive into the generated code to finish the task. Bouncing up and down the abstraction ladder is hard and made harder by being forced to live in the IDE's idea of generated code. Given that, GUI IDEs are still helpful if your base langauge is a pain to write and debug (e.g., C++, Java). But if your language is actually easier to use than the GUI IDEs, then the equation shifts. With Python, the clarity of thought and the opportunities for higher-level programming (dynamic code genration et al) make GUI IDEs just a waste of time or worse. I also have moved to text-based inputs to my own GUI builders. Maybe there is a sourceforge project waiting to be borne here :-) [snip] -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From steven.bethard at gmail.com Sat Jun 4 17:24:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 15:24:36 -0600 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Andrew Dalke wrote: > On Sat, 04 Jun 2005 10:43:48 -0600, Steven Bethard wrote: > >>Ilpo Nyyss?nen wrote: >> >>>How about this instead: >>> >>>with locking(mutex), opening(readfile) as input: >>> ... > >>I don't like the ambiguity this proposal introduces. What is input >>bound to? > > It would use the same logic as the import statement, which already > supports an 'as' like this Ahh, so if I wanted the locking one I would write: with locking(mutex) as lock, opening(readfile) as input: ... There was another proposal that wrote this as: with locking(mutex), opening(readfile) as lock, input: ... which is what was confusing me. Mirroring the 'as' from the import statement seems reasonable. But it doesn't address my other concern, namely, is with locking(mutex), opening(readfile) as input: ... equivalent to the nested with-statements, e.g.: _locking = locking(mutex) _exc1 = (None, None, None) _locking.__enter__() try: try: _opening = opening(readfile) _exc2 = (None, None, None) input = _opening.__enter__() try: try: ... except: _exc2 = sys.exc_info() raise finally: _opening.__exit__(*exc) except: _exc1 = sys.exc_info() raise finally: _locking.__exit__(*exc) Or is it equivalent to something different, perhaps: _locking = locking(mutex) _opening = opening(readfile) _exc = (None, None, None) _locking.__enter__() input = _opening.__enter__() try: try: ... except: _exc = sys.exc_info() raise finally: _opening.__exit__(*exc) _locking.__exit__(*exc) Or maybe: _locking = locking(mutex) _opening = opening(readfile) _exc = (None, None, None) _locking.__enter__() input = _opening.__enter__() try: try: ... except: _exc = sys.exc_info() raise finally: # same order as __enter__ calls this time!! _locking.__exit__(*exc) _opening.__exit__(*exc) All I'm saying is that any of these are possible given the syntax. And I don't see a precedent in Python for preferring one over another. (Though perhaps there is one somewhere that I'm missing...) And if it *is* just equivalent to the nested with-statements, how often will this actually be useful? Is it a common occurrence to need multiple with-statements? Is the benefit of saving a level of indentation going to outweigh the complexity added by complicating the with-statement? STeVe From skn at skn.com Thu Jun 16 01:45:40 2005 From: skn at skn.com (skn) Date: Thu, 16 Jun 2005 11:15:40 +0530 Subject: Generating .pyo from .py Message-ID: Hello., Does the python compiler provide an option to generate a .pyo(optimized byte code file) from a .py (source file)? For generating .pyc I know that I only have to pass the source file name as an argument to py_compile.py. But for generating .pyo, I could not find anything. Any clues/help will be greatly appreciated. With best regards, skn From saint.infidel at gmail.com Fri Jun 24 18:26:46 2005 From: saint.infidel at gmail.com (infidel) Date: 24 Jun 2005 15:26:46 -0700 Subject: a dictionary from a list In-Reply-To: <2133494.bAtaJnSUkF@teancum> References: <2133494.bAtaJnSUkF@teancum> Message-ID: <1119652006.368615.153320@z14g2000cwz.googlegroups.com> dict((x, None) for x in alist) From thomasbartkus at comcast.net Sat Jun 11 13:51:04 2005 From: thomasbartkus at comcast.net (tom) Date: Sat, 11 Jun 2005 12:51:04 -0500 Subject: Dealing with marketing types... References: Message-ID: On Sat, 11 Jun 2005 10:27:26 -0700, bruce wrote: > i don't know what the original thread is/was... > > but.. if you are part of an initial project.. get in writing what your role > is!!!! if you're as a partner, get it in writing... if you're as a hired > gun.. get it in writing... if you can't get anything in writing.. then make > sure you have your own copies of any/all code that you're created/been a > part of... > > in this day/age, you need to protect yourself.... > > and trust me, if your code is valuable, and you walk away with it because > you feel you've been treated in an unfair manner (assuimng no written > statement of your role), then let the other guy come after you... things get > resolved in a much more equitable manner when the concerned parties are > reasonably equal... > > -bruce I agree completely and you do need to read the original post. Thomas Bartkus From grante at visi.com Sun Jun 12 17:33:03 2005 From: grante at visi.com (Grant Edwards) Date: Sun, 12 Jun 2005 21:33:03 -0000 Subject: How to test if an object IS another object? References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> Message-ID: <11apagfb4e22d10@corp.supernews.com> On 2005-06-12, eloff777 at yahoo.com wrote: >>The most obvious way (as usual ?): >> >>if obj1 is obj2: >> // your code here > > I immediately thought of is, and tested it in the console, but it > didn't work quite like I expected: > >>foo = 3 >>bar = 3 >>zoo = foo >>foo is zoo > True >>foo is bar > True >>zoo is bar > True > > clearly foo and bar have the same value but they are different objects > aren't they? Nope. > Yet applying the is operator yields True. They're the same object. Why did you expect them not to be? -- Grant Edwards grante Yow! Am I elected yet? at visi.com From mwm at mired.org Wed Jun 8 18:53:39 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 08 Jun 2005 17:53:39 -0500 Subject: Help with SMTP References: Message-ID: <86ekbc7958.fsf@guru.mired.org> "Ivan Shevanski" writes: > Ok, all my problems are solved except for one. . .If I want my program > to send a message back to me do I need the from adress? Because I > don't specifically know it for the person using the program. Any help > is appreciated =D You need a from address for the SMTP transaction. You really should have a From: field in the message headers as well, but the message may work without that. In one sense, the message is "from" you, as it's being sent by your script. I'd be tempted to cons up a maildrop for the script, alias it to point at your mailbox, and then use that as the "From" address for the mail you're sending. You could ask the user to input an email address and use that as the >From address. Unless you plan on getting back to them via email, I wouldn't bother. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jepler at unpythonic.net Thu Jun 2 23:04:23 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Jun 2005 22:04:23 -0500 Subject: thread vs GC In-Reply-To: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> References: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> Message-ID: <20050603030423.GA26528@unpythonic.net> I suspect that getting the threads to die will be tricky, and as written the thread holds a reference to the 'primegen' instance (this part can be cured, but it still doesn't ever make the thread exit). Instead of figuring out how to get this to clean itself up, why not make sure you only make one 'primegen' instance, using one of the various singleton patterns? There may still be something "uncollectable", but at least there will only be one. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From reder at jpl.nasa.gov Thu Jun 9 18:33:51 2005 From: reder at jpl.nasa.gov (Leonard J. Reder) Date: Thu, 09 Jun 2005 15:33:51 -0700 Subject: Multithreaded Python FSM (Harel State Machines) Message-ID: Hello list, I have been searching on the web for a while now for a specific Python implementation of an FSM. More specifically what I am looking for is a Python implementation of the so called UML Harel State Machine notion of a state machine. These are multi-threaded capable state machines with hierarchical representation capability (nested instances of state machines). They also have a unique conditional trigger symbol scheme for event representation and state machine transitions. I have seen some great implementations of simple FSMs and some interesting descriptions of how generator/yeild python keywords can be used. I think python has all the pieces to make a Heral implementation. Does anyone know of a Python implementation of FSM that comes close to this functionality? Any comments or recommendation for FSM packages that I could add this functionality to would also be welcome. I certainly think someone has done something that approaches this already. All replies are very much appreciated. If I get enough response I will post a summary of findings to this group. Thanks for reading this and please reply. Regards, Len -- ____________________________________________________ Leonard J. Reder Jet Propulsion Laboratory Interferometry Systems and Technology Section 383 Email: reder at huey.jpl.nasa.gov Phone (Voice): 818-354-3639 Phone (FAX): 818-354-4357 Mail Address: Mail Stop: 171-113 4800 Oak Grove Dr. Pasadena, CA. 91109 --------------------------------------------------- From noreply at gcgroup.net Mon Jun 13 11:12:54 2005 From: noreply at gcgroup.net (William Gill) Date: Mon, 13 Jun 2005 15:12:54 GMT Subject: string formatting using the % operator Message-ID: I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%' I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? Thanks, Bill From harold.fellermann at upf.edu Mon Jun 13 12:15:13 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 13 Jun 2005 18:15:13 +0200 Subject: extending Python base class in C Message-ID: <45a2459ff94e552141ac47828242c16a@upf.edu> Hi all, I once read that it is possible to use a python base class for a C extension class. To be precise, I want to achieve the following behavior: class PythonClass : pass class CClass(PythonClass) : "this class should be implemented as C extension" pass Unfortunately, google could not find me the right reference. Does anyone know how to do it, or where I can find relevant information? Thanks, - harold - -- Je me suis enferm? dans mon amour -- je r?ve. -- Paul Eluard From me at privacy.net Wed Jun 29 10:58:14 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 29 Jun 2005 10:58:14 -0400 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c44giis2f5fa8@corp.supernews.com> Message-ID: On Wed, 29 Jun 2005 03:14:26 -0000, Grant Edwards wrote: > On 2005-06-28, James Stroud wrote: >> I think James Bond did it for Americans. He always wore a >> dinner jacket and played a lot of backarack--which is only >> cool because you have to bet a lot of money. Anyway, if you >> insist on making distinctions between the backwoods of >> apalachia and european aristocracy, > What, you think they sound the same? As a recent transplant to Appalachia, I have heard that some linguists speculate that because of the region's cultural isolation, perhaps the locals here do actually speak as they did (and as their ancestors in England did) a few hundred years ago. Regards, Dan -- Dan Sommers From darkpaladin79 at hotmail.com Mon Jun 6 18:51:36 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 18:51:36 -0400 Subject: Creating file of size x In-Reply-To: <42A4D20F.1030802@gmail.com> Message-ID: > > Can you elaborate more? Just any file? > >Yes -- a binary file. > > The file will contain check blocks for another file. The problem is >that the order of the received check blocks is not specified, so I need >to be able seek to the block's position in the file, and then just write >the block. > >-- >Kind Regards, >Jan Danielsson >Nobody loves a cynic ><< signature.asc >> I don't know. . .have you searched through modules? That's all I can think of. . . -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From claird at lairds.us Mon Jun 13 20:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Jun 2005 00:08:02 GMT Subject: implicit variable declaration and access References: <877jgy88do.fsf@hector.domek> Message-ID: <6kj1o2-13e.ln1@lairds.us> In article <877jgy88do.fsf at hector.domek>, Peter Dembinski wrote: >Benji York writes: > >[snap] > >>> code = x + '= 0' >>> exec(code) >> >> You should generally stay away from exec for lots of reasons. > >Code 'refactorizability' is one of them. There's an affirmative way to express this that I can't now make the time to generate. Yes, you're both right that, as popular as some make out such coding is in Lisp (and Perl and PHP), the per- ception that there's a need for it generally indicates there's a cleaner algorithm somewhere in the neighborhood. In general, "application-level" programming doesn't need exec() and such. PyPy and debugger writers and you other "systems" programmers already know who you are. My own view is that refactorizability is one of the secondary arguments in this regard. From nephish at xit.net Wed Jun 8 08:35:39 2005 From: nephish at xit.net (nephish at xit.net) Date: 8 Jun 2005 05:35:39 -0700 Subject: need some cgi help please In-Reply-To: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> References: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> Message-ID: <1118234139.279932.237290@g49g2000cwa.googlegroups.com> no takers? From steven.bethard at gmail.com Wed Jun 1 16:33:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Jun 2005 14:33:17 -0600 Subject: idiom for constructor? In-Reply-To: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: Mac wrote: > Is there a nice Python idiom for constructors which would expedite the > following? > > class Foo: > def __init__(self, a,b,c,d,...): > self.a = a > self.b = b > self.c = c > self.d = d > ... py> class Foo(object): ... def __init__(self, a, b, c, d): ... params = locals() ... del params['self'] ... self.__dict__.update(params) ... py> vars(Foo(1, 2, 3, 4)) {'a': 1, 'c': 3, 'b': 2, 'd': 4} Just make sure that "params = locals()" is the first line in __init__ method. (Otherwise you might have other local variables slip in there.) I wouldn't actually advise this code to anyone though. I find that if I have more than 3 or 4 parameters to a function, I should probably refactor my code. And with 4 or fewer parameters, I don't think you gain any clarity by using the "self.__dict__.update" trick. STeVe From cappy2112 at gmail.com Mon Jun 27 14:52:03 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 27 Jun 2005 11:52:03 -0700 Subject: delphi to python converter In-Reply-To: References: Message-ID: <1119898323.737872.284590@g44g2000cwa.googlegroups.com> Thys Meintjes wrote: > Greets, > > I have need of a Delphi/pascal to python converter. Googling didn't > suggest any obvious leads so I'm trying here... > > Thanks > Thys This isn't what you want, but you can probably achieve similar results, by embedding Pyton in your delphi app. http://www.atug.com/andypatterns/pythonDelphiTalk.htm From barney.dalton at gmail.com Tue Jun 7 17:00:09 2005 From: barney.dalton at gmail.com (barney) Date: 7 Jun 2005 14:00:09 -0700 Subject: file permissions on windows XP (home) References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> Message-ID: <1118178009.923372.160210@g44g2000cwa.googlegroups.com> Thanks, I tried creating a test file but I get "Access is denied" from windows explorer! The folder appears to be read only but when I try and uncheck read only/apply/repopen the folder properties its still read only. This read only flag seems to propagate down from the My Music directory but unchecking it there also has no lasting effect. I realise that theses are windows rather than python issues but I would expect there would be some reliable way of changing the file permissions from within python. I'm updating ID3 tags in MP3 file to give some context. If I use something like winamp to make the change to the ID3 tag then the file is updated with no permission errors so there must be a way.... I have added a stat call to the code which returns: (33206, 0L, 2, 1, 0, 0, 4142103L, 1118176036, 920221388, 1111442057) and this is the output of cacls (didn't know about this command): C:\Users\Barney\My Music\U2\The Best Of 1980 - 1990 (US CD 1)\02 - New Year's Day.mp3 XPHOME\Barney:(special access:) STANDARD_RIGHTS_ALL DELETE READ_CONTROL WRITE_DAC WRITE_OWNER SYNCHRONIZE STANDARD_RIGHTS_REQUIRED FILE_GENERIC_READ FILE_READ_DATA FILE_READ_EA FILE_WRITE_EA FILE_READ_ATTRIBUTES FILE_WRITE_ATTRIBUTES XPHOME\None:(special access:) READ_CONTROL SYNCHRONIZE FILE_GENERIC_READ FILE_READ_DATA FILE_READ_EA FILE_READ_ATTRIBUTES Everyone:(special access:) READ_CONTROL SYNCHRONIZE FILE_GENERIC_READ FILE_READ_DATA FILE_READ_EA FILE_READ_ATTRIBUTES I'm not entirely sure how to interpret these but will do some reading. In the meantime if someone could show me some python to force the file to be writeable that's all I really need at this stage. Thanks Barney From peter at engcorp.com Sat Jun 18 12:15:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:15:32 -0400 Subject: thread.start_new_thread question In-Reply-To: References: Message-ID: Konstantin Veretennicov wrote: > Thank you, but that doesn't answer my question. I was asking if there > is a reason that "args" is not optional. At the risk of increasing your frustration, I'm going avoid answering your question as well and simply point out that if you use the "threading" module, as is recommended, you won't have to deal with this issue at all, and your code will generally be simpler. (To answer your real question I'd have to check the docs for "thread" and, since I _never_ use that module in spite of heavy use of threading, I can't help you more... sorry.) -Peter From roy at panix.com Sat Jun 25 09:45:14 2005 From: roy at panix.com (Roy Smith) Date: Sat, 25 Jun 2005 09:45:14 -0400 Subject: Favorite non-python language trick? References: <42BBAE6A.1040100@kzoo.edu> Message-ID: Steve wrote: > One thing that I miss every once in a while is "pre-processing". There are so many things wrong with preprocessing, at least if you're thinking of the way C/C++ implements it (cpp). Cpp a number of things. 1) It does file inclusion. Pythons "import" serves that purpose and does a better job of it. 2) It defines constants. A simple assignment in Python does that just fine (and in C++, enums and const variables do it). 3) It does conditional compilation. Just use "if" in Python. You can even enclose function definitions inside an "if" body. 4) It lets you do macro expansion. Just write a function in Python. The big problem with cpp is that it essentially lets you define a whole new language. The code that is compiled/executed isn't anything like the code that you see on the screen. This can lead to debugging nightmares. BTW, if you *really* want to, you can use cpp with Python. For example, I just wrote the following little program. It's in a language I'll call Prethon, for lack of a better name. It comes in two files: ------------------------------- Roy-Smiths-Computer:play$ cat pp.h #define foo(bar) mySillyFunction(bar, 0) def mySillyFunction(x, y): x / y ------------------------------- and ------------------------------- Roy-Smiths-Computer:play$ cat pp.pre #include "pp.h" foo(37) ------------------------------- I can use cpp to turn this into a Python program by doing "cpp pp.pre > pp.py". When I run that, I get a run-time exception and a stack trace: Roy-Smiths-Computer:play$ python pp.py Traceback (most recent call last): File "pp.py", line 13, in ? mySillyFunction(37, 0) File "pp.py", line 10, in mySillyFunction x / y ZeroDivisionError: integer division or modulo by zero This is really confusing. I'm looking at my source code and don't see any calls to mySillyFunction(). In the trivial example I've given, it's obvious that it's a #define in pp.h, but in a real-life example, there can be hundreds or thousands of included files in a project, scattered about all sorts of different directories you may not even know exist. Trying to figure out what's going on becomes a nightmare. From dalke at dalkescientific.com Sat Jun 11 21:22:25 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 12 Jun 2005 01:22:25 GMT Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> <7xekb84rsa.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > That article makes a lot of bogus claims and is full of hype. LAMP is > a nice way to throw a small site together without much fuss, sort of > like fancy xerox machines are a nice way to print a small-run > publication without much fuss. If you want to do something big, you > still need an actual printing press. In the comments the author does say he's trying to be provocative. My question to you is - what is "something big"? I've not been on any project for which "LAMP" can't be used, and nor do I expect to be. After all, there's only about 100,000 people in the world who might possibly interested using my software. (Well, the software I get paid to do; not, say, the couple of patches I've sent in to Python). I had one client consider moving from Python/CGI/flat files to Java/WebLogic/Oracle. The old code took nearly 10 seconds to display a page (!). They were convinced that they had gone past the point where Python/CGI was useful, and they needed to use a more scalable enterprise solution. The conviction meant they didn't profile the system. With about a day of work I got the performance down to under a second by removing some needless imports, delaying others until they were needed, making sure all the .pyc files existed, etc. I could have gotten more performance switching to a persistent Python web server and using a database instead of a bunch of flat files in a directory, but that wasn't worth the time. Andrew dalke at dalkescientific.com From lycka at carmen.se Tue Jun 21 06:05:25 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 21 Jun 2005 12:05:25 +0200 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Remi Villatel wrote: > while True: > some(code) > if final_condition is True: > break > # > # > > What I don't find so "nice" is to have to build an infinite loop only to > break it. This is a common Python idiom. I think you will get used to it. > Is there a better recipe? final_condition = False while not final_condition: some(code) From chinook.nr at tds.net Tue Jun 28 15:30:36 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 15:30:36 -0400 Subject: I need help figuring out how to fix this code. References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: <0001HW.BEE71D9C000101B8F0407550@news.gmane.org> On Tue, 28 Jun 2005 14:39:47 -0400, Nathan Pinno wrote (in article <42c1997b$0$6975$b9fe7a78 at news.usenetrevolution.com>): > Hi all, > > I need help figuring out how to fix my code. I'm using Python 2.2.3, and > it keeps telling me invalid syntax in the if name == "Nathan" line. Here is > the code if you need it. > > #This program asks for a password, then asks for the user's name after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" > > What's wrong with the code? How do I fix it, so that it works? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > > > > At least one problem is further within the "if" > Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> name = 'yosa' >>> test = ['yosa', 'sosa'] >>> name == test False >>> name in test True >>> Lee C From kveretennicov at gmail.com Wed Jun 22 19:35:05 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 23 Jun 2005 01:35:05 +0200 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: <4660fe30050622163513271889@mail.gmail.com> On 6/23/05, Steve Horsley wrote: > It is my understanding that Pythons multithreading is done at the > interpteter level and that the interpreter itself is single > threaded. In this case, you cannot have multiple threads running > truly concurrently even on a multi-CPU machine Python uses native threads. >>> import thread, win32api >>> win32api.GetCurrentThreadId() 1532 >>> def t(): ... print win32api.GetCurrentThreadId() ... >>> for i in range(10): ... thread.start_new_thread(t, ()) ... 1212 1804 804 1276 1792 ... - kv From anthra.norell at tiscalinet.ch Wed Jun 15 04:04:21 2005 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Wed, 15 Jun 2005 10:04:21 +0200 Subject: Single test for a class and all its subclasses? Message-ID: <007c01c57180$d6619880$0201a8c0@mcuf7> class C: ... class C2 (C): ... # What I want to do: if x.__class__ in (C, C2): do_something_with (x) # Requires an exhaustive genealogy, which normally is impractical and often impossible # Another approach class_tree = inspect.getclasstree ((x.__class__,)) if classtree_contains (class_tree, C): do_something_with (x) # An awful lot of activity for a simple task I'd expect a attribute name like __class__, but haven't found one in the doc and my doc-search time-out setting for simple things like this is about one hour. Frederic -------------- next part -------------- An HTML attachment was scrubbed... URL: From twic at urchin.earth.li Fri Jun 24 11:31:08 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Fri, 24 Jun 2005 16:31:08 +0100 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: On Fri, 24 Jun 2005, Joseph Garvin wrote: > Claudio Grondi wrote: > > So far we've got lisp macros and a thousand response's to the lua trick. > Anyone else have any actual non-python language tricks they like? Higher-order functions like map, filter and reduce. As of Python 3000, they're non-python tricks. Sigh - i guess it's time for me to get to know list comprehensions a bit better. The one thing i really do miss is method overloading by parameter type. I used this all the time in java, and it really notice the lack of it sometimes in python. No, it's not really possible in a typeless language, and yes, there are implementations based on decorators, but frankly, they're awful. Yeah, and i'm with "if False:" for commenting out chunks of code. tom -- ... but when you spin it it looks like a dancing foetus! From jello at comics.com Sat Jun 4 09:07:08 2005 From: jello at comics.com (rzed) Date: Sat, 04 Jun 2005 09:07:08 -0400 Subject: If - Or statements References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> Message-ID: Ognjen Bezanov wrote in news:mailman.483.1117877861.18027.python-list at python.org: > Robert Kern wrote: > >> Ognjen Bezanov wrote: >> >>> Another newbie-ish question. >>> >>> I want to create an if statement which will check if a >>> particular variable matches one of the statements, and willl >>> execute the statement if the variable matches any of the >>> statements. >>> >>> I have tried the following (the pass is just used for testing) >>> >>> >>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or >>> ext[1] == "aac" or ext[1] != "wma": >>> print "we have a valid extension: " + ext[1] #here >>> would go the >>> code for decoding the above >>> pass >> >> >> It works fine for me. Could you post the smallest complete >> program (one that defines ext) that displays the behavior and >> its entire output? >> >> As an aside, is 'ext[1] != "wma"' correct or should it be ==? >> As written, you could collapse the whole thing to 'if ext[1] != >> "wma":' but I presume it is a typo. >> > filelist = os.listdir('/mnt/cdrom/') #get a list of files from > the cdrom drive > for thefile in filelist[:]: #for each file in the > filelist > if thefile.find(".") != -1: #if the file has an > extenstion > at all > ext = thefile.split('.') #get the file extension > ext[1] = ext[1].lower() #convert to lowercase > print ext[1] #debugging, to see the variable > before > passed to if statement > > if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] > == "ogg" > or ext[1] == "aac" or ext[1] == "wma": > print "we have a valid extension: " + ext[1] > #here > would go the code for decoding the above > pass Though this may sidetrack the issue, another way of doing multiple checks like that is to make a list and check for inclusion in the list. Something like this: exts = ['mp3','mp4','ogg','aac','wma'] if ext[1] not in exts: # do whatever or if ext[1] in exts: print 'we have a valid extension:',ext[1] It's easier to add to the list than to add another explicit test, particularly if the tests occur in several places. -- rzed From mfurmaniuk at gmail.com Tue Jun 7 09:12:35 2005 From: mfurmaniuk at gmail.com (Pykid) Date: 7 Jun 2005 06:12:35 -0700 Subject: EnumKey vs EnumValue In-Reply-To: References: Message-ID: <1118149950.308651.248400@g43g2000cwa.googlegroups.com> Ok, this was not how I understood it to work earlier when I was going over this. I do want to eventually see the values under each key, so I guess if I want to see what is under each key I need to then reopen it and send that value to EnumValue. Tried that and ended up with this which seems to work: for i in range(25): try: regEndeca = EnumKey(regpath,i) print regEndeca regValue = OpenKey(HKEY_LOCAL_MACHINE, key + "\\" + regEndeca) for j in range(25): try: regstr,value,type = EnumValue(regValue,j) print "Value Name: ", regstr, " - Value: ",value, " - Data: ",type except EnvironmentError: print "There are", j,"values under",regEndeca break print "That was using EnumValue." except EnvironmentError: print "There are", i,"keys under",key break print "That was using EnumKey." Thanks for the help From grante at visi.com Thu Jun 30 18:47:02 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 30 Jun 2005 22:47:02 -0000 Subject: Scket connection to server References: <3ij2bgFlr9h0U1@news.dfncis.de> Message-ID: <11c8tj6ba0u5v42@corp.supernews.com> On 2005-06-30, Andr? Egners wrote: >>> I would like to establish a socket connection to a server >>> running a service on port 29999. the host address is >>> 10.214.109.50. how do i do this using python? >>> >>> many thanks >>> >>> >> >> Off the top of my head (so there could be errors): >> >> import socket >> s = socket.Socket() >> s.connect((10.214.109.50, 29999)) >> s.send("Hello, Mum\r\n") > > Just curious...where do these messages show up @10.214.109.50? Um, at port 29999? -- Grant Edwards grante Yow! does your DRESSING at ROOM have enough ASPARAGUS? visi.com From python at rcn.com Sun Jun 12 22:05:30 2005 From: python at rcn.com (Raymond Hettinger) Date: 12 Jun 2005 19:05:30 -0700 Subject: case/switch statement? References: Message-ID: <1118628330.865192.122210@o13g2000cwo.googlegroups.com> [Joe Stevenson] > > I skimmed through the docs for Python, and I did not find anything like > > a case or switch statement. I assume there is one and that I just > > missed it. [deelan] > topic already beated to death It's not dead yet. It has excellent use cases and an open PEP, http://www.python.org/peps/pep-0275.html . It needs advocacy, TLC, a clear proposal, an implementer, and a little luck. Raymond Hettinger From kveretennicov at gmail.com Tue Jun 21 10:00:17 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 17:00:17 +0300 Subject: Python choice of database In-Reply-To: References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: <4660fe30050621070023b2591c@mail.gmail.com> On 6/21/05, Charles Krug wrote: > > Related question: > > What if I need to create/modify MS-Access or SQL Server dbs? You could use ADO + adodbapi for both. http://adodbapi.sourceforge.net/ - kv From phillip.watts at anvilcom.com Tue Jun 28 14:04:58 2005 From: phillip.watts at anvilcom.com (phil) Date: Tue, 28 Jun 2005 13:04:58 -0500 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com><1119956464.362328.290370@o13g2000cwo.googlegroups.com> Message-ID: <42C1914A.1060208@anvilcom.com> > > You are quite correct to point out how much better it is to know what is > going on behind the scenes. But heck, once you know how to extract square > roots - you need to let the computer do it! > > GUI interfaces should be the same deal! > Thomas Bartkus > I think I pretty much agree. I essentially code my own gui builder but in text files. I just think it is really important to emphasise the operative "but once you know how" in your comments. Then some would counter with "oh, so we should code everthing in assembler?" Ouch. No, I will admit there is judgement required. Everything should be done the easiest way, with the qualification that you need to understand how using someone else's shortcut leaves you vulnerable. This guy is trying to get started and looking for our advice and I saw most of the advice leaning towrd VB (aarrgh!) and I thought I should give him other food for thought. I'm going to take this opportunity for a short rant. I believe our society ( I'm an old fart) is drifting toward a VERY small percentage of people knowing, caring or even being curious about "how stuff works". I teach high school geometry and am APPALLED at the apathy. I am concerned about the future of this nation, economically, but spirtually as well. So, this influences my advice. Know how your stuff works if it is reasonable. Tom Wolfe talked in a book about two kinds of kids. Those that play video games and those that make video games, and the numbers of the latter is shrinking. From cimrman3 at ntc.zcu.cz Mon Jun 13 10:46:56 2005 From: cimrman3 at ntc.zcu.cz (Robert Cimrman) Date: Mon, 13 Jun 2005 16:46:56 +0200 Subject: program call graph Message-ID: Hi, After much googling, I still cannot find any tool/module for producing a (static) call graph of a program. I have got nearly to my aim with trace.py, though it must actually run the program and the output would have to be parsed after; and doxygen + pythfilter.py, which should work, but did not (pythfilter having some parsing problems). I would greatly appreciate your hints/suggestions. Thanks, Robert From richie at entrian.com Fri Jun 24 10:26:46 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 24 Jun 2005 15:26:46 +0100 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: <42BC15A6.4040801@pythonapocrypha.com> References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <42BC15A6.4040801@pythonapocrypha.com> Message-ID: <0v5ob1t2njntqo8hqbgkml3u32taub2t0q@4ax.com> [Dave Brueck] > Please keep the discussion civil; please help keep c.l.py a nice place to visit. +1 -- Richie Hindle richie at entrian.com From grig.gheorghiu at gmail.com Sat Jun 11 16:57:18 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 11 Jun 2005 13:57:18 -0700 Subject: Sending mail from 'current user' in Python In-Reply-To: <42aaee03$0$71235$e4fe514c@news.xs4all.nl> References: <3gsve7Fe8957U1@individual.net> <1118461971.461936.327550@g14g2000cwa.googlegroups.com> <42aaee03$0$71235$e4fe514c@news.xs4all.nl> Message-ID: <1118523438.783855.197350@f14g2000cwb.googlegroups.com> There may have been a reason for the win32 stuff at some point....but I don't remember and you're right, it does seem like getpass by itself would do the job. Grig From max at alcyone.com Wed Jun 29 01:54:02 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 28 Jun 2005 22:54:02 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1120023753.231890.182890@g43g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1120023753.231890.182890@g43g2000cwa.googlegroups.com> Message-ID: BORT wrote: > In my earlier browsing, I eliminated Logo early on, thinking we would > hit its capability ceiling too quickly and then backtrack in order to > make a transition to a "REAL" language. > > uh... I've been browsing on Logo tonight and, even without the Lego > robots, I may go that route. Shoot, I thought Logo was just moving > hokey sprites in increasingly complex patterns until I saw the book > list at: It's probably ideal for ages 7 and 10. Note that even the name _logo_ is Greek for _word_. There's plenty of "non-hokey sprite" stuff you can do with Logo, it's just that the turtle graphics are the most visually obvious form of Logo and what most people who had any exposure to Logo remember most easily. The language itself shares a great deal with Lisp. There are numerous modern Logo interpreters, so you shouldn't have any problem finding something both you and the kids can use, like UCBLogo for Unix or MSWLogo for Windows (based on UCBLogo). If you want to go that route, there's even a set of computer science texts based on Logo, called _Computer Science Logo Style_ by Brian Harvey, maintainer of UCBLogo. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Does the true light / Of love come in flashes -- Sandra St. Victor From cantabile.03 at wanadoo.fr Mon Jun 13 18:26:23 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Tue, 14 Jun 2005 00:26:23 +0200 Subject: Get drives and partitions list (Linux) In-Reply-To: References: <42accf62$0$11720$8fcfb975@news.wanadoo.fr> Message-ID: <42ae0810$0$11707$8fcfb975@news.wanadoo.fr> Hi, Peter Thanks for the reply. I'll check popen(). But you said I should not rely on fdisk... Why ? And should I prefer sfdisk ? Why ? Peter Hansen wrote: > cantabile wrote: > >> Hi, I'd like to get drives and partitions (and their size too) with >> python under Linux. So far, I thought of reading /proc/partitions but >> maybe i could use fdsik also ? >> How would I do that in python ? > > > Somebody else posted a very similar question quite recently. A Google > Groups search would probably lead you to the answers pretty quickly. > (Try "partition proc sfdisk" or something like that.) > > My previous answer was to call sfdisk, using os.popen(). Others > suggested reading /proc/partitions. I doubt fdisk (if that's what you > meant) is a good idea. > > There is no pure Python solution, so far as I know, probably because > there may not be any standardized way of finding this information. > > -Peter From trentm at ActiveState.com Thu Jun 9 11:33:33 2005 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 9 Jun 2005 08:33:33 -0700 Subject: identifying 64-bit Windows from 2.3.5? In-Reply-To: References: Message-ID: <20050609153333.GB22482@ActiveState.com> [Steven Knight wrote] > If I have installed 2.3.5 from the python.org Windows installer, can > any one point me to a run-time way to identify whether I'm running on > a 32-bit vs. 64-bit version of Windows XP, given that Python itself was > built on/for a 32-bit system? > > I hoped sys.getwindowsversion() was the answer, but it returns the same > platform value (2) on both 32-bit and 64-bit systems. sys.platform > ("win32") and sys.maxint are both set at compile time. Things like > os.uname() aren't on Windows. > > Can some Windows-savvy Pythonista point me to some way to distinguish > between these two? To see if the Python you are running is 64-bit you can see how big a pointer is: import struct struct.calcsize('P') Mind you, you can run a 32-bit Python build on 64-bit-capable systems so that may not be what you want. Trent -- Trent Mick TrentM at ActiveState.com From jrastrick at student.usyd.edu.au Wed Jun 8 14:24:08 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 8 Jun 2005 11:24:08 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> Message-ID: <1118255048.849018.259500@g14g2000cwa.googlegroups.com> Well, I don't really want the objects to be comparable. In fact, to quote that PEP you linked: An additional motivation is that frequently, types don't have a natural ordering, but still need to be compared for equality. Currently such a type *must* implement comparison and thus define an arbitrary ordering, just so that equality can be tested. I don't want to order the objects. I just want to be able to say if one is equal to the other. Here's the justification given: The == and != operators are not assumed to be each other's complement (e.g. IEEE 754 floating point numbers do not satisfy this). It is up to the type to implement this if desired. Similar for < and >=, or > and <=; there are lots of examples where these assumptions aren't true (e.g. tabnanny). Well, never, ever use equality or inequality operations with floating point numbers anyway, in any language, as they are notoriously unreliable due to the inherent inaccuracy of floating point. Thats another pitfall, I'll grant, but its a pretty well known one to anyone with programming experience. So I don't think thats a major use case. Are there any other reasonable examples people can give where it makes sense for != and == not to be each other's complement? Besides, the argument given doesn't justfiy the approach taken. Even if you want to allow objects, in rare cases, to override __ne__ in a way thats inconsistent with __eq__, fine, do so. But thats no reason for Python not to fall back on __eq__ in the cases where __ne__ is not defined, rather than reverting to object identity comparison (at least I assume thats what its doing) To draw a parallel: In Java, the compareTo method in a class is allowed to be inconsistent with the equals method, but those who write such code are advised to heavily advertise this fact in their documentation and source, so as not to catch unwary users off guard. In Python, the *default* behaviour is for the equals and not equals operations to disagree if the __eq__ method happens to be overriden (which it definitely should be in a great number of cases). Surely this isn't the right way to do things. How many classes out there that have the following redundant, cluttering piece of code? def __ne__(self, other): return not self.__eq__(other) Worse still, how many classes don't have this code, but should, and are therefore harbouring highly confusing potential bugs? Unless someone can explain some sort of problem that arises from having != take advantage of a __eq__ method where present, I'd suggest that it should do so in Python 2.5. I'd be surprised if such a change broke so much as a single line of existing Python code. From tim.golden at viacom-outdoor.co.uk Fri Jun 10 08:26:05 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 10 Jun 2005 13:26:05 +0100 Subject: python create WMI instances Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8B0@vogbs009.gb.vo.local> [Marc Wyburn] | | Hi all, I am struggling with a vb - python code conversion. I'm using | WMI to create printers on remote machines using (in VB); | | set oPrinter = oService.Get("Win32_Printer").SpawnInstance_ | | oPrinter.DriverName = strDriver | oPrinter.PortName = strPort | oPrinter.DeviceID = strPrinter | oPrinter.Put_(kFlagCreateOnly) | | In python I have logged onto the WMI service on the remote machine and | I can run things like c.new.AddPrinterConnection so I know that I am | connected and working OK. I don't get any errors when I create a new | object with SpawnInstance_ but when I try to set the value of | oPrinter.Drivername I get an error saying that the Drivername object | doesn't exist. Does anyone know how to set the values of the object | using either the method above or with the WMI module? I think the WMI | module only allows access to modify methods such ADDPrinterConnection | or Create (from Win32_Service). Not sure if I can help here or not, but just in case... As far as I understand you, the fact that you're creating on a remote machine is just an incidental, ie you'd have the same problem doing this locally. Part of the problem is that when VB does something like: oPrinter.DriverName = strDriver what's really happening behind the scenes is something like: oPrinter.Properties_ ("DriverName").Value = strDriver Now you can do that in Python. (In fact, that's what the wmi module does when it overrides __setattr__, followed by a Put_). So if you want to translate code fairly literally, then carry on as you were, but substitute the latter code for the former. Having said that, the wmi module *can* create new instances of classes. The problem is that I had/have little knowledge of how WMI works in this area, so what I've done may not be right. The method you're looking for is .new (aliased as .new_instance_of) and if you use help on that method, you'll get this: new(self, wmi_class) unbound wmi.WMI method Create a new , typically something like Win32_Process, eg: c = wmi.WMI ("remote_machine") for p in c.Win32_Process (name="notepad.exe"): print p c.new ("Win32_Process").Create (CommandLine="notepad.exe") for p in c.Win32_Process (name="notepad.exe"): print p p.Terminate () for p in c.Win32_Process (name="notepad.exe"): print p Now this example works, but I notice from the code that what I did to make it work was to remove the SpawnInstance_ which I had, and replace it by an instance retrieval. ie I just do a Get on the class. I'll try to find some examples around of what you're doing which, up till now, I've not really needed to do. Meanwhile, I hope the above info is of some use. Feel free to respond with questions or comments. This can only get clearer! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dotpyFE at gmail.com Thu Jun 9 16:49:40 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Thu, 09 Jun 2005 20:49:40 GMT Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > "wooks" wrote in message > news:1118318436.192627.320820 at g49g2000cwa.googlegroups.com... > >>http://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem&item=5206943952 > > > Are you the seller flogging his item? We really don't need every auction > listing for Python books copied to this forum. Please don't repeat. > > TJR > > > I don't think that was his intention. -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From thomas at thomas-lotze.de Wed Jun 22 14:42:24 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Wed, 22 Jun 2005 20:42:24 +0200 Subject: Package organization Message-ID: Hi, I've two questions concerning organizing and naming things when writing a Python package. - Naming of classes: I'm writing a library that reads PDF files. I have a data structure that represents the large-scale structure of a PDF file (header, trailer, incremental updates etc), and I'll have others, e.g. one that represents the document as a collection of logical objects (page descriptions, images etc). Assume I have a package called PDF. Should the classes then be called simply File and Objects, as it is clear what they do as they are imported from PDF? Or should they be called PDFFile and PDFObjects, as the names would be too undescriptive otherwise? - Organizing subpackages and interfaces: I'm using the zope.interface package in order to define interface classes. In a small package called foo, one might define interfaces IReadableFoo and IWritableFoo in foo.interfaces. However, in a large package foo with subpackages bar and baz, interface definitions might either sit in foo.bar.interfaces and foo.baz.interfaces, or in foo.interfaces.bar and foo.interfaces.baz. Which is preferable? Thanks for any thought on this. -- Thomas From sjmachin at lexicon.net Sat Jun 11 23:26:26 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 12 Jun 2005 13:26:26 +1000 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: <42ABAB62.4040205@lexicon.net> Roy Smith wrote: > "Philippe C. Martin" wrote: > >>Yet, many issues that a future software engineer should know are >>mostly hidden by Python (ex: memory management) and that could be >>detrimental. > > > I know I'm going out on a limb by asking this, but why do you think future > software engineers should know about memory management? Perhaps we have a terminology problem here i.e. different meanings of "software engineer". Philippe started talking about "CS" courses, whereas you may be referring to people who have done an "IT" course or achieved a certification in the use of app development tool X. > > I used to worry about register allocation. Today, I don't even know how > many registers any machine I work on has. I used to worry about word size, > and byte order. I used to worry about whether stacks grew up or down and > addressing modes and floating point formats. Sure, somebody's got to worry > about those things, but most people who write software can be blissfully > ignorant (or, at best, dimly aware) of these issues because somebody else > (compiler writer, hardware designer, operating system writer, etc) has > already done the worrying. You would hope they'd done more than worry about it. However sometimes one's fondest hopes are dashed. You must have noticed the anguish in the timbot's posts that mention Windows 95 memory management. > > There used to be a time when you had to worry about how many tracks to > allocate when you created a disk file. When's the last time you worried > about that? Seeing you asked: early 1970s, on an IBM 1800. But much more recently it certainly helped if one were slightly more than dimly aware of the difference between a FAT filesystem and an NTFS filesystem :-) Cheers, John From harlin at pythonian.com Mon Jun 20 11:54:17 2005 From: harlin at pythonian.com (Harlin Seritt) Date: Mon, 20 Jun 2005 11:54:17 -0400 Subject: Want to learn a language - is Python right? References: <1119264546.393296.245650@f14g2000cwb.googlegroups.com> <7x3brdjnyt.fsf@ruckus.brouhaha.com> <1119278824.847517.294700@g47g2000cwa.googlegroups.com> Message-ID: Aziz McTang wrote: > Hi Paul, > > Thanks for your input. > > As usual, hearing some answers helps formulate the question... > > What I'm looking for is more to learn one good, comprehensive > programming language well than several approximately on an ad hoc > basis. What I also failed to mention is the desire to develop my > presently limited computer skills a lot further. > > So although your answer to 1 suggests I'd be using a steam-roller to > kill a fly, if I do need to go further (or ask other people to help and > still understand what's going on: one site I may want to develop later > involves a number of languages including Japanese as well as audio) I > won't have to re-learn another program. Is this right? > > As to 2, I have yet to find a canned program that does what I want, and > so far every programmer I've asked to write it has said "hey that's > easy" then escaped, never to be heard of again. > > And 3: good! Actually, having learned half a dozen languages, I can > vouch for it being an excellent way to acquire and consolidate > vocabulary. Talking to (or, rather, understanding) the natives is > another kettle of fish! > > Thanks again! > > Any new slants from yourself or others are welcome. > > Aziz You can use CherryPy for creating a Python-esque web application. Never buy into the fluff that says Python is not as good as PHP for web apps! PHP is still too Perl-Like (meaning old and useless)! Python is the choice of a new generation baby!!! :) JK... For your vocab program, Python is actually perfect. This could even go for apps that require some Unicode and other Internationalization snafus (like right-to-left characters and Cyrillic typesets). If you're looking for one programming language then you should consider the idea that no one language can do it all (although Python comes close in my biased opinion). Python is not for memory management, writing device drivers and the like. As far as needing something for web apps, CherryPy is great -- just learn Python first. PHP is good but it has fallen out of favor with me though there are a ton of people out there who think it is the greatest thing since sliced bread. Take a look at the Python tutorial: http://docs.python.org/tut/tut.html. Good luck, Harlin Seritt From tbr at nospam.nos Mon Jun 13 04:06:11 2005 From: tbr at nospam.nos (TechBookReport) Date: Mon, 13 Jun 2005 09:06:11 +0100 Subject: Learning more about "The Python Way" In-Reply-To: References: Message-ID: Kalle Anke wrote: > Those who have read my posts today have probably understood that I'm > not a "true" Python programmer ... but I want to learn more (I think > that Python is rather fun). > > I've read "Learning Python" pretty thoroughly, I've looked at some of > the tutorials, some of online documentation, etc. But I still miss a > lot of pieces for writing good python code, idioms, advanced > usage/features, etc. > > I've also seen a lot of references to v3, but I haven't found any > real documentation of what's planned for that version. > > So, I'm looking for advice/information on: > > + How to write "proper" python code instead of > Java/Perl/C/C++/Pascal/Modula-2/etc inspired code > > + The more advanced parts/uses of Python > > + Discussions about the ideas behind different Python > constructs > > + What's going to happen with v3 > > I would really appriciate some pointers to where I can find info > about this. Web sites (I've looked at python.org but haven't manage > to find the stuff of what I'm looking for ... but perhaps I've missed > all the interesting parts) ? Books (I've got 'Learning Python' and > 'Programming Python')? Other things? > > jem > > latest edition of the Python Cookbook (read a review here http://www.techbookreport.com/tbr0163.html). Also online at ActiveState. From twic at urchin.earth.li Thu Jun 30 13:58:20 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 30 Jun 2005 18:58:20 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 29 Jun 2005, Michael Hoffman wrote: > Steven D'Aprano wrote: > >> Herb starts with H, not E. It isn't "ouse" or "ospital" or "istory". It >> isn't "erb" either. You just sound like tossers when you try to >> pronounce herb in the original French. Yes, i find this insanely irritating. >> And the same with homage. > > Strangely enough there are Brits who pronounce "hotel" without an H at > the beginning. And even those who pronounce it with an H sometimes say > "an hotel" rather than "a hotel" because it used to be pronounced > starting with the vowel! That's an interesting one. In most English accents, and i think in RP, it's "a hotel"; dropping of the aitch and the accompanying shift to 'an', as in "an 'otel" is a symptom of Estuary english. However, as you say, there is some weird historical precedent for pronouncing the 'h' but also using 'an', as in "an hotel", which is practiced only by the self-consciously posh (including, often, newsreaders), and sounds completely absurd. > Similarly, the Brits should note that "idea" does not end in an "r" and that > "Eleanor" does. How about carrier? tom -- I know you wanna try and get away, but it's the hardest thing you'll ever know From guettli at thomas-guettler.de Thu Jun 9 10:33:33 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 09 Jun 2005 16:33:33 +0200 Subject: Generating HTML from python References: Message-ID: Am Thu, 09 Jun 2005 12:43:19 +0000 schrieb Philippe C. Martin: > Hi, > > I wish to use an easy way to generate reports from wxPython and feel > wxHtmlEasyPrinting could be a good solution. > > I now need to generate the HTML wxHtmlEasyPrinting can print I don't know wxPython, but generating HTML is very easy. Some people say mixing HTML and programming code is not good. But if you want to create dynamic pages with more logic than HTML this is the best solution. Example: Multiplication Table rows=[] heading=[] for i in range(1, 11): heading.append('%s' % i) cols=[] for j in range(1, 11): cols.append('%s' % (i*j)) row='%s%s' % (i, ''.join(cols)) rows.append(row) html=""" Multiplication Table %s %s
 
""" % (''.join(heading), ''.join(rows)) I guess this looks more ugly in most template languages. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From http Thu Jun 2 03:08:26 2005 From: http (Paul Rubin) Date: 02 Jun 2005 00:08:26 -0700 Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> Message-ID: <7xd5r55j85.fsf@ruckus.brouhaha.com> "poisondart" writes: > If this thread has shown anything it is I'm a bit green with respect to > software licenses, but the other thing is that I consider myself as an > isolated case and I wanted to know if there were others who wanted the > same thing as me. You're going through the same issues that most of us involved in free software have gone through at some time. Welcome. > I'm curious to know what the money that open source or GPL'd projects > get and what this money means to these people's overall income. Well, it varies, but I'd say most of the time, it's done as a community contribution, not for money. It's similar to doctors doing free medical clinics, lawyers doing pro bono legal work, etc. However, it's possible to make a living writing GPL'd code, and some people do that. (I've done it in the past). > Yes, what I ask may seem ridiculous, but I don't view it that way. > Instead, I find that it is the implication of using a restrictive > license such as I described to be ridiculous: if there is no monetary > gain option in the license, then this implies that nobody (or very few) > will be willing to do any work or "asking for something for nothing". > It isn't for nothing if you value knowledge and learning. Well, long experience has shown that in practice, such clauses tend to turn away users and developers. > I admit that my view is a bit idealistic which leads me to believe that > maybe I should reconsider the whole decision altogether. The really idealistic view is that once the program is published, the author has no special relation to it that others don't have. This is what the GPL tries to approximate, by giving users similar rights to the author's (e.g. guaranteed access to the source code). Note also that in your other posts, you're using "selling" in an imprecise and confusing way. This might help: http://www.gnu.org/philosophy/selling.html Some more articles on the general free software topic: http://www.gnu.org/philosophy/ From donn at u.washington.edu Thu Jun 23 12:50:39 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 23 Jun 2005 09:50:39 -0700 Subject: Avoiding deadlocks in concurrent programming References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> <7xslz93nh2.fsf@ruckus.brouhaha.com> Message-ID: In article , Konstantin Veretennicov wrote: > On 22 Jun 2005 17:50:49 -0700, Paul Rubin > <"http://phr.cx"@nospam.invalid> wrote: > > > Even on a multiprocessor > > system, CPython (because of the GIL) doesn't allow true parallel > > threads, ... . > > Please excuse my ignorance, do you mean that python threads are always > scheduled to run on the same single CPU? Or just that python threads > are often blocked waiting for GIL? Any thread may execute "inside" the interpreter, but not concurrently with another. I don't see the original point, though. If you have a C application with no GIL, the queueing model is just as useful -- more, because a GIL avoids the same kind of concurrency problems in your application that it intends to avoid in the interpreter. Rigorous application of the model can be a little awkward, though, if you're trying to adapt it to a basically procedural application. The original Stackless Python implementation had some interesting options along those lines. Donn Cave, donn at u.washington.edu From rkern at ucsd.edu Fri Jun 17 15:07:43 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 17 Jun 2005 12:07:43 -0700 Subject: add new modules? In-Reply-To: <11b65f7bjjt7a51@corp.supernews.com> References: <11b65f7bjjt7a51@corp.supernews.com> Message-ID: Dennis Clark wrote: > This is a total newb question, you have been warned... > > I've been all over the www.python.org site and googled, but I've not > found just how to add new modules. I've tried setting PYTHONPATH, > I've tried putting the new module directories into the site-packages > directory, I've tried creating the .pth files, I've even done all > three of these things at the same time and still my python script > refuses to import. What is the cannonical way to add new modules > to python? I am running on OS X 10.4 (Macintosh obviously) on basically > freeBSD, os I'm doing UNIX type stuff at the console. If you are using the Apple-supplied Python 2.3.5, put the modules in /Library/Python/2.3/site-packages/ . If you are using Bob Ippolito's Python 2.4.1, then it's /Library/Frameworks/Python.framework/Versions/Current/lib/python2.4/site-packages . -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From eurleif at ecritters.biz Mon Jun 6 16:28:52 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 06 Jun 2005 20:28:52 GMT Subject: About size of Unicode string In-Reply-To: References: Message-ID: <8m2pe.8937$Cz3.1120032@monger.newsread.com> Frank Abel Cancio Bello wrote: > request.add_header('content-encoding', 'UTF-8') The Content-Encoding header is for things like "gzip", not for specifying the text encoding. Use the charset parameter to the Content-Type header for that, as in "Content-Type: text/plain; charset=utf-8". From jrastrick at student.usyd.edu.au Sat Jun 18 03:42:41 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 18 Jun 2005 00:42:41 -0700 Subject: extreme newbie In-Reply-To: <42B3AC76.2060504@lexicon.net> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> Message-ID: <1119080561.407266.319960@o13g2000cwo.googlegroups.com> Another thing to keep in mind is that while technically both Python and Java are converted into intermediate byte-codes, which are then interpreted, the Java Virtual Machine runs java bytecode significantly faster. Partly this is because Sun have put a lot of effort into making Java as fast as possible, in an attempt to lure away clockcycle-addicted C programmers; and partly its because having your langugage statically typed makes it easier to do things quickly (for technical reasons that I don't fully understand ;)) So Java has and probably always will have an advantage in the execution speed steaks. That doesnt change the fact that I'd rather code in Python over Java any day of the wek, though :) From grahamd at dscpl.com.au Mon Jun 6 23:27:35 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 6 Jun 2005 20:27:35 -0700 Subject: PSP / mod_python ... how to get POST vars on .psp ? In-Reply-To: References: Message-ID: <1118114855.882302.262800@g49g2000cwa.googlegroups.com> The documentation states: Additionally, the PSP code will be given global variables req, psp, session and form. In other words, in your PSP page you can access the "form" variable and it will give you access to the FieldStorage object that PSP creates for you. The members of the FieldStorage class are documented on the mod_python web site. From steve at holdenweb.com Wed Jun 15 20:59:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 15 Jun 2005 20:59:00 -0400 Subject: Cause for using objects? In-Reply-To: <1e71b37dbd3c61060246fa2630a0d2ae@guardnet.com> References: <1e71b37dbd3c61060246fa2630a0d2ae@guardnet.com> Message-ID: John Heasly wrote: > Given: > [{"mugshot": "nw_gradspeaker4_0608", "width": 67.0, "height": 96.0}, \ > {"mugshot": "nw_gradspeaker2_0608", "width": 67.0, "height": 96.0}, \ > {"freehand": "b1.developreport.0614", "width": 154.0, "height": > 210.0}, \ > {"graphic": "bz_cafeparadiso_0613", "width": 493.0, "height": 341.0}] > > Return: > {"mugshot1": "nw_gradspeaker4_0608", "mugshot1.width": 67.0, > "mugshot1.height": 96.0,\ > "mugshot2": "nw_gradspeaker2_0608", "mugshot2.width": 67.0, > "mugshot2.height": 96.0, \ > "freehand1": "b1.developreport.0614", "freehand1.width": 154.0, > "freehand1.width": 210.0, \ > "graphic1": "bz_cafeparadiso_0613", "graphic1.width": 493.0, > "graphic1.height": 341.0} > > I'm trying to teach myself some OOP. Does grinding the Given above into > the Return seem like a good candidate? > John: Other responders have already hinted at the possibility that you are asking for help with one step of a significant task. Perhaps with more context (I have to write TIFF images read from disk at the rate of three per second for an advertising display system) we might be able to be of more assistance? regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From dberlin at gmail.com Thu Jun 16 17:22:19 2005 From: dberlin at gmail.com (dberlin at gmail.com) Date: 16 Jun 2005 14:22:19 -0700 Subject: wx GUI with other classes Message-ID: <1118956939.703973.196800@g47g2000cwa.googlegroups.com> hey, My situation is like this- whenever I create an application with a gui I put the gui source in one file that calls all the other classes (from imported modules). This creates a problem when needing to print something out on a gui control or something similar. It is then needed to send the called class the control object and the class will then modify it on its part. This makes the classes I create not very generic, and just gives me the feeling i'm tangling all my modules and classes together. Anyone have other ideas how to solve this? or maybe there is no problem in doing this at all? From sjmachin at lexicon.net Fri Jun 24 09:03:17 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Jun 2005 23:03:17 +1000 Subject: howto load and unload a module In-Reply-To: References: Message-ID: <42BC0495.9080900@lexicon.net> Peter Hansen wrote: > Guy Robinson wrote: > >> I have a directory of python scripts that all (should) contain a >> number of attributes and methods of the same name. >> >> I need to import each module, test for these items and unload the >> module. I have 2 questions. [snip] >> 2.. how do I test for the existance of a method in a module without >> running it? What the OP is calling a 'method' is more usually called a 'function' when it is defined at module level rather than class level. > > > The object bound to the name used in the import statement is, well, an > object, so you can use the usual tests: > > import mymodule > try: > mymodule.myfunction > except AttributeError: > print 'myfunction does not exist' > > or use getattr(), or some of the introspection features available in the > "inspect" module. > Ummm ... doesn't appear to scale well for multiple modules and multiple attributes & functions. Try something like this (mostly tested): modules = ['foomod', 'barmod', 'brentstr', 'zotmod'] attrs = ['att1', 'att2', 'att3', 'MyString'] funcs = ['fun1', 'fun2', 'fun3'] # the above could even be read from file(s) for modname in modules: try: mod = __import__(modname) except ImportError: print "module", modname, "not found" continue for attrname in attrs: try: attr = getattr(mod, attrname) except AttributeError: print "module %s has no attribute named %s" % \ (modname, attrname) continue # check that attr is NOT a function (maybe) for funcname in funcs: pass # similar to above but check that it IS a function BTW, question for the OP: what on earth is the use-case for this? Bulk checking of scripts written by students? Cheers, John From querypk at gmail.com Tue Jun 7 11:40:08 2005 From: querypk at gmail.com (querypk at gmail.com) Date: 7 Jun 2005 08:40:08 -0700 Subject: time consuming loops over lists Message-ID: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> X-No-Archive: yes Can some one help me improve this block of code...this jus converts the list of data into tokens based on the range it falls into...but it takes a long time.Can someone tell me what can i change to improve it... def Tkz(tk,data): no_of_bins = 10 tkns = [] dmax = max(data)+1 dmin = min(data) rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0))) rngs = zeros(no_of_bins+1) for i in xrange(no_of_bins+1): rngs[i] = dmin + (rng*i) for i in xrange(len(data)): for j in xrange(len(rngs)-1): if data[i] in xrange(rngs[j],rngs[j+1]): tkns.append( str(tk)+str(j) ) return tkns From jan.danielsson at gmail.com Wed Jun 29 13:56:54 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 29 Jun 2005 19:56:54 +0200 Subject: Graphs/statistics using wxPython Message-ID: <42c2df8b$1@griseus.its.uu.se> Hello all, I wanted to plot some statistics, so I wrote a simple wxPython class to do it. Then I realized that I would like to draw bar graphs, so I added that too. Since I'm a complete Python newbie, I haven't done much of it the "Python way", I suspect. So, I'm wondering if someone would like to show me some of the tricks I should have used. You can find the code at: http://user.it.uu.se/~jada3673/drawtest.py It's not finished[*], but it is usable. Oh, you can do whatever you want with it. Since I had never touched wxPython before working with this, I used some doodle application as a starting point. Btw... Has anyone already written statistics classes for wxPython? If so, where can I find them? If nothing similar exists, I'll probably add support for loading data from a file, and a few other features. Feel free to make requests or enhancements. [*] There are some size/offset bugs which I am aware of, but they are easily fixed. I just haven't got around to it yet. From uche.ogbuji at gmail.com Sat Jun 18 02:48:38 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 17 Jun 2005 23:48:38 -0700 Subject: ElementTree Namespace Prefixes In-Reply-To: <1118680405.635415.110740@f14g2000cwb.googlegroups.com> References: <1118680405.635415.110740@f14g2000cwb.googlegroups.com> Message-ID: <1119077318.730438.78590@g47g2000cwa.googlegroups.com> Chris Spencer: """ Fredrik Lundh wrote: > Chris Spencer wrote: > > If an XML parser reads in and then writes out a document without having > > altered it, then the new document should be the same as the original. > says who? Good question. There is no One True Answer even within the XML standards. It all boils down to how you define "the same". Which parts of the XML document are meaningful content that needs to be preserved and which ones are mere encoding variations that may be omitted from the internal representation? """ One can point out the XML namespaces spec all one wants, but it doesn't matter. The fact is that regardless of what that spec says, as you say, Chris, there are too many XML technologies that require prefix retention. As a simple example, XPath and XSLT, W3C specs just like XMLNS, uses qnames in context, which requires prefix retention. Besides all that, prefix retention is generally more user friendly in round-trip or poartial round-trip scenarios. That's why cDomlette, part of 4Suite [1] and Amara [2], a more Pythonic API for this, both support prefix retention by default. [1] http://4suite.org [2] http://uche.ogbuji.net/tech/4Suite/amara/ -- Uche http://copia.ogbuji.net From steve at REMOVETHIScyber.com.au Thu Jun 2 11:52:18 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 03 Jun 2005 01:52:18 +1000 Subject: Is there a better way of doing this? References: Message-ID: On Mon, 30 May 2005 14:05:36 +0200, Magnus Lycka wrote: > Steven D'Aprano wrote: > > print is a statement, not a function. The brackets are syntactically > > correct, but pointless. Remove them. > ... >> On Sat, 28 May 2005 13:24:19 +0000, Michael wrote: >>> while( newNS ): >> >> Guido (our Benevolent Dictator For Life and creator of Python) hates >> seeing whitespace next to parentheses. I agree with him. while(newNS) >> good, while( newNS ) bad. > > while is a statement, not a function. The brackets are syntactically > correct, but pointless. Remove them. ;^) Um. Er. Of course I knew that. I deliberately made that error to see if others were paying attention. Well done, go to the head of the class. *cough* :-) > while newNS: > > Not only are they pointless (in both print and while), but they are > blurring the distinction between statements and callables, and they > add noise. Only wrap the expression following a statement such as > while, if, print etc in () if the following expression spans several > lines. Yes, of course you are right. Serves me right for replying to Usenet posts in the wee hours of the morning. Although, pardon me for stating the obvious, using brackets for precedence, or to add clarity by careful grouping, is always allowed even if the expression doesn't span more than one line. eg while (index > 0) and (not found or still_working): -- Steven. From chris.arndt at web.de Wed Jun 29 19:43:23 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 30 Jun 2005 00:43:23 +0100 Subject: Debugger Confusion In-Reply-To: <1120059903.248536.135970@o13g2000cwo.googlegroups.com> References: <1120059903.248536.135970@o13g2000cwo.googlegroups.com> Message-ID: Rex Eastbourne schrieb: > Also, when I try running pdb in my Emacs shell, I get very weird > behavior: for instance, I'll hit 'h' and enter twenty times with no > output. Then, all of a sudden, twenty output messages will pop up. That may be due to output buffering. Try running your script with "python -u yourscript.py". You have to figure out for yourself, how to do that from within emacs though. HTH, Chris From ronan_boisard at yahoo.com Fri Jun 3 04:55:37 2005 From: ronan_boisard at yahoo.com (ronan_boisard at yahoo.com) Date: 3 Jun 2005 01:55:37 -0700 Subject: calling ksh script from python In-Reply-To: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: <1117788937.207065.18670@z14g2000cwz.googlegroups.com> thanks for your input... well I just find out that modifying environment through ksh call is not possible (can't get the new evironment back to python). I think the best thing to do is to translate all my ksh to pure python... I thought that I could re-use some stufff, but I guest I'm going to translate everything... From spam.csubich+block at block.subich.spam.com Thu Jun 30 05:02:19 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 30 Jun 2005 05:02:19 -0400 Subject: twisted: not doing DNS resolutions? In-Reply-To: References: Message-ID: Christopher Subich wrote: > Christopher Subich wrote: > >> From what I can tell, the problem lies in that Twisted simply isn't >> performing the DNS resolutions. From the connection factory's ... right, finally figured it out after a very long time at debugging the beast. It's an interaction with IDLE. What happens is that the deferToThread call in twisted's lookup Just Doesn't Run Right (under some circumstances) when it's run under IDLE with tksupport. I finally got the idea to run the application from the command line, and it worked just fine. This is kind of odd, since a trivial test case run from the interactive idle prompt works okay, but it's now 5am and I'm going to sleep. Moral: beware the IDLEs of March. From rynt at yahoo9.com Thu Jun 30 14:34:52 2005 From: rynt at yahoo9.com (Ruben Baumann) Date: Thu, 30 Jun 2005 11:34:52 -0700 Subject: Seeking IDE References: Message-ID: "Nick Mountford" wrote in message news:mailman.1133.1120151988.10512.python-list at python.org... Hi, Complete newb to Python and programming, looking for an open source IDE to download. Any suggestions? Thanks, Nick SPE (Can be used in editor mode only if desired, but comes with WxGlade for GUI) Boa Constructor, VisualWx, Python Card (if your desire a GUI approach) RB From greg at example.invalid Tue Jun 7 15:45:33 2005 From: greg at example.invalid (Greg Krohn) Date: Tue, 07 Jun 2005 19:45:33 GMT Subject: Wxpython demo crashes In-Reply-To: References: Message-ID: Pekka Karjalainen wrote: > I'm using WinXP (Finnish), Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC > v.1310 32 bit (Intel)] on win32 and wxPython 2.6.0.1. > > When I go to the Process and Events section in the wxDemo and run the > Process demo, bad things can happen. It crashes. I think the crash is > caused by characters outside the basic ASCII range, but I haven't tested > it in detail. Do you have the unicode version of wxPython? http://prdownloads.sourceforge.net/wxpython/wxPython2.6-win32-unicode-2.6.1.0-py24.exe ^^^^^^^ From dalke at dalkescientific.com Thu Jun 2 17:03:49 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 02 Jun 2005 21:03:49 GMT Subject: Formatting Time References: Message-ID: Ognjen Bezanov wrote: > I have a float variable representing seconds, and i want to format it > like this: > > 0:00:00 (h:mm:ss) >>> def format_secs(t): ... m, s = divmod(t, 60) ... h, m = divmod(m, 60) ... return "%d:%02d:%02d" % (h, m, s) ... >>> format_secs(0) '0:00:00' >>> format_secs(1) '0:00:01' >>> format_secs(59) '0:00:59' >>> format_secs(60) '0:01:00' >>> format_secs(61) '0:01:01' >>> format_secs(3600) '1:00:00' >>> format_secs(3601) '1:00:01' >>> format_secs(3661) '1:01:01' >>> format_secs(3600*100+120+58) '100:02:58' >>> Andrew dalke at dalkescientific.com From kent37 at tds.net Thu Jun 16 08:33:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jun 2005 08:33:13 -0400 Subject: access properties of parent widget in Tkinter In-Reply-To: References: Message-ID: <42b17114$1_2@newspeer2.tds.net> William Gill wrote: > I am trying to get & set the properties of a widget's parent widget. > What I have works, but seems like a long way around the block. First I > get the widget name using w.winfo_parent(), then i convert the name to a > reference using nametowidget(). > > self.nametowidget(event.widget.winfo_parent()).hasChanged= True Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? Kent From python at rcn.com Mon Jun 13 04:17:13 2005 From: python at rcn.com (Raymond Hettinger) Date: 13 Jun 2005 01:17:13 -0700 Subject: new string function suggestion References: <7fare.27429$J12.6708@newssvr14.news.prodigy.com> Message-ID: <1118650633.758355.56740@g49g2000cwa.googlegroups.com> [Andrew Dalke] <200 lines of thorough analysis> > To summarize: > - I don't think it's needed that often > - I don't think your implementation's behavior (using an > exception) is what people would expect > - I don't think it does what you expect Wow, that was a remarkably thoughtful, total demolition ;-) I expect that this thread is going to be somewhat short lived. From oneill at konto.pl Tue Jun 14 15:42:15 2005 From: oneill at konto.pl (Grzegorz) Date: Tue, 14 Jun 2005 21:42:15 +0200 Subject: eclipse, pydev and wxpython - standard output redirection ? Message-ID: Hello, I'm using eclipse with pydev plugin, I'm working on a program using wxpython . When I'm executing that application standard error output does not show in eclipse console window - wxpython seems to redirect standard output to some another window , and closes that window immediately, so I can't see any error messagess. Is there a way to redirect standard output to eclipse console ? From deets at web.de Sat Jun 18 10:40:50 2005 From: deets at web.de (Diez B. Roggisch) Date: Sat, 18 Jun 2005 16:40:50 +0200 Subject: extreme newbie In-Reply-To: <1119105092.240065.224910@g44g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> Message-ID: <3hiq3lFh0dsfU1@uni-berlin.de> cpunerd4 wrote: > what I mean by secure is that no one can steal the code. I want to > create comercial applications eventually. (although I will work on open > source I hope, so don't get mad at me) and calling me cpunerd4 will be > fine. Commercial applications don't suffer from code-stealing. They might suffer from feature replicating competitors, or from non-paying users. But your code is usual so tied to your actual design approach that it is of no or at least limited use to anyone trying to create his own application. And 98% if not 100% of the code is not actually new or innovative by itself. The only part of an app that might be of interest for others is something like a new algorithm - e.g. a videodecoder. But if it _is_ interesting, it can and will be reverse engineered - even if written in pure assembly. The only way to protect it is not to release it at all - by using a RPC mechansim like CORBA or XMLRPC to access it. So - the bottomline is - don't worry about releasing the code too much. The question of FOSS or commercial is a license thing - the hindrance is of legal nature, not technical. Diez From agriff at tin.it Fri Jun 17 18:02:46 2005 From: agriff at tin.it (Andrea Griffini) Date: Fri, 17 Jun 2005 22:02:46 GMT Subject: What is different with Python ? References: <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: <6lg6b1568j7lu52g18kcmrsks48saib0rj@4ax.com> On Fri, 17 Jun 2005 08:40:47 -0400, Peter Hansen wrote: >And the fact that he's teaching C++ instead of just C seems to go >against your own theories anyway... (though I realize you weren't >necessarily putting him forth as a support for your position). He's strongly advocating of a starting from high-level; comp.lang.c++.moderated is where I first posted on this issue. While I think that python is not a good first language, C++ is probably the *worst* first language I can think to. C++ has so many traps, asymmetries and ugly parts (many for backward compatibility) that I would say that one should try put aside logic when learning it and just read the facts; in many aspect C++ is the way it is for historical reasons or unexplicable incidents: IMO there's simply no way someone can deduce those using logic no matter how smart s/he is. C++ IMO must be learned by reading... thinking is pointless and in a few places even dangerous. Also, given the C/C++ philosophy of "the programmer always knows perfectly what is doing", experimenting is basically impossible; trial and error doesn't work because in C++ there is no error; you have undefined behaviour daemons instead of runtime error angels. Add to the picture the quality of compile time error messages from the primitive template technology and even compile time errors often look like riddles; if you forget a "const" you don't get "const expected"... you get two screens full of insults pointing you in the middle of a system header. Thinking to some of the bad parts of it it's quite shocking that C++ is good for anything, but indeed it does work; and can be better than C. I think C++ can be a great tool (if you understand how it works; i.e. if it has no magic at all for you) or your worst nightmare (if you do not understand how it works). I think that using C++ as the first language for someone learning programming is absurd. Francis thinks otherwise. Andrea From ikvsabre at comcast.net Sat Jun 11 12:15:42 2005 From: ikvsabre at comcast.net (Joe Stevenson) Date: Sat, 11 Jun 2005 16:15:42 -0000 Subject: case/switch statement? Message-ID: Hi all, I skimmed through the docs for Python, and I did not find anything like a case or switch statement. I assume there is one and that I just missed it. Can someone please point me to the appropriate document, or post an example? I don't relish the idea especially long if-else statements. Joe From silasju at gmail.com Tue Jun 21 09:51:16 2005 From: silasju at gmail.com (silasju at gmail.com) Date: 21 Jun 2005 06:51:16 -0700 Subject: Python can do it for me? In-Reply-To: References: <1119357359.145942.139840@g43g2000cwa.googlegroups.com> Message-ID: <1119361876.273665.114710@f14g2000cwb.googlegroups.com> Really? I see Python is very good general-purpose language. I studing TCL, C++ and Java too. And remote conection? Do you know something? Thank you very much! Bye! From tjreedy at udel.edu Wed Jun 1 12:52:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 12:52:10 -0400 Subject: Elementtree and CDATA handling References: <1117631202.723453.20060@z14g2000cwz.googlegroups.com> Message-ID: "Fredrik Lundh" wrote in message news:d7kdam$71c$1 at sea.gmane.org... > you're confusing the external representation of something with the > internal > data model. > > consider this: > > >>> "hello" > >>> 'hello' > >>> "hell\x6f" > >>> "hell\157" > >>> "hell" + "o" > >>> 'h' 'e' 'l' 'l' 'o' > > the above are six ways to write the same string literal in Python. Minor nit: I believe 'hell' + 'o' is two string literals and a runtime concatenation operation. Perhaps you meant 'hell' 'o', without the '+', which I believe is joined to one literal at parsing or compilation time. > all these result > in a five-character string containing the letters "h", "e", "l", "l", and > "o". > if you type the above at a python prompt, > you'll find that Python echoes the strings back as > 'hello' in all six cases. Nit aside, this is a valuable point that bears repeating. Another example of one internal versus multiple external that confuses many is the following: 1.1 == 1.1000000000000001 # True The mapping of external to internal is many-to-one for both strings and floats and therefore *cannot* be exactly inverted! (Or round-tripped.) So Python has to somehow choose one of the possible external forms that would generate the internal form. Terry J. Reedy From ukc902591034 at btconnect.com Mon Jun 27 03:34:37 2005 From: ukc902591034 at btconnect.com (Alan Gauld) Date: Mon, 27 Jun 2005 07:34:37 +0000 (UTC) Subject: Life of Python References: Message-ID: "Uwe Mayer" wrote in message news:d9jcij$nm6$1 at news2.rz.uni-karlsruhe.de... > con: If you are planning larger applications (for a reasonable value of > "large") you have to discipline yourself to write well structured code. As always. > Then you will want to specify interfaces, accessor functions with different > read /write access, ... Why? What advantage does this really give you over indicative doc strings? interfaces in particular are a modern madness. Why not just define a class with a set of unimplemented methods. Who cares if someone tries to instantiate it? What can they do with it? They only make sense in languages which are statically typed and rely on inheritance to implement polymorphism. Pure accessor methods are usually a mistake anyway, but can be done using properties if you really must. > Unless you have designed the software interactions completely bevorehand > (which never works out) this is the only way to incorporate changes without > refactoring your source all the time. On really big projects it is fairly normal to define the structure of the code to quite a detailed level - often using Case tools and UML etc - so refactoring is only needed when you discover a hole. Thats true regardless of size of project but the Case approach tends to limit the damage. > this should be expanded further, i.e. more build-in decorators for > interfaces, abstract classes, parameter and return value restrictions. What kind of parameter and return value restrictions? In a dynamically typed language there is a limit to what can be applied, and much of that is of limited value IMHO. > with Perl than with Python and since there is no way of forcing a > programmer to do it a certain way, I'm always uncomfortable about trying to "force" a programmer to do it a certain way. I can never know what circumstances those client programmers might be facing when I write/design my code. And I can never be sure that I know better than the client programmer. I've seen too much C++ code that begins #define private public to believe that trying to force programmers rather than inform them is a good idea. (And FWIW I have worked on several multi million line projects with upwards of 400 programmers working in 5 or more locatons in Lisp, C, SQL, COBOL etc. Attempts to impose rules rather than agreed protocols have never been very helpful in my experience) > its often easyer to rewrite Perl programs over 400 lines That probably has a lot more to do with Perl's inscrutable syntax and "many ways to do it" approach than any of the classifiers being discussed here! I certainly didn't find us rewriting Lisp code rather than enhancing what was there, and Lisp shares much of Python's approach to life. -- Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Nicholas.Vaidyanathan at aps.com Wed Jun 15 12:12:49 2005 From: Nicholas.Vaidyanathan at aps.com (Nicholas.Vaidyanathan at aps.com) Date: Wed, 15 Jun 2005 09:12:49 -0700 Subject: Tkinter Question Message-ID: <23B7F3E89F1D424C96B13402B5F514D3048A55F9@ntm007.apsc.com> Thanks for all the help guys... I'm a bit confused as to the inner workings of the Tkinter system (I'm both a Python and a GUI n00b). I was hoping that by slapping the x on button python was doing some cool dynamic variable creation (i.e. creating 9 variables with 1 loop using the x as a variable to modify the identifier), but I suppose you can't do that in Python (or can you?) I'm a little confused as to why self.button.text doesn't work but self.button["text"] does, can someone explain this? Thanks! -Nick "MMS " made the following annotations. ------------------------------------------------------------------------------ --- NOTICE --- This message is for the designated recipient only and may contain confidential, privileged or proprietary information. If you have received it in error, please notify the sender immediately and delete the original and any copy or printout. Unintended recipients are prohibited from making any other use of this e-mail. Although we have taken reasonable precautions to ensure no viruses are present in this e-mail, we accept no liability for any loss or damage arising from the use of this e-mail or attachments, or for any delay or errors or omissions in the contents which result from e-mail transmission. ============================================================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Jun 5 20:52:55 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 06 Jun 2005 10:52:55 +1000 Subject: PyArg_ParseTuple and dict In-Reply-To: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> References: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> Message-ID: <42A39E67.4060909@lexicon.net> sjh at gmail.com wrote: > I'm trying to write an extension for python 2.4, and I can't seem to > get PyArg_ParseTuple to work with a dict. I've tried all sorts of > things, but the most simple thing that fails is: > > [...] > if (!PyArg_ParseTuple(args, "O", &file)) { > return NULL; > } > [...] > > > If I call the function from python with an int, or a string, etc it > works fine. If I pass in a dict I get: > > SystemError: new style getargs format but argument is not a tuple > > > even though a call to: > PyObject_TypeCheck(args, &PyTuple_Type) > > tells me that args is a tuple. PyObject_Print(args, stdout, NULL) even > produces: > > ({'foo': 1},) > > Can anyone give me a minimal example of a C function that takes a dict > and parses it out with PyArg_ParseTuple? 1. On the surface, there appears to be a bug. In the interests of finding out where the bug is, perhaps it would be better if you posted your minimal compilable runnable example of what *doesn't* work. 2. To get you off the ground: *if* there is only one argument and it can only be described in general terms like "O" (i.e. you still need to check the type) then there is little point in using PyArg_ParseTuple; describe the function as using METH_O instead of METH_VARARGS, and access the arg directly. 3. What is your platform? Which C compiler? What warnings does it give, [or would it give if allowed free speech]? Are you running Python 2.4 or 2.4.1? 4. Do you get the same symptoms when you pass in a list instead of a dict? What about a minimal user-created object? Cheers, John From kveretennicov at gmail.com Thu Jun 16 11:02:00 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 16 Jun 2005 18:02:00 +0300 Subject: Set of Dictionary In-Reply-To: <20050616144143.26956.qmail@web53905.mail.yahoo.com> References: <20050616144143.26956.qmail@web53905.mail.yahoo.com> Message-ID: <4660fe3005061608023c4f96ab@mail.gmail.com> On 6/16/05, Vibha Tripathi wrote: > Hi Folks, > > I know sets have been implemented using dictionary but > I absolutely need to have a set of dictionaries... While you can't have a set of mutable objects (even dictionaries :)), you can have a set of immutable snapshots of those objects: >>> d1 = {1: 'a', 2: 'b'} >>> d2 = {3: 'c'} >>> s = set([tuple(d1.iteritems()), tuple(d2.iteritems())]) >>> s set([((3, 'c'),), ((1, 'a'), (2, 'b'))]) >>> [dict(pairs) for pairs in s] [{3: 'c'}, {1: 'a', 2: 'b'}] - kv From mage at mage.hu Fri Jun 10 10:20:38 2005 From: mage at mage.hu (Mage) Date: Fri, 10 Jun 2005 16:20:38 +0200 Subject: without shell In-Reply-To: References: Message-ID: <42A9A1B6.9020101@mage.hu> Steven D'Aprano wrote: >On Sun, 12 Jun 2005 23:16:35 +0530, km wrote: > > > >>hi all, >> >>can any linux command be invoked/ executed without using shell (bash) ? >> >> > >py> import os >py> status = os.system("ls") > >Prints the output of ls and stores the exit code into status. > >py> file_list = os.popen("ls").read() > >Stores the output of ls into file_list. > > > These commands invoke shell indeed. Mage From dformosa at dformosa.zeta.org.au Wed Jun 1 08:30:31 2005 From: dformosa at dformosa.zeta.org.au (David Formosa (aka ? the Platypus)) Date: Wed, 01 Jun 2005 12:30:31 GMT Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <3584469.Aerji1NdQr@yahoo.com> <9SXme.22456$Is4.3402@attbi_s21> Message-ID: On Wed, 1 Jun 2005 06:09:43 +0200, Tassilo v. Parseval wrote: [...] > I am only familiar with its successor Modula-3 which, as far as I > understand, is Modula-2 with uppercased keywords and some OO-notion > bolted onto it (I still recall 'BRANDED' references). Modula-2 also overused caps, I recall the irratation I found programing it was irratating, streaching my finger to hit the shift key or taking me hands of the home keys to bump the CAPSLOCK key quick became phisically painfull. -- Please excuse my spelling as I suffer from agraphia. See http://dformosa.zeta.org.au/~dformosa/Spelling.html to find out more. Free the Memes. From peter at engcorp.com Mon Jun 13 20:31:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Jun 2005 20:31:05 -0400 Subject: win32evtlog In-Reply-To: <1118705839.260490.13140@z14g2000cwz.googlegroups.com> References: <1118705839.260490.13140@z14g2000cwz.googlegroups.com> Message-ID: <7PydnRpfyLjuuzPfRVn-qA@powergate.ca> sigzero at gmail.com wrote: > Is anyone versed in pulling out information from the Windows (2000) > event log? I have looked at the docs and I am in the dark as to how to > do it. Do what? I am looking to pull out all events with "error" as the > type. Generally there are a few things you can do to help yourself with such things. There are some samples of win32 stuff in the win32all package, in the "Demos" directories. It's possible there is some support for that already. Google can also help you search the list archives to find whether others have asked this question in the past, as is almost always the case. Usually it helps to know the name of either the relevant module from the win32all package, or the relevant Win32 API which you can often get from the msdn.com site if you don't already know it. Finally, Googling the web instead of the newsgroup will often work very nicely. The best approach is to start with the subject line you are about to use for your posting plus the word Python (e.g. "python win32evtlog"). Let us know what you find out! -Peter From thomas at thomas-lotze.de Sat Jun 11 19:48:41 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sun, 12 Jun 2005 01:48:41 +0200 Subject: Controlling a generator the pythonic way References: <863bro4o9h.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Yes, such a switch gets the desired behavior as a side effect. Then again, > a generator that returns tokens has a desired behavior (advancing to the > next token) as a side effect(*). That's certainly true. > If you think about these things as the > state of the object, rather than "side effects", it won't seem nearly as > ugly. In fact, part of the point of using a class is to encapsulate the > state required for some activity in one place. > > Wanting to do everything via parameters to methods is a very top-down way > of looking at the problem. It's not necessarily correct in an OO > environment. What worries me about the approach of changing state before making a next() call instead of doing it at the same time by passing a parameter is that the state change is meant to affect only a single call. The picture might fit better (IMO) if it didn't look so much like working around the fact that the next() call can't take parameters for some technical reason. I agree that decoupling state changes and next() calls would be perfectly beautiful if they were decoupled in the problem one wants to model. They aren't. > *) It's noticable that some OO languages/libraries avoid this side > effect: the read method updates an attribute, so you do the read then > get the object read from the attribute. That's very OO, but not very > pythonic. Just out of curiosity: What makes you state that that behaviour isn't pythonic? Is it because Python happens to do it differently, because of a gut feeling, or because of some design principle behind Python I fail to see right now? -- Thomas From bronger at physik.rwth-aachen.de Sat Jun 18 19:08:39 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 19 Jun 2005 01:08:39 +0200 Subject: Unbound names in __del__ References: <87mzpnmwpg.fsf@wilson.rwth-aachen.de> <87is0bmvqt.fsf@wilson.rwth-aachen.de> Message-ID: <87ekazntzc.fsf@wilson.rwth-aachen.de> Hall?chen! "Terry Reedy" writes: > "Torsten Bronger" wrote: > > [...] > >> However, this doesn't close sessions while the program is >> running. If the programmer has the above code in a function >> which is called repeatedly, he may run into trouble. IIRC my >> current VISA DLL has only 256 session slots. > > Deleting during a run is a different issue from deleting during > program shutdown, which is where you started us. Well, I talked about shutdown in the OP because only *then* I had experienced problems. Cleaning up is important in every phase of the program, though. > [...] So an explicit close is the only dependable > cross-implementation method that I know of. I agree, but I could live with the little danger of a Python implementation that frees so slowly that the DLL runs out of handles. One could add a close() method for emergency use. However, this __del__ thingy is so damn tempting ... ;-) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From dalke at dalkescientific.com Wed Jun 1 04:09:34 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 01 Jun 2005 08:09:34 GMT Subject: pickle alternative References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <1117524878.988878.181820@g44g2000cwa.googlegroups.com> <1117527950.319411.193030@g44g2000cwa.googlegroups.com> <1117606128.506536.234690@g14g2000cwa.googlegroups.com> Message-ID: simonwittber posted his test code. I tooks the code from the cookbook, called it "sencode" and added these two lines dumps = encode loads = decode I then ran your test code (unchanged except that my newsreader folded the "value = ..." line) and got marshal enc T: 0.21 marshal dec T: 0.4 sencode enc T: 7.76 sencode dec T: 11.56 This is with Python 2.3; the stock one provided by Apple for my Mac. I expected the numbers to be like this because the marshal code is used to make and read the .pyc files and is supposed to be pretty fast. BTW, I tried the performance approach I outlined earlier. The numbers aren't much better marshal enc T: 0.2 marshal dec T: 0.38 sencode2 enc T: 7.16 sencode2 dec T: 9.49 I changed the format a little bit; dicts are treated a bit differently. from struct import pack, unpack from cStringIO import StringIO class EncodeError(Exception): pass class DecodeError(Exception): pass def encode(data): f = StringIO() _encode(data, f.write) return f.getvalue() def _encode(data, write, pack = pack): # The original code use the equivalent of "type(data) is list" # I preserve that behavior T = type(data) if T is int: write("I") write(pack("!i", data)) elif T is list: write("L") write(pack("!L", len(data))) # Assumes len and 'for ... in' aren't lying for item in data: _encode(item, write) elif T is tuple: write("T") write(pack("!L", len(data))) # Assumes len and 'for ... in' aren't lying for item in data: _encode(item, write) elif T is str: write("S") write(pack("!L", len(data))) write(data) elif T is long: s = hex(data)[2:-1] write("B") write(pack("!i", len(s))) write(s) elif T is type(None): write("N") elif T is float: write("F") write(pack("!f", data)) elif T is dict: write("D") write(pack("!L", len(data))) for k, v in data.items(): _encode(k, write) _encode(v, write) else: raise EncodeError((data, T)) def decode(s): """ Decode a binary string into the original Python types. """ buffer = StringIO(s) return _decode(buffer.read) def _decode(read, unpack = unpack): code = read(1) if code == "I": return unpack("!i", read(4))[0] if code == "D": size = unpack("!L", read(4))[0] x = [_decode(read) for i in range(size*2)] return dict(zip(x[0::2], x[1::2])) if code == "T": size = unpack("!L", read(4))[0] return tuple([_decode(read) for i in range(size)]) if code == "L": size = unpack("!L", read(4))[0] return [_decode(read) for i in range(size)] if code == "N": return None if code == "S": size = unpack("!L", read(4))[0] return read(size) if code == "F": return unpack("!f", read(4))[0] if code == "B": size = unpack("!L", read(4))[0] return long(read(size), 16) raise DecodeError(code) dumps = encode loads = decode I wonder if this could be improved by a "struct2" module which could compile a pack/unpack format once. Eg, float_struct = struct2.struct("!f") float_struct.pack(f) return float_struct.unpack('?\x80\x00\x00')[0] which might the same as return float_struct.unpack1('?\x80\x00\x00') Andrew dalke at dalkescientific.com From john at hazen.net Wed Jun 8 18:57:15 2005 From: john at hazen.net (John Hazen) Date: Wed, 8 Jun 2005 15:57:15 -0700 Subject: poker card game revisited (code included) In-Reply-To: References: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> Message-ID: <20050608225714.GA8844@gate2.hazen.net> [Erik Max Francis] > > > Searching for straights and flushes is much better done by masks. Interesting. I've been thinking about playing with this stuff too, but hadn't considered masks. So each card has a representation: n bits for rank, then m bits for suit. 00000000000010 0001 = 2 clubs 01000000000000 1000 = K spades ... [flupke] > > As for straights, if i understand correctly, you make all possible > > straights of the cards in the hand and then see if one matches? Yeah, I originally thought that's what you meant, too. But if you take the scheme above, and sort the cards before you merge them into the hand-bits aggregate, then you can just have *one* mask for straights, and shift it down by a bit each time you check. So the best straight mask (A high) would be (ignoring suit bits): 10000000000000 01000000000000 00100000000000 00010000000000 00001000000000 Then this could be shifted right for a K-high straight: 01000000000000 00100000000000 00010000000000 00001000000000 00000100000000 I guess that means that an Ace has to have the following representation, since it can be both at the high and low end of a straight: 10000000000001 0100 = A hearts But this may mess with bit-counting shortcuts for other calculations... This is interesting to think about. Thanks for the pointer. I'm also going to look at pokersource, though I may put that off until I at least partially re-invent the wheel for learning purposes. -John From dstanek at dstanek.com Fri Jun 3 00:20:56 2005 From: dstanek at dstanek.com (David Stanek) Date: Fri, 3 Jun 2005 00:20:56 -0400 Subject: ANN: Cleveland Area Python Interest Group Message-ID: <20050603042056.GA8494@goliath.hsd1.oh.comcast.net> I am attempting to start a Cleveland (Ohio) Python Interest Group. This group is a revival of the very inactive Cleveland Python Meetup Group. If you are in the Cleveland area and are interested goto http://www.clepy.org for more information. -- David Stanek www.roninds.net GPG keyID #6272EDAF on http://pgp.mit.edu Key fingerprint = 8BAA 7E11 8856 E148 6833 655A 92E2 3E00 6272 EDAF -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mhuening at zedat.fu-berlin.de Mon Jun 27 06:54:37 2005 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Mon, 27 Jun 2005 12:54:37 +0200 Subject: turn text lines into a list In-Reply-To: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> Message-ID: <3ia430FkimuuU1@uni-berlin.de> Xah Lee (27.06.2005 12:33): > i have a large number of lines i want to turn into a list. > In perl, i can do > > @corenames=qw( > rb_basic_islamic > sq1_pentagonTile > sq_arc501Tile > sq_arc503Tile > ); > > use Data::Dumper; > print Dumper(\@corenames); > > ---------- > is there some shortcut to turn lines into list in Python? txt = """rb_basic_islamic sq1_pentagonTile sq_arc501Tile sq_arc503Tile""" print txt.splitlines() Matthias From fredrik at pythonware.com Mon Jun 20 08:27:17 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Jun 2005 14:27:17 +0200 Subject: utf8 and ftplib References: <1119267462.32655.236736750@webmail.messagingengine.com> Message-ID: Richard Lewis wrote: > OK, I'm still not getting this unicode business. obviously. > > aàáâã > eèéêë > iìíîï > oòóôõ > oùúûü > > > (If testing, make sure you save this as utf-8 encoded.) why? that XML snippet doesn't include any UTF-8-encoded characters. ::: > file = codecs.open(sys.argv[1], "r", "utf-8") > document = parse(file) > file.close() why do you insist on decoding the stream you pass to the XML parser, when you've already been told that you shouldn't do that? change this to: document = parse(sys.argv[1]) > print document.toxml(encoding="utf-8") this converts the document to UTF-8, and prints it to stdout. if you get gibberish, your stdout wants some other encoding. if you get "capital- A-with-tilde" gibberish, your stdout expects ISO-8859-1. try changing this to: print document.toxml(encoding=sys.stdout.encoding) > out_str = unicode2charrefs(document.toxml(encoding="utf-8")) this converts the document to UTF-8, and then translates the *encoded* data to character references as if the document had been encoded as ISO- 8859-1. this makes no sense at all, and results in an XML document full of "capital-A-with-tilde" gibberish. > i.e., does anyone else get two byte sequences beginning with > capital-A-with-tilde instead of the expected characters? since you've requested UTF-8 output, "capital A with tilde" is the expected result if you're directing output to an ISO-8859-1 stream. > the output file is still wrong. well, you're messing it up all by yourself. getting rid of all the codecs and unicode2charrefs nonsense will fix this: document = parse(sys.argv[1]) # parser decodes ... manipulate document ... file = open(..., "w") file.write(document.toxml(encoding="utf-8")) # writer encodes file.close() From steve at REMOVETHIScyber.com.au Fri Jun 10 11:09:41 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Jun 2005 01:09:41 +1000 Subject: without shell References: <11aj7vh2f0hqsd1@corp.supernews.com> Message-ID: On Fri, 10 Jun 2005 14:13:05 +0000, Grant Edwards wrote: > On 2005-06-10, Steven D'Aprano wrote: >> On Sun, 12 Jun 2005 23:16:35 +0530, km wrote: >> >>> hi all, >>> >>> can any linux command be invoked/ executed without using shell (bash) ? >> >> py> import os >> py> status = os.system("ls") >> >> Prints the output of ls and stores the exit code into status. > > It's done by invoking the user's SHELL and passing the string > "ls" to it. In the general case, invoking an unknown shell and > passing it a string is fraught with peril. Ah... you learn something new every day. I interpreted the original question as meaning "can Python execute arbitrary Linux commands without exiting the Python interpretor and dropping into a shell prompt?". -- Steven. From tjreedy at udel.edu Fri Jun 3 14:26:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Jun 2005 14:26:44 -0400 Subject: couple of new python articles on onlamp References: <42A08381.9070404@bellsouth.net> Message-ID: "Jeremy Jones" wrote in message news:42A08381.9070404 at bellsouth.net... > I've got a couple of new articles on ONLamp: > > Writing Google Desktop Search Plugins > http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html Wow, another use for Python. I should get this. Thanks. I would add the important fact ', written in Python' at the end of "One such plugin is Kongulo, a web spider. " Terry J. Reedy From pingveno at comcast.net Fri Jun 10 17:41:13 2005 From: pingveno at comcast.net (Pingveno) Date: Fri, 10 Jun 2005 14:41:13 -0700 Subject: re - multiple results Message-ID: I'm working on the Python Challenge (make sure to try it: http://www.pythonchallenge.com). One of the puzzles requires the use of regular expressions, but with multiple matches in the text. I tried to use re.findall(), but I only go one result instead of a list of results. >>> print re.findall(r"myexpression",text) ['AZBaCTR'] There should, of course, be several matches. What function should I use? Or is it not a function issue? Thanks, Pingveno From nephish at xit.net Tue Jun 14 01:44:34 2005 From: nephish at xit.net (nephish at xit.net) Date: 13 Jun 2005 22:44:34 -0700 Subject: stuck in cgi-image mess Message-ID: <1118727874.245133.250850@g49g2000cwa.googlegroups.com> i have an html form with a drop-down list that lists a bunch of images. how can i get my cgi script to load the image ? i have imported cgi and os text entered from a form and read from a file do ok, but i cant seem to get it to load an image. the form writes all of the entries as lines in a .txt file this file is selected later, all the lines are read, and based on the first line of the text file determines the name of the .gif image to load. is there a way to do this, i think i am getting all the ' and '' stuff confused. thanks. From peter at engcorp.com Fri Jun 17 08:43:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Jun 2005 08:43:26 -0400 Subject: Unbound names in __del__ In-Reply-To: References: Message-ID: Torsten Bronger wrote: > However, all of this is not pretty pythonic in my opinion. Is it > that exotic to want to call functions from within __del__? Yes, I think it probably is. In the few hundred thousand lines of Python code I've played a role in developing, we've used __del__ once, to my knowledge, and I believe it was not a critical use, just an expedient one. And I don't recall the last time I saw a __del__ in third-party code I was examining. What's your use case for del? -Peter From john106henry at hotmail.com Wed Jun 15 21:59:12 2005 From: john106henry at hotmail.com (John Henry) Date: 15 Jun 2005 18:59:12 -0700 Subject: Finding Word and switch focus to it In-Reply-To: References: Message-ID: <1118887152.009558.85660@g43g2000cwa.googlegroups.com> I tried the first part and works like a charm. I will read the post you cited. Thanks, -- John From lycka at carmen.se Thu Jun 30 06:24:18 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 30 Jun 2005 12:24:18 +0200 Subject: Boss wants me to program In-Reply-To: <1119988656.668457.202660@g43g2000cwa.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119988656.668457.202660@g43g2000cwa.googlegroups.com> Message-ID: <42C3C852.4020701@carmen.se> I think Python works on fairly antique hardware, whatever OS you use (as long as the OS works ok). You can get a DOS version of Python 2.2 at http://www.caddit.net/ , but I don't have any good suggestions for a UI then. This might work after some tweaking: http://www.effbot.org/zone/console-index.htm If you google for "python curses" you'll find info on that route, and if you go for a GUI solution on Windows or Linux, there are more routes than Tkinter. I'm not sure what to suggest on really old hardware though. Perhaps pyFLTK or FxPy are lighter than the typical alternatives. See also http://wiki.python.org/moin/GuiProgramming Unless we're talking about several installations, getting at least a Pentium III is obviously much cheaper than to spend several hours getting the program to work. For a dirt cheap system with several users, curses and terminals with a linux server is obviously hard to beat. A slightly more modern approach would be a web based app. From jmdeschamps at cvm.qc.ca Thu Jun 23 22:12:03 2005 From: jmdeschamps at cvm.qc.ca (jean-marc) Date: 23 Jun 2005 19:12:03 -0700 Subject: Thanks for PIL (and other stuff) Message-ID: <1119579123.611615.197720@g14g2000cwa.googlegroups.com> I was just reading on daily-python that PIL is 10 years old... So I wish it and its author(s) a good day, week, month, year and more! Really! Jean-Marc PS If I knew that Python had a anniversary date, I'd also write to thanks our BDFL (and authors)! But no such luck, so I'm restaining myself! ;-)) From chinook.nr at tds.net Sun Jun 26 03:36:58 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 26 Jun 2005 03:36:58 -0400 Subject: noob question References: <42BE37C0.3000306@maudit.net> Message-ID: <0001HW.BEE3D35A001A7944F0407550@news.gmane.org> On Sun, 26 Jun 2005 01:06:08 -0400, Matt Hollingsworth wrote (in article <42BE37C0.3000306 at maudit.net>): > Hello, > > Very new to python, so a noob question. When I've written stuff in > JavaScript or MEL in the past, I've always adopted the variable naming > convention of using a $ as the first character (no, I don't use perl, > never have). Not possible in python. What are some good options that > people commonly use so that they can easily and quickly identify > variable with just a glance? When I was writing stuff in SoftImage > XSI/JScript, many of the examples in the SDK used just a leading lower > case o, but I'd like somethign that's more visible. I'm not a super > advanced user and am just starting out in python (pretty much just > working my way through Learning Python, at around page 160 or so). > Seems like an _extremely_ elegent language that is very easy to read, so > I suppose it's not really as much of an issue as it is with other > languages. Still, I would like to see what other people do and what are > some good ideas for this kind of thing. > > Thank you for any and all ideas. > > cheers, > > -Matt > > Here is something I copied from somewhere (someone else might know the source): Summary of Naming Conventions Type Convention Example ----------------------------------------------------------------------------- function action_with_underscores find_all variable noun_with_underscores curr_index constant NOUN_ALL_CAPS ALLOWED_RNA_PAIRS class MixedCaseNoun RnaSequence public property MixedCaseNoun IsPaired private property _noun_with_leading_underscore _is_updated public method mixedCaseExceptFirstWordVerb stripDegenerate private method _verb_with_leading_underscore _check_if_paired really private data __two_leading_underscores __delegator_object_ref parameters that match properties SameAsProperty def __init__(data, Alphabet=None) factory function MixedCase InverseDict module lowercase_with_underscores unit_test Hope it does not come out too jumbled, Lee C From arazavi at swen.uwaterloo.ca Tue Jun 14 11:48:14 2005 From: arazavi at swen.uwaterloo.ca (Ali Razavi) Date: Tue, 14 Jun 2005 11:48:14 -0400 Subject: implicit variable declaration and access In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Mon, 13 Jun 2005 12:18:31 -0400, Ali Razavi wrote: > > >>Is there any reflective facility in python >>that I can use to define a variable with a >>name stored in another variable ? >>like I have : >>x = "myVarName" >> >>what can I do to declare a new variable with the name of the string >>stored in x. And how can I access that implicitly later ? > > > Any time you find yourself wanting to indirectly define variables like > this, the chances are you would get better results (faster, less security > risks, easier to maintain, easier to re-factor and optimise, more > readable) if you change the algorithm. > > Instead of: > > x = "myVarName" > create_real_variable(x, some_value) > print myVarName > > why not do something like this: > > data = {"myVarName": some_value} > print data["myVarName"] > > It is fast, clean, easy to read, easy to maintain, no security risks from > using exec, and other Python programmers won't laugh at you behind your > back > > I ain't writing a real program, just summarizing a few languages (Python, Smalltalk, Ruby, ...) meta programming facilities and compare them with each other, it will only be an academic paper eventually. Thus I am only trying out stuff, without worrying about their real world consequences. And yes you are right, I am not a Python programmer, well to be honest, I am not a real "any language" programmer, as I have never written any big programs except my school works, and I don't even intend to become one, Sorry it's just too boring and repetitive, there are much more exciting stuff for me in computer engineering and science than programming, so I will leave the hard coding job to you guys and let you laugh behind the back of whoever you want! Have a good one! From grante at visi.com Wed Jun 22 14:06:35 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 22 Jun 2005 18:06:35 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> Message-ID: <11bja5bienakv68@corp.supernews.com> On 2005-06-22, Scott David Daniels wrote: >> Fixing it is really quite trivial. It takes less than a dozen >> lines of code. Just catch the exception and handle it. > > Since you know it is quite trivial, and I don't, why not > submit a patch resolving this issue. Be sure to include tests > for all supported Python platforms. I'm working on it. I should have said it's trivial if you have access to the platforms to be supported. I've tested a fix that supports pickle streams generated under Win32 and glibc. That's using the "native" string representation of a NaN or Inf. A perhaps simpler approach would be to define a string representation for Python to use for NaN and Inf. Just because something isn't defined by the C standard doesn't mean it can't be defined by Python. -- Grant Edwards grante Yow! I'm shaving!! I'M at SHAVING!! visi.com From bogus@does.not.exist.com Thu Jun 30 10:15:02 2005 From: bogus@does.not.exist.com () Date: Thu, 30 Jun 2005 14:15:02 -0000 Subject: No subject Message-ID: #! rnews 2218 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 39 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Thu, 30 Jun 2005 13:53:07 GMT Xref: news.xs4all.nl comp.lang.python:384162 Peter Hansen writes: > Harry George wrote: > > "Adriaan Renting" writes: > >>Both VB and Python are easier to learn as the more powerful > >>languages, the price is that they lack features that make it easier to > >>manage large and complex projects. > > What is a large project, and what is Python missing that C++ and Java > > have for such tasks? > > But C++ and Java have features that *management* likes, thus making it > "easier to manage large projects". (That says nothing about whether > or not it makes it easier to produce quality code, successful > projects, happy customers, large profits, or any such silly > things... just that it's "easier to manage". ;-) > > Less facetiously: I have managed a large Python project or three, and > several large C++ projects (and, thankfully, no large Java projects) > and found Python quite up to the task. In fact, if anything the C++ > projects ended up more in danger of succumbing to the sheer weight of > the code than did the Python projects. But I attribute this more to > the fact that we had evolved to using agile approaches with the Python > projects than to any of those special features either present or > lacking in C++. > > Ultimately, manageability of a project is far and away more about the > people involved and the techniques used than it is about any single > technology involved. > > -Peter That's our experience too (and the reason I asked). I wonder if the OP will respond. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From rkern at ucsd.edu Thu Jun 30 18:11:12 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 15:11:12 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: <86slyza5hn.fsf@bhuda.mired.org> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> <86slyza5hn.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Harry George writes: > >>b) Installing distutils-aware python packages is trivial. I'd rather >>the energy which might go into a bigger std library go instead into >>helping projects which don't have distutils-style builds. > > How about integrating distutils and PyPI, so that distutils can > automatically download and install packages that are required by the > package it's currently installing? In other words, C-Python-AN. http://peak.telecommunity.com/DevCenter/EasyInstall -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From maxilys at SPAMCOP_tele2.fr Sat Jun 18 01:28:52 2005 From: maxilys at SPAMCOP_tele2.fr (Remi Villatel) Date: Sat, 18 Jun 2005 07:28:52 +0200 Subject: Loop until condition is true Message-ID: Hi there, There is always a "nice" way to do things in Python but this time I can't find one. What I'm trying to achieve is a conditionnal loop of which the condition test would be done at the end so the loop is executed at least once. It's some way the opposite of "while". So far, all I got is: while True: some(code) if final_condition is True: break # # What I don't find so "nice" is to have to build an infinite loop only to break it. Is there a better recipe? -- ================== Remi Villatel maxilys_ at _tele2.fr ================== From newsgroups at jhrothjr.com Mon Jun 27 22:35:42 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 27 Jun 2005 20:35:42 -0600 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> <11c166s2sh66b93@news.supernews.com> <1119923787.531336.292220@z14g2000cwz.googlegroups.com> Message-ID: <11c1ds3bmun2v5d@news.supernews.com> "Inkiniteo" wrote in message news:1119923787.531336.292220 at z14g2000cwz.googlegroups.com... >I see. So... what about sending HTML email? If i send HTML tagged text, > the client will be able to read it as HTML? > > For example, if i send an email with:
> Yo! will the client read a bold Yo! ? > > Because i can replace tabs with tables if this is possible. To send HTML, you definitely need a mimetype. Otherwise some clients will autodiagnose as HTML and attempt to render it, some won't. Strictly speaking, they shouldn't do autodetection. I also agree with Dan - HTML mail is evil, and I try to avoid it whenever possible. That's one of the major vectors for worms, viri and simliar malware. John Roth > From philippe at philippecmartin.com Thu Jun 9 18:44:40 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 09 Jun 2005 22:44:40 GMT Subject: howto send html mails using smtplib Message-ID: Hi, I have the following problem: 1) I can use smtplib to send text messages 2) I can generate html 3) I want to email the html and want it to be seen by the email client as html. However, when I receive the message, the email client displays it as text (code hereunder) - I assume it has to do with the MIMEText call but since I cannot see any MIMEhtml ..... Any clue ? Thanks Philippe #******************************************************************** def Mail(self,p_data): you = wx.GetTextFromUser('EMAIL ADDRESS','ID') if len(you) == 0: return self.__m_config = Config() self.__m_config.Load() me = self.__m_config.dict['ACCOUNT'] #me = 'philippecmartin at sbcglobal.net' host = self.__m_config.dict['SMTP'] s = smtplib.SMTP() s.connect(host) s.login(me,self.__m_config.GPW()) the_text = p_data msg = MIMEText(the_text) msg['To'] = you msg['Subject'] = self.__m_config.dict['TITLE'] msg['From'] = self.__m_config.dict['FROM'] s.sendmail(me, [you], msg.as_string()) self.__m_list = [] From contact at alanlittle.org Thu Jun 23 05:30:53 2005 From: contact at alanlittle.org (contact at alanlittle.org) Date: 23 Jun 2005 02:30:53 -0700 Subject: pydoc - suppressing builtins? Message-ID: <1119519053.138956.298930@z14g2000cwz.googlegroups.com> Is it possible to persuade pydoc not to include documentation for methods inherited from built-in classes? I have several classes that inherit from dict, and don't really need documentation thousands of lines long that consists mostly of dict's methods repeated multiple times. I'm sure I could qite easily write something to post-process the HTML files; just wondering if there might be an easier way. thanks Alan From peter at engcorp.com Sat Jun 18 15:16:36 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 15:16:36 -0400 Subject: Unbound names in __del__ In-Reply-To: <87is0bmvqt.fsf@wilson.rwth-aachen.de> References: <87mzpnmwpg.fsf@wilson.rwth-aachen.de> <87is0bmvqt.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: >>Torsten Bronger wrote: >>> keithley = GpibInstrument(14) >>> keithley.write("*IDN?") >>> print keithley.read() >> [on using atexit] > However, this doesn't close sessions while the program is running. > If the programmer has the above code in a function which is called > repeatedly, he may run into trouble. IIRC my current VISA DLL has > only 256 session slots. Hmm... it sounds to me as though the design of this DLL is such that one is expected to hold a session open for the duration of the application. So instead of creating new GpibInstrument objects as needed, then just sort of dropping them, the programmers would have to create the required instrument objects at the start of the program and reuse them when needed. But that's as far as my thoughts take me on this, without working directly with you. I guess you'll have to explore the __del__ approach through to its conclusion before you'll be confident it won't work (or perhaps you'll find a solution after all!). -Peter From tundra at tundraware.com Thu Jun 23 14:06:51 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jun 2005 14:06:51 EDT Subject: OT: Re: Looking For Geodetic Python Software In-Reply-To: <3hvrhjFj3qfmU1@uni-berlin.de> References: <447po2-iqt.ln1@eskimo.tundraware.com> <3hvrhjFj3qfmU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Tim Daneliuk wrote: > >> Casey Hawthorne wrote: >> >>> >>> Do your planes fly over the earth's surface or through the ground? >> >> >> >> Why do you presume this has anything to do with airplanes? >> > > That was supposed to be a funny remark regarding that your > "straight-line-distance" makes no sense at all - because that would mean > that you'd have to go underground. So it has no real-world-application - > unless you actually have underground-planes ;) > > Diez Huh? When traversing along the surface of the earth, it's curvature is relevant in computing total distance. An airplane flies more-or-less in a straight line above that curvature. For sufficiently long airplane routes (where the ascent/descent distance is trivial compared to the overall horizontal distance traversed), a straight line path shorter than the over-earth path is possible. That's why I specified the desire to compute both path lengths. Where's the humor? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From user at unknown.invalid Thu Jun 30 19:07:57 2005 From: user at unknown.invalid (Koncept) Date: Thu, 30 Jun 2005 19:07:57 -0400 Subject: OOP help needed incorporating existing modules in class Message-ID: <300620051907570695%user@unknown.invalid> I want to incorporate the datetime and other modules into my class. I am new to Python and would really appreciate some help doing this. class FooBar: def getDate(self): return ^^^ how do I do something like this? -- Koncept << "The snake that cannot shed its skin perishes. So do the spirits who are prevented from changing their opinions; they cease to be a spirit." -Nietzsche From kay.schluehr at gmx.net Sat Jun 11 01:43:45 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Jun 2005 22:43:45 -0700 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118429907.140244.298390@g43g2000cwa.googlegroups.com> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> Message-ID: <1118468625.619330.12540@f14g2000cwb.googlegroups.com> fuzzylollipop wrote: > There are 2 things he can do. > > 1. Get your resume ready and approach the CEO or whomever and say. Why > is this happening? Since I can guarantee you they have already decided > to port this app to Java. The CEO is probably indifferent about particular technology issues but certainly not about money. Trashing a ready to use project ( it does not seem to be a functional prototype ) is clearly a waste of effort and time. Offer him to draw an architecture fulfilling the requirements of the "enterprise solution" reusing existing components that is much less expensive. Arguing that a Python project definitely needs less programmers than the Java counterpart ( which is very cost effective because you need less management and administration to lead them - remember that a programmer is always cheap compared to a manager ). A new ambitious manager wants to enforce changes. That's part of the game and one has to assume this. Remember also that there is not only a lot of hype and buzz around Java technologies but one can also spread adjectives like "agile" in the debate and buzz back ( doing politics ). There's still a lot to exploit in this direction: the "agile" company/department relies on lightweight methodologies, technologies, languages, thinking, eating, drinking and pissing. O.K. if the boss is nervous, carefull and weak and goes directed by it's servants one may be off-chance. Kay From jan.danielsson at gmail.com Mon Jun 6 18:36:32 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Tue, 07 Jun 2005 00:36:32 +0200 Subject: Creating file of size x Message-ID: <42a4cea6$1@griseus.its.uu.se> Hello all, Is there any way to create a file with a specified size? From steven.bethard at gmail.com Mon Jun 27 15:12:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Jun 2005 13:12:27 -0600 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > For my part, ctypes seems like a suggestion to start with. I believe this has been discussed somewhere before and the conclusion was that ctypes should not be a candidate for inclusion in the Python stdlib because people don't want things in the stdlib that can make Python segfault. STeVe From hicinbothem at ems.att.com Wed Jun 29 10:29:09 2005 From: hicinbothem at ems.att.com (hicinbothem at ems.att.com) Date: 29 Jun 2005 07:29:09 -0700 Subject: Programmers Contest: Fit pictures on a page Message-ID: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> GLOSSY: The Summer Programmer Of The Month Contest is underway! Deadline is September 30, 2005 http://dinsights.com/POTM -------------------------------------------------------------------------------- I love taking digital pictures, but that nice glossy photo paper is expensive! So when my lovely wife asks for prints of a bunch of pictures, I always try and fit them onto a single piece of paper. The summer POTM challenges you to write a program that will place up to 26 pictures on a sheet of paper with the least amount of leftover space. -------------------------------------------------------------------------------- The Programmer Of The Month (POTM) is a just-for-fun programming contest with an active forum and over 1100 members (we usually get 40-50 entries for each POTM challenge). Supported languages include C/C++/Perl/Ruby/PHP/Python/awk/shell. Emphasis is on the algorithms and the joy of programming. If it sounds like fun, please visit at http://dinsights.com/POTM ... =Fred (a.k.a. The POTM-MASTER) From brettk at gmail.com Tue Jun 21 18:59:03 2005 From: brettk at gmail.com (brettk at gmail.com) Date: 21 Jun 2005 15:59:03 -0700 Subject: Getting/Saving email attachments w/ poplib and email modules Message-ID: <1119394743.478968.278290@g49g2000cwa.googlegroups.com> Hello All, Here's what I'm trying to do: I need to connect to a pop3 server, download all messages, and copy all of the attachments into a specific directory. The actual email message is unimportant. Now, I've found plenty of examples that strip the attachments from an email message, but most (if not all) of them take a file parameter. My question is this: How can i retrieve an email message via poplib and pass it to email.message_from_string()? This is essentially what i'm doing now, ############## import email import poplib mimes = ["image/tif","image/tiff","images/x-tif","image/x-tiff", "application/tif","application/tiff","application/x-tif", "application/x-tiff"] def WriteAttachment(msg): docs = [(part.get_filename(),part.get_payload(decode=True)) for part in msg.get_payload() if part.get_type() in mimes] for name,data in docs: f = file(name,'wb') f.write(data) f.close() ms = poplib.POP3(server) ms.user(uname) ms.pass_(passw) msgcount = len(ms.list()[1]) for i in range(msgcount): for j in ms.retr(i+1)[1]: msg = email.message_from_string(j) WriteAttachment(msg) ################################## I'm sure i'm missing something pretty simple, i just need a slap in the right direction... TIA From qscomputing at gmail.com Thu Jun 2 09:45:18 2005 From: qscomputing at gmail.com (qscomputing at gmail.com) Date: 2 Jun 2005 06:45:18 -0700 Subject: Two questions Message-ID: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Hi, I've developed in several other languages and have recently found Python and I'm trying to use it in the shape of the PythonCard application development tool. My two questions: 1. What is the easiest way to create a for loop in the style I'm used to from Delphi ie: for I:=0 to 2 do begin //code end; 2. Philospohy(sp?) aside, I could potentially want to create a binary-only distribution of my finished apps. I noticed the documentation on .pyc files: how do I create these and, aside from being basically read-only, are they used just like ordinary .py source files? And can they be easily reverse-engineered? Thanks, - QS Computing. From greg_miller at nexpress.com Wed Jun 29 08:20:36 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 29 Jun 2005 05:20:36 -0700 Subject: COM problem .py versus .exe In-Reply-To: References: Message-ID: <1120047636.453205.244840@g49g2000cwa.googlegroups.com> I put you code snippet into my code, running it from the desktop PC gave me the following output ( I added a print statement ): . . . winmgmts: TTTTTTTTTTTTTTTTT i.Caption is \\rocps00101\ROCPR001 TTTTTTTTTTTTTTTTT i.Caption is \\ROCPS00101\ROCPR024 TTTTTTTTTTTTTTTTT i.Caption is \\ROCPS00101\ROCPR070 TTTTTTTTTTTTTTTTT i.Caption is \\rocps00101\ROCPR143 so that appears to work great, I took out the for i in c.Win32_Printer.... statement, built the executable, but still get the exact same error on the embedded PC. It errors as soon as the import wmib call is made, so it never gets to: wmi._DEBUG = 1 moniker = "winmgmts:" c = wmi.WMI (moniker=moniker) that you recommended. I also copied my python24 directory from the desktop PC to the embedded PC. Then added the path variable for Python. I ran the win32com\client\makepy.py file using our target dll. That seemed to work okay. I got the expected output. That didn't seem to make a difference to the executable, same error was generated. WMIB.pyc is in the library.zip file that py2exe builds, so I know that it is getting into the executable correctly. I will check around to see if the win32 calls you were referring to made it into the pywin32 package. I'll also look at ctypes again, I had originally looked at using ctypes but your wmi package simplified things so much. Thanks again for you help. From qwweeeit at yahoo.it Fri Jun 17 05:49:05 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 17 Jun 2005 02:49:05 -0700 Subject: How to right align IPaddress? In-Reply-To: References: <1118740170.9602.236315256@webmail.messagingengine.com> Message-ID: <1119001745.599008.32800@g14g2000cwa.googlegroups.com> Hi, the solution is a little more involved, if you want to "right justify" each of the four components of IP number: import sys try: . sIPnumber=sys.argv[1] except: . sys.exit(-1) list_lPcomponents=sIPnumber.split('.') sRJ=''" for n in list_IPcomponents: . sRJ+=n.rjust(3)+'.' print sRJ[:-1] Bye. From dalke at dalkescientific.com Sat Jun 4 02:49:26 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 04 Jun 2005 06:49:26 GMT Subject: how to get name of function from within function? References: Message-ID: I'm with Steven Bethard on this; I don't know what you (Christopher J. Bottaro) are trying to do. Based on your example, does the following meet your needs? >>> class Spam(object): ... def funcA(self): ... print "A is called" ... def __getattr__(self, name): ... if name.startswith("_"): ... raise AttributeError, name ... f = get_function(name) ... if f is not None: ... return f ... raise AttributeError, name ... >>> def get_function(name): ... return globals().get(name + "IMPL", None) ... >>> x = Spam() >>> x.funcA() A is called >>> x.funcB() Traceback (most recent call last): File "", line 1, in ? File "", line 10, in __getattr__ AttributeError: funcB >>> def funcBIMPL(): ... print "Calling all bees" ... >>> x.funcB() Calling all bees >>> Confused-ly-your's Andrew dalke at dalkescientific.com From jeremy+plusnews at jeremysanders.net Tue Jun 21 05:40:09 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Tue, 21 Jun 2005 10:40:09 +0100 Subject: Python choice of database References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: On Mon, 20 Jun 2005 23:42:21 -0800, EP wrote: > until my records (text - maybe 50KB average) unexpectedly blossomed into > the 10,000-1,000,000 ranges. If I or someone else (who innocently doesn't > know better) opens up one of the directories with ~150,000 files in it, > the machine's personality gets a little ugly (it seems buggy but is just > very busy; no crashing). Under 10,000 files per directory seems to work > just fine, though. Yes. Programs like "squid" use subdirectories to avoid this problem. If your key is a surname, then you can just use the first letter to divide the names up, for instance, or part of the hash value. Many Linux FSs can cope with lots of files, but it doesn't hurt to try to avoid this. Jeremy From python at rcn.com Sat Jun 4 05:49:14 2005 From: python at rcn.com (Raymond Hettinger) Date: 4 Jun 2005 02:49:14 -0700 Subject: how to get name of function from within function? References: Message-ID: <1117878554.505475.95390@g44g2000cwa.googlegroups.com> [Christopher J. Bottaro] >> def myFunc(): >> print __myname__ >> >>> myFunc() >> 'myFunc' Perhaps the __name__ attribute is what you want: >>> def myFunc(): print myFunc.__name__ >>> myFunc() myFunc From twic at urchin.earth.li Sat Jun 25 15:01:38 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 25 Jun 2005 20:01:38 +0100 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: On Fri, 24 Jun 2005, Roy Smith wrote: > Tom Anderson wrote: > >> The one thing i really do miss is method overloading by parameter type. >> I used this all the time in java > > You do things like that in type-bondage languages I love that expression. I think it started out as 'bondage and discipline languages', which is even better. I'm going to start referring to python as a 'sluttily typed' language. > like Java and C++ because you have to. Can you give an example of where > you miss it in Python? No. I don't generally go around keeping a list of places where i miss particular features or find particular warts irritating. Still, my medium-term memory is not completely shot, so i assume i haven't missed it much in the last couple of days! > If you want to do something different based on the type of an argument, > it's easy enough to do: > > def foo (bar): > if type(bar) == whatever: > do stuff > else: > do other stuff > > replace type() with isistance() if you prefer. Yeah, i'm well aware that this is possible - what it's not is a clean solution. If i was into writing boilerplate, i'd be using C. Also, this gets really nasty if you want to overload on multiple variables. Also, it actually falls down really badly in combination with duck typing - you can't use isinstance to ask if an object looks like a file, for example, only if it really is a file. Sure, you can do a bunch of hasattrs to see if it's got the methods it should have, but that doesn't tell you for certain it's a file, and it's a pain in the arse to write. In a typed language, you'd just ask if it implemented the Channel (for example) interface. >> No, it's not really possible in a typeless language, > > Python is not typeless. It's just that the types are bound to the > objects, not to the containers that hold the objects. No. Types are properties of variables; the property that objects have is called class. Python has classes but not types. I realise that many, even most, people, especially those using typeless languages like python or smalltalk, use the two terms interchangeably, but there's a real and meaningful distinction between them. I may be the last person alive who thinks it's an important distinction, but by god i will die thinking it. So let's recognise that we have slightly different terminologies and not argue about it! tom -- Why do we do it? - Exactly! From bdesth.quelquechose at free.quelquepart.fr Tue Jun 14 19:30:30 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 15 Jun 2005 01:30:30 +0200 Subject: Controlling assignation In-Reply-To: <42AE8657.9070806@imag.fr> References: <42aded8f$0$31916$636a15ce@news.free.fr> <42AE8657.9070806@imag.fr> Message-ID: <42af62ce$0$17060$626a14ce@news.free.fr> Xavier D?coret a ?crit : > Bruno Desthuilliers a ?crit : > (snip) >> I really wonder what it can be ??? > > It's the ability to develop the equivalent of GeoNext (and much more) in > Python with a very nice syntax. This is nice, but this does not explain the why of your code snippet. >> >> You could achieve the same effect with: >> >> class A( object): >> def __init__(self, value): >> self.value = value >> >> a = A(3) >> a.value = 4 >> a.value >> => 4 >> > > Of course, and even simpler ;-) > print "4" of course !-) > More seriously, try to do this with your simpler approach. > > a = A(4) > b = A(lambda : a.x+5) > a.x = 2 > > print b.x # I want this to be 7, not 9 I may miss the point, but what about: class A(object): def __init__(self, x): self.x = x def _getx(self): if callable(self._x): return self._x() else: return self._x def _setx(self, x): self._x = x x = property(_getx, _setx) a = A(4) b = A(lambda : a.x+5) a.x = 2 print "b.x is", b.x #... and now for the fine part: del a b.x But what, your solution behaves just the same. >> Ever googled for "evolution of a programmer" ?-) >> > Not to brag, but I think I know what programming is. I don't have any reason to doubt it. But do you know what not programming is ?-) > C'est bien un commentaire de francais ca ;-) Meuhnon From rtomek at ceti.pl Fri Jun 10 06:30:33 2005 From: rtomek at ceti.pl (Tomasz Rola) Date: Fri, 10 Jun 2005 12:30:33 +0200 (CEST) Subject: without shell In-Reply-To: <20050612174635.GA20992@mrna.tn.nic.in> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sun, 12 Jun 2005, km wrote: > hi all, > > can any linux command be invoked/ executed without using shell (bash) ? > what abt security concerns ? Ops, I missed the word "command" when reading your mail for the first time, and this changes some parts of my previous answer and makes it shorter: There is an execve system call. You don't need neither sh, nor the libc to run programs. It's described in section 2 of manpages. The rest of the answer you can get from my previous post. Sorry if I went a bit offtopic in my previous mail. Shouldn't watch tv and write mails at the same time. > regards, > KM Regards, Tomasz Rola - -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** -----BEGIN PGP SIGNATURE----- Version: PGPfreeware 5.0i for non-commercial use Charset: noconv iQA/AwUBQqlr0RETUsyL9vbiEQIocwCfVh1SsT+RegTaxvNjlsCl8FYupe8AoLH5 qci3LXS1w8bq1ZqH7EKL1HuT =0WoY -----END PGP SIGNATURE----- From tzot at sil-tec.gr Tue Jun 28 09:17:01 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 16:17:01 +0300 Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> Message-ID: <5aj2c11l5vl4qds031uj7ucikikcf7uvji@4ax.com> On 27 Jun 2005 20:13:41 -0700, rumours say that "Brett Hoerner" might have written: >Christ, thanks. When you install Windows it should pop up first thing >and ask if you want to be annoyed, Y/N. When you agree to the EULA of Windows, you implicitly say yes to "do you want to be annoyed"? >Well, that solves my sound problem (thanks again), now if only I could >stretch the window horizontally. Thats much less of a problem though, >this is at least usable now. Hm... right-click the cmd.exe window's title bar (or click on the top-left icon, or press Alt-Space), go to Properties, Layout tab, Window Size, Width. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From greg at cosc.canterbury.ac.nz Tue Jun 14 00:04:01 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Tue, 14 Jun 2005 16:04:01 +1200 Subject: circular import Module In-Reply-To: References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Message-ID: <3h739uFfd4fmU1@individual.net> Magnus Lycka wrote: > Due to the cycle, you can never use file1 without > file2 or vice versa. Why do you then want it to be > two different modules instead of one? Perhaps because it would then be too big and unwieldy to maintain? Sometimes there are legitimate reasons for mutually-dependent modules. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From duncan.booth at invalid.invalid Wed Jun 1 10:02:32 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2005 14:02:32 GMT Subject: working with pointers References: Message-ID: Leif K-Brooks wrote: > Duncan Booth wrote: >> The constant integers are created in advance, not when you do the >> assignment. > > But that's just an optimization, not Python's defined behavior. It seems > more useful to me to think of all integers as being created at > assignment time, even if CPython doesn't actually do that. > Alternatively think of all integers as existing all of the time, whether or not they are referenced. Yes, it is just an optimisation, but it is one which results in an observable difference in behaviour. i.e. if all integers are created as they are needed you will never share integers. Of course, if all integers existed all of the time then I guess you might expect 'a==b' to always imply 'a is b', so my interpretation is differently inaccurate. From sjmachin at lexicon.net Mon Jun 13 04:36:33 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 13 Jun 2005 18:36:33 +1000 Subject: new string function suggestion In-Reply-To: <7fare.27429$J12.6708@newssvr14.news.prodigy.com> References: <7fare.27429$J12.6708@newssvr14.news.prodigy.com> Message-ID: <42ad4591@news.eftel.com> Andy wrote: > What do people think of this? > > 'prefixed string'.lchop('prefix') == 'ed string' > 'string with suffix'.rchop('suffix') == 'string with ' > 'prefix and suffix.chop('prefix', 'suffix') == ' and ' > > The names are analogous to strip, rstrip, and lstrip. But the functionality > is basically this: > > def lchop(self, prefix): > assert self.startswith(prefix) > return self[len(prefix):] > > def rchop(self, suffix): > assert self.endswith(suffix) > return self[:-len(suffix] > > def chop(self, prefix, suffix): > assert self.startswith(prefix) > assert self.endswith(suffix) > return self[len(prefix):-len(suffix] > > The assert can be a raise of an appropriate exception instead. I find this > to be a very common need, I'm not sure whether I should be surprised or not. I've never felt the need for such a gadget. I don't even recall seeing such a gadget in other languages. One normally either maintains a cursor (index or pointer) without chopping up the original text, or splits the whole text up into tokens. AFAICT, most simple needs in Python are satisfied by str.split or re.split. For the special case of file paths, see os.path.split*. There are also various 3rd party parsing modules -- look in PyPI. > and often newbies assume that the > strip/lstrip/rstrip family behaves like this, but of course they don't. > > I get tired of writing stuff like: > > if path.startswith('html/'): > path = path[len('html/'):] > elif s.startswith('text/'): > path = path[len('text/'):] > So create a function (example below) and put it along with others in a module called (say) andyutils.py ... def chop_known_prefixes(path, prefixes): for prefix in prefixes: if path.startswith(prefix): return path[len(prefix):] return path By the way, what do you do if path doesn't start with one of the "known" prefixes? > It just gets tedious, and there is duplication. Instead I could just write: > > try: > path = path.lchop('html/') > path = path.lchop('text/') > except SomeException: > pass > In the event that path contains (say) 'html/text/blahblah...', this produces 'blahblah...'; the original tedious stuff produces 'text/blahblah...'. > Does anyone else find this to be a common need? Has this been suggested > before? You can answer that last question yourself by googling comp.lang.python ... From peter at engcorp.com Fri Jun 24 09:09:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 09:09:32 -0400 Subject: howto load and unload a module In-Reply-To: <42BC0495.9080900@lexicon.net> References: <42BC0495.9080900@lexicon.net> Message-ID: <36adnXL3_djXmyHfRVn-tA@powergate.ca> John Machin wrote: > Peter Hansen wrote: [sample code] > Ummm ... doesn't appear to scale well for multiple modules and multiple > attributes & functions. It certainly wouldn't! :-) I was posting mainly to elicit more information, since clearly you wouldn't get far hardcoding all the names you were interested in. (It's hard to judge a poster's level of expertise in Python without any example code from him. That makes it too likely to go way above the head of the poster, and possibly provide a much more complex solution than he really needs.) > Try something like this (mostly tested): > > modules = ['foomod', 'barmod', 'brentstr', 'zotmod'] > attrs = ['att1', 'att2', 'att3', 'MyString'] > funcs = ['fun1', 'fun2', 'fun3'] > # the above could even be read from file(s) > for modname in modules: > try: > mod = __import__(modname) > except ImportError: > print "module", modname, "not found" > continue > for attrname in attrs: > try: > attr = getattr(mod, attrname) > except AttributeError: > print "module %s has no attribute named %s" % \ > (modname, attrname) > continue > # check that attr is NOT a function (maybe) > for funcname in funcs: > pass > # similar to above but check that it IS a function Of course, one could simply hand the man a complete answer... ;-) -Peter From grante at visi.com Fri Jun 10 10:37:23 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 10 Jun 2005 14:37:23 -0000 Subject: without shell References: Message-ID: <11aj9d3fga9or8b@corp.supernews.com> On 2005-06-10, Mage wrote: >>py> file_list = os.popen("ls").read() >> >>Stores the output of ls into file_list. >> > These commands invoke shell indeed. Under Unix, popen will not invoke a shell if it's passed a sequence rather than a single string. -- Grant Edwards grante Yow! I was in EXCRUCIATING at PAIN until I started visi.com reading JACK AND JILL Magazine!! From grante at visi.com Fri Jun 17 21:49:32 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 01:49:32 -0000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> Message-ID: <11b6vdcnqdnsm4a@corp.supernews.com> On 2005-06-18, cpunerd4 wrote: > I've guessed that python is purely an interpreted language unless its > compiled into another language (ie. it needs python installed in order > to run programs). Is this correct? It's just like Java. It's compiled into bytecode and then the bytecode is executed on a virtual machine. > If it is, I guess my plan of action would be to use python > embeded in java applets. There is a Python compiler (usually refered to as Jython) that generates Java bytecode for execution on a JVM, so that might be of interest. -- Grant Edwards grante Yow! I like the IMPUDENT at NOSE on that car... Are you visi.com a TEEN-AGER? From jan.danielsson at gmail.com Mon Jun 13 20:44:39 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Tue, 14 Jun 2005 02:44:39 +0200 Subject: Going crazy... Message-ID: <42ae2729$1@griseus.its.uu.se> Hello all, I'm 100% sure that I saw an example which looked something like this recently: >>> a=(1, 2, 3, 4, 5, 6) >>> b=(2, 3, 6) >>> a - b (1, 4, 5) The only new language I have been involved in lately is Python. Is my memory failing me, or have I seen such an Python-example somewhere? If so: Where; or more importantly: How does it work? I just tried typing the above in Python, and it - obviously - doesn't work, so it must be some other syntax. From darkpaladin79 at hotmail.com Thu Jun 9 02:40:12 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 02:40:12 -0400 Subject: identifying 64-bit Windows from 2.3.5? In-Reply-To: Message-ID: >From: Steven Knight >To: python-list at python.org >Subject: identifying 64-bit Windows from 2.3.5? >Date: Wed, 8 Jun 2005 23:51:15 -0400 (EDT) > >If I have installed 2.3.5 from the python.org Windows installer, can >any one point me to a run-time way to identify whether I'm running on >a 32-bit vs. 64-bit version of Windows XP, given that Python itself was >built on/for a 32-bit system? > >I hoped sys.getwindowsversion() was the answer, but it returns the same >platform value (2) on both 32-bit and 64-bit systems. sys.platform >("win32") and sys.maxint are both set at compile time. Things like >os.uname() aren't on Windows. > >Can some Windows-savvy Pythonista point me to some way to distinguish >between these two? > >Thanks, > > --SK >-- >http://mail.python.org/mailman/listinfo/python-list I really don't think it matters too much which one you have, I have 64 bit and it works fine. -Ivan _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From fumanchu at amor.org Tue Jun 28 17:02:35 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 28 Jun 2005 14:02:35 -0700 Subject: Debugger Confusion Message-ID: <3A81C87DC164034AA4E2DDFE11D258E37724DE@exchange.hqamor.amorhq.net> Rex Eastbourne wrote: > I'm a little confused about which debugging utilities do what, and > which I should use for my Python code. I'd like to be able to step > through my code, insert breakpoints, etc. I haven't been able to do > this yet (I'm using Emacs on Windows). I have seen references to GDB, > GUD, PDB, and others. Which ones do I need? 1. At the point you would like to start the debugger, insert the following 2 lines: import pdb pdb.set_trace() 2. Run your script from the command line. 3. When your script executes the above lines, the pdb debugger will start up, and give you a prompt. Type 'h' at the prompt (and hit 'enter'), and you'll be shown a list of pdb commands. 's' to step through your code, 'c' to continue processing (and stop the debugger, essentially). The prompt is interactive, so you can inspect program variables as you like. Start with that, and come back if you have any more questions. :) Robert Brewer System Architect Amor Ministries fumanchu at amor.org From roy at panix.com Wed Jun 15 16:07:56 2005 From: roy at panix.com (Roy Smith) Date: 15 Jun 2005 16:07:56 -0400 Subject: Does Python cause tides? References: <42AFB8FD.1060504@REMOVEMEcyber.com.au> Message-ID: Terry Hancock wrote: > is the statement "Viruses are made of DNA" true, or false? False. Viruses were made of Word macros :-) From david.baelde at ens-lyon.fr Sat Jun 11 13:25:52 2005 From: david.baelde at ens-lyon.fr (David Baelde) Date: Sat, 11 Jun 2005 19:25:52 +0200 Subject: Abstract and concrete syntax References: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Message-ID: >>> You can do stuff like this: lambda x: x and 2 or 3 >> lambda x: {True:2,False:3}.get(bool(a)) And by the way, I just noticed that this kind of hack is essentially "pushing the control (statement) inside expressions"... People should really admit that statements are expressions and stop twist their mind. I sure can write unreadable python without statement-as-expressions, and this is an example of it. From cam.ac.uk at mh391.invalid Fri Jun 10 19:59:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 11 Jun 2005 00:59:45 +0100 Subject: re - multiple results In-Reply-To: References: Message-ID: Pingveno wrote: > I'm working on the Python Challenge (make sure to try it: > http://www.pythonchallenge.com). One of the puzzles requires the use of > regular expressions, but with multiple matches in the text. I tried to > use re.findall(), but I only go one result instead of a list of results. > >>>>print re.findall(r"myexpression",text) > > ['AZBaCTR'] > > Or is it not a function issue? Works for me. Although I usually prefer this idiom: re_something = re.compile(r"pattern") re_something.findall(text) You're doing something else wrong. -- Michael Hoffman From philippe at philippecmartin.com Sat Jun 11 15:43:14 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 11 Jun 2005 19:43:14 GMT Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: This is the never ending story of the cyclic (I'm being redundant) life cycle of many companies: R&D driven versus Marketing driver. My belief is that none work as the trades do not attempt to reach the same goal: 1) R&D should not try to define products 2) Marketing should not try to impose the tools/means necessary to implement the products they have defined. I know that does not help flyingfred0 wrote: > A small software team (developers, leads and even the manager when he's > had time) has been using (wx)Python/PostgreSQL for over 2 years and > developed a successful 1.0 release of a client/server product. > > A marketing/product manager has brought in additional management and > "architecture" experts to propose moving the entire thing to a Java > (application server) platform for the next release. They want a > "scalable, enterprise solution" (though they don't really know what that > means) and are going crazy throwing around the Java buzzwords (not to > mention XML). > > The developers (including myself) are growing uneasy; the management is > continuing to push their requirements and ignore the engineers. I think > there's still hope, but I'm at a loss for ideas beyond pointing out the > success stories of Python and Zope and language comparisons between > Python and Java. > > What experiences have those in the Python community had in these kinds > of situations? From peterbe at gmail.com Tue Jun 14 07:01:58 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 14 Jun 2005 04:01:58 -0700 Subject: Hopefully simple regular expression question Message-ID: <1118746918.581184.5470@g49g2000cwa.googlegroups.com> I want to match a word against a string such that 'peter' is found in "peter bengtsson" or " hey peter," or but in "thepeter bengtsson" or "hey peterbe," because the word has to stand on its own. The following code works for a single word: def createStandaloneWordRegex(word): """ return a regular expression that can find 'peter' only if it's written alone (next to space, start of string, end of string, comma, etc) but not if inside another word like peterbe """ return re.compile(r""" ( ^ %s (?=\W | $) | (?<=\W) %s (?=\W | $) ) """% (word, word), re.I|re.L|re.M|re.X) def test_createStandaloneWordRegex(): def T(word, text): print createStandaloneWordRegex(word).findall(text) T("peter", "So Peter Bengtsson wrote this") T("peter", "peter") T("peter bengtsson", "So Peter Bengtsson wrote this") The result of running this is:: ['Peter'] ['peter'] [] <--- this is the problem!! It works if the parameter is just one word (eg. 'peter') but stops working when it's an expression (eg. 'peter bengtsson') How do I modify my regular expression to match on expressions as well as just single words?? From peter at engcorp.com Sat Jun 11 13:24:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Jun 2005 13:24:14 -0400 Subject: Controlling a generator the pythonic way In-Reply-To: References: Message-ID: Thomas Lotze wrote: > Which is, as far as the generator code is concerned, basically the same as > passing a mutable object to a (possibly standalone) generator. The object > will likely be called self, and the value is stored in an attribute of it. Fair enough, but who cares what the generator code thinks? It's what the programmer has to deal with that matters, and an object is going to have a cleaner interface than a generator-plus-mutable-object. > Probably this is indeed the best way as it doesn't require the programmer > to remember any side-effects. > > It does, however, require a lot of attribute access, which does cost some > cycles. Hmm... "premature optimization" is all I have to say about that. -Peter From slick_mick_00 at hotmail.com Thu Jun 2 10:34:30 2005 From: slick_mick_00 at hotmail.com (Michael) Date: Thu, 2 Jun 2005 14:34:30 +0000 (UTC) Subject: wxPython Message-ID: Hi, I've got a question about wxPython, wheres the best place to ask?? Mike From rschroev_nospam_ml at fastmail.fm Wed Jun 29 04:39:44 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 29 Jun 2005 08:39:44 GMT Subject: Newbie: Explain My Problem In-Reply-To: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> References: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> Message-ID: ChuckDubya at gmail.com wrote: > Code: > [snip] > else: > counter = counter - 1 > print > print "The number is greater than your guess." > print "You have", counter, " chances left to guess the number." > guess = (raw_input("Your guess is ")) The above line is incorrect: it should be guess = int(raw_input("Your guess is ")) -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From grante at visi.com Fri Jun 24 21:28:41 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Jun 2005 01:28:41 -0000 Subject: Newbie question: how to keep a socket listening? References: <1119637288.536579.249340@z14g2000cwz.googlegroups.com> <11bok3btkedg151@corp.supernews.com> <1119660879.852664.167100@f14g2000cwb.googlegroups.com> Message-ID: <11bpcq94635iod2@corp.supernews.com> On 2005-06-25, Peter Hansen wrote: > You *may* correct, mainly because the OP's code doesn't appear > to spawn off new threads to handle the client connections, > which means he can handle only one connection at a time. > Specifically, while he is talking to one client he is not also > in an accept() call on the server socket, which means there > will be (because of the listen(1) call) only a single pending > connection allowed in the backlog. But when he closes that connection, he calls accept again. And it's at that point where he tries to connect and can't. I think. Can the program be pared down to something smaller that demonstrates the problem? > I haven't attempted a thorough analysis... just this much, > trying to see whether it is obvious that the listen(1) is at > fault -- and it's not obvious. I thought this response might > clarify the meaning of listen(1) a little bit for some folks > nevertheless. He could change the 1 to a larger number and see if the behavior changes. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From pmaupin at gmail.com Sun Jun 12 22:21:03 2005 From: pmaupin at gmail.com (pmaupin at gmail.com) Date: 12 Jun 2005 19:21:03 -0700 Subject: BBC R&D White Paper on Kamaelia Published (Essentially a framework using communicating python generators) In-Reply-To: <42ab5b17$0$2046$ed2e19e4@ptn-nntp-reader04.plus.net> References: <42ab5b17$0$2046$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <1118629263.552489.236130@f14g2000cwb.googlegroups.com> > I'm posting a link to this since I hope it's of interest to people here :) > > I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework, > and it's been published as a BBC R&D White Paper and is available here: > > * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml I enjoyed the paper. I don't have time to play with the code right now, but it sounds like fun. I do have one question -- in practice, how difficult have you found it that Python generators don't maintain separate stacks? Regards, Pat From grante at visi.com Fri Jun 10 13:43:53 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 10 Jun 2005 17:43:53 -0000 Subject: without shell References: <11aj9d3fga9or8b@corp.supernews.com> Message-ID: <11ajkap3isrmndf@corp.supernews.com> On 2005-06-10, Donn Cave wrote: > In article <11aj9d3fga9or8b at corp.supernews.com>, > Grant Edwards wrote: > >> On 2005-06-10, Mage wrote: >> >> >>py> file_list = os.popen("ls").read() >> >> >> >>Stores the output of ls into file_list. >> >> >> > These commands invoke shell indeed. >> >> Under Unix, popen will not invoke a shell if it's passed a >> sequence rather than a single string. > > I suspect you're thinking of the popen2 functions. According to the current module reference, that's the behavior of the os.popen*() functions: http://docs.python.org/lib/os-newstreams.html#os-newstreams > On UNIX, os.popen is posix.popen, is a simple wrapper around > the C library popen. It always invokes the shell. Not according the the docs: Also, for each of these variants, on Unix, cmd may be a sequence, in which case arguments will be passed directly to the program without shell intervention (as with os.spawnv()). If cmd is a string it will be passed to the shell (as with os.system()). It's not exactly clear what "these variants" refer to, but I read it as referring to all of the the os.popen functions. Perhaps it only refers to os.popen[234]? > The no-shell alternatives are spawnv (instead of system) and > the popen2 family (given a sequence of strings.) > > Donn Cave, donn at u.washington.edu -- Grant Edwards grante Yow! FIRST, I'm covering at you with OLIVE OIL and visi.com PRUNE WHIP!! From pmaupin at gmail.com Thu Jun 23 18:56:02 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 23 Jun 2005 15:56:02 -0700 Subject: PEP 304 - is anyone really interested? References: Message-ID: <1119567362.026775.272080@g44g2000cwa.googlegroups.com> Thomas Heller wrote: > Although I was not interested originally, I think that's > a use case I also have. Optional config files, which > should not be compiled to .pyc or .pyo. Only removing > the .py file doesn't have the expected effect > if a .pyc and/or .pyo if is left. I also think that if nobody has the same use-case as envisioned by the original PEP, we should probably step back and rethink how it should be implemented. The original PEP envisioned the installation of third-party .py file libraries without their corresponding .pyc files into directories for which the eventual script user had no write-access. As more people become coginzant of the correct way to install Python libraries, I think this use-case fades in importance. The key distinction between this older use-case and the currently envisioned use-case is that the former assumes third-party code, and the latter assumes that the control over .pyc generation is desired by the _author_ of some python code, rather than merely the _installer_ of some python code. In this latter case, environment variables are not strictly necessary, because the top-level script could do whatever it needs to control .pyc generation, from inside Python itself. > AFAIK, it is not possible to define empty env vars on Windows. You make a good point about null environment variables. I think the original PEP was fairly *nix-centric, both in that aspect, and in the aspect of requiring the value of bytecodebase to be the "root" of the file system. This might not have the desired results in all cases on Windows. Regards, Pat From darkpaladin79 at hotmail.com Mon Jun 6 19:04:44 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 19:04:44 -0400 Subject: Creating file of size x In-Reply-To: <42A4D60B.9010107@gmail.com> Message-ID: http://python.org/doc/2.4.1/modindex.html this is the global module index. I'd keep it handy to search through since it has some of the most useful stuff every intented! =D Try looking through here to help. . .That's the best I can think of. -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rkern at ucsd.edu Wed Jun 1 16:23:30 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 01 Jun 2005 13:23:30 -0700 Subject: PySol not working on WinXP, SP2 In-Reply-To: <17054.5553.369830.823280@montanaro.dyndns.org> References: <429DC8F7.38AFB2B5@pauahtun.org> <17054.5553.369830.823280@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Ivan> I can't find any later version on google... > > It may not help you much, but I was able to get it working on MacOSX by > grabbing the latest available source and tracking down the contents of the > data directory via the Wayback Machine. If you'd like to give it a try (I'm > not sure how you'd get sound stuff working - I'm not a Windows guy), let me > know. Source, data, and OS X binaries for 4.82 also available from here: http://homepage.mac.com/brian_l/FileSharing6.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From spam.csubich+block at block.subich.spam.com Sun Jun 12 01:41:31 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 12 Jun 2005 01:41:31 -0400 Subject: TKinter -- '' event executing more than once? In-Reply-To: References: <6EKqe.115932$J25.63349@bignews6.bellsouth.net> Message-ID: <0SPqe.90792$8S5.63138@bignews3.bellsouth.net> jepler at unpythonic.net wrote: > Bindings created on a Toplevel or Tk widget apply to *all* widgets in > the same toplevel. So you're seeing a event for each widget > you create... Oh. :) Is there a way of binding the event just to the window itself, or should I just check that the widget referenced in the 'event'? [update: not even sure how I'd do this anyway, since the widget returned in the event "is not" the root widget] From peter at engcorp.com Thu Jun 9 22:00:44 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 22:00:44 -0400 Subject: inactive Spambayes w/ Outlook In-Reply-To: <1118358998.183038.192940@g14g2000cwa.googlegroups.com> References: <1118358998.183038.192940@g14g2000cwa.googlegroups.com> Message-ID: tendengarci at yahoo.com wrote: > I had installed spambayes with outlook 2003 a while ago and it worked > great. Then I did who know what it stopped working. I would click on > the 'delete spambayes' toolbar icon but nothing would happen. I clicked > on the 'spambayes' icon for options but nothing happened. I uninstalled > and reinstalled a number of times with no luck. I just downloaded and > installed version 1.1a1 and still no luck. I would love to get this > working again. The following link might help. Pay particular attention to item 6 under "Addin doesn't load", since what you describe is very similar to a problem I had which that sequence fixed for me. -Peter From oliver.andrich at gmail.com Mon Jun 20 16:54:04 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Mon, 20 Jun 2005 22:54:04 +0200 Subject: Python and encodings drives me crazy In-Reply-To: References: Message-ID: <6f7b52d05062013545cbc435d@mail.gmail.com> > I know this isn't your question, but why write: > > > data = apply(string.replace, [data, html, char]) > > when you could write > > data = data.replace(html, char) > > ?? Cause I guess, that I am already blind. Thanks. Oliver -- Oliver Andrich --- http://fitheach.de/ From bronger at physik.rwth-aachen.de Sat Jun 25 13:08:34 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 25 Jun 2005 19:08:34 +0200 Subject: distutils: Every file doubled in binary distri Message-ID: <87mzpeqs8d.fsf@wilson.rwth-aachen.de> Hall?chen! I have a very simple package structure with one directory denoting a package (with __init__.py file of course). In my setup.py I write ... packages=['my_package'] ... Then I call "python setup.py bdist_dumb" on ym Linux box. The resulting tar ball contains every file twice, e.g. ./usr/lib/python2.3/site-packages/my_package/my_module.py ./usr/lib/python2.3/site-packages/my_module.py Why is this? (The source distri doesn't show this effect.) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From kay.schluehr at gmx.net Thu Jun 16 12:31:08 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 16 Jun 2005 09:31:08 -0700 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> <1118468625.619330.12540@f14g2000cwb.googlegroups.com> <4se8o2-ksq.ln1@lairds.us> Message-ID: <1118939468.138147.98310@g14g2000cwa.googlegroups.com> Sorry, Cameron, if I twist meanings. Thomas argues that Python programmers are more expensive than Java ones. But if one needs more Java programmers to fit into the project plan one needs probably more managenment/admistration staff ( ~ ratio = 1/3) and managers are usually more expensive than programmers. I concede that this is hard to measure but for a similar issue one should remember that the OPs project did not incorporate the role of a "software architect" up to now - it did not have to be reified. Kay From kbilsted at hotmail.com Sun Jun 12 20:03:18 2005 From: kbilsted at hotmail.com (newseater) Date: 12 Jun 2005 17:03:18 -0700 Subject: changing how instances are "created" In-Reply-To: References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> <1118619382.878977.185960@g44g2000cwa.googlegroups.com> Message-ID: <1118620998.606895.119420@g47g2000cwa.googlegroups.com> > > A staticmethod does not take a cls argument. It is essentially just a > function that is attached to a class. yes i know of that difference... but one cannot easily override a class method in a supclass.. as calling super then make the cls variable point to the super class class rather than the subclass! very confusing! So i decided to skip that one... From eloff777 at yahoo.com Mon Jun 13 20:31:53 2005 From: eloff777 at yahoo.com (Eloff) Date: 13 Jun 2005 17:31:53 -0700 Subject: "also" to balance "else" ? In-Reply-To: References: Message-ID: <1118709113.769757.160250@g47g2000cwa.googlegroups.com> My first reaction was that this is terrible, else clauses on loops are confusing enough. But if I think about it more, I'm warming up to the idea. Also/Else for loops is clear, symmetrical, and would be useful. Reversing the meanign of else will break code, but it's not used that frequently, and it was a confusing thing to begin with, nothing wrong in breaking something (slowly!) if it was 'broken' to begin with. Alifs look evil, I couldn't deduce the control flow very easily, but then they are a new idea. I'll keep an open mind on that one. I think the best thing would be to compare the also/else syntax to what identical functionality looks like in python now [hint to someone with more time than me right now ;)]. I'd vote for whichever is the more concise and readable of the two. -Dan From devlai at gmail.com Fri Jun 24 14:48:26 2005 From: devlai at gmail.com (Devan L) Date: 24 Jun 2005 11:48:26 -0700 Subject: what list comprehension can't In-Reply-To: <1119638714.090433.130520@z14g2000cwz.googlegroups.com> References: <1119638714.090433.130520@z14g2000cwz.googlegroups.com> Message-ID: <1119638906.858952.185230@g44g2000cwa.googlegroups.com> I wasn't aware that python supported "if then else". From patfitz at gmail.com Wed Jun 22 23:09:57 2005 From: patfitz at gmail.com (Patrick Fitzsimmons) Date: Wed, 22 Jun 2005 23:09:57 -0400 Subject: Does a function like isset() exist in Python? Message-ID: <76d1249d050622200924e14e@mail.gmail.com> Hi, I'm sure I should know this, but I can't find it in the manual. Is there a function in Python like the function in PHP isset()? It should take a variable name and return True or False depending on whether the variable is initialized. Thanks for any help, Patrick From oren.tirosh at gmail.com Fri Jun 17 04:10:53 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 17 Jun 2005 01:10:53 -0700 Subject: Set of Dictionary In-Reply-To: References: Message-ID: <1118995853.509161.49840@g49g2000cwa.googlegroups.com> See the frozendict recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/414283 It was written exactly for this purpose: a dictionary that can be a member in a set. Oren From http Wed Jun 22 18:25:42 2005 From: http (Paul Rubin) Date: 22 Jun 2005 15:25:42 -0700 Subject: Optimize a cache References: Message-ID: <7xoe9y9ggp.fsf@ruckus.brouhaha.com> Florian Lindner writes: > What possible you see to optimize this lookup? Or anything else you see to > make it better? Do you need to update the timestamp of cached entries when you access them? If yes, use the heapq module. If no, is the cache something different from a simple FIFO? From idontneednostinkinid at yahoo.com Wed Jun 1 15:26:32 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 12:26:32 -0700 Subject: idiom for constructor? In-Reply-To: References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <1117653992.039800.122880@z14g2000cwz.googlegroups.com> > You might look to see if you can customize your editor to use > templates/interaction and then inserts the right text for you. Well, I'm not really concerned with "amount of typing" as much as with the inherent ugliness, tediousness, and lack of elegance of the original form. Alas, templates/macros would not fix the latter. From austin at maxtronic.com.tw Fri Jun 10 05:10:23 2005 From: austin at maxtronic.com.tw (Austin) Date: Fri, 10 Jun 2005 17:10:23 +0800 Subject: os.system Message-ID: My code is " os.system("NET SEND computer hihi") " i use this funtion on Windows server 2003. it's ok. But the same code running on Windows XP SP2, it shows the command window twice. How do i remove the command window? From http Wed Jun 8 16:58:00 2005 From: http (Paul Rubin) Date: 08 Jun 2005 13:58:00 -0700 Subject: Fast text display? References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> Message-ID: <7xll5ka7mv.fsf@ruckus.brouhaha.com> Christopher Subich writes: > > Use tkinter if you care about cross-platform operation. Everything > > else requires downloading and installing separate toolkits. > > Oh, the downloading and installing isn't a big deal. If in the > far-flung future anyone else uses this program, they'll be big boys > who can install things themselves. :) No, it's a big pain. I'm a big boy and gave up on trying to install wxpython for bittorrent on FC3 (the problem was with wxwidgets needing an obsolete version of gtk, not with wxpython itself). There's just no compelling reason to want to deal with this stuff. Tkinter has its warts but it allows making functional gui's without all that much fuss. If it were replaced in the default distro then I'd say use whatever the new default is, but as it is, it's best to not impose unnecessary extra headache on users. From t-meyer at ihug.co.nz Sun Jun 26 04:49:28 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Sun, 26 Jun 2005 20:49:28 +1200 Subject: Tracing down segfault In-Reply-To: Message-ID: [Tony Meyer] >> I have (unfortunately) a Python program that I can >> consistently (in a reproducible way) segfault. [Tim Peters] > The _best_ thing to do next is to rebuild Python, and as many other > packages as possible, in debug mode. [...] > It's especially useful to rebuild Python that way. Many asserts are > enabled then, and all of Python's memory allocations go thru a special > debug allocator then with gimmicks to try and catch out-of-bounds > stores, double frees, and use of free()'d memory. I wondered if that might help. I really ought to get around to doing a debug build someday, I guess. It just doesn't seem like the easiest thing to do on Windows without the MS tools (although I do recall various c.l.p messages indicating that the required patches were around somewhere). Luckily (see below), I managed to avoid it this time. > You didn't mention which version of any of these you're using, or the > OS in use. Playing historical odds, and assuming relatively recent > versions of all, wx is the best guess. Sorry (although your guesses were pretty good; just as well you pop up everywhere I post to help me out <0.5 wink>). Windows XP SP2, Python 2.3.5 or 2.4.1, ZODB 3.4.0, wxPython 2.6.1.0. After taking 24 hours off, I figured out that I could reasonably easily run the code without using anything that imported wx, and, sure enough, the segfault doesn't occur. Good in that it's much less code to look at, but bad in that I didn't write any of the code that uses wx... [Tony, suspecting threading to be the cause] > It's unlikely to be the true cause. Apart from some new-in-2.4 > thread-local storage gimmicks, all of the threading module is written > in Python too. NULL pointers are a (depressingly common) C problem. Oh well. I was working on a few things at once, and it's possible that I only noticed it after adding the new threading code. > So only a single thread is running at the time the segfault occurs? As far I know, yes. At least, all the threads that I created I have called join() on without any timeout. > Is Python also in the process of tearing itself down (i.e., is the > program trying to exit?). Yes, the program is trying to exit. It's after the a call is made to "wx.GetApp().ExitMainLoop()" (but a print statement after that does print). If I run with python -v, it dies before any of the # clear statements get printed out. I'm not sure what runs between those :( [Later] The 24 hours off helped me think much more clearly. Once I had narrowed it down to wx (and stopped worrying about all the threading code) I managed to find a line of Python that commenting out would get rid of the segfault and uncommenting would return the segfault. FWIW, I believe what was happening is that there was a wx.TaskBarIcon class that, when the "Exit" menu item was chosen, would call an exit function of the main frame of the wx application. That exit function called "Destroy()" on the TaskBarIcon class - and it was this call that caused the segfault. I presume that the problem was that the TaskBarIcon class was waiting for that exit function to be finished, and didn't appreciate being Destroy()d while it was waiting. Many thanks for the help! (Like the recent ZODB problem, the help was somewhat lateral - here, pointing me away from the threads). =Tony.Meyer From bronger at physik.rwth-aachen.de Sat Jun 18 12:55:07 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 18 Jun 2005 18:55:07 +0200 Subject: Unbound names in __del__ References: Message-ID: <87mzpnmwpg.fsf@wilson.rwth-aachen.de> Hall?chen! Peter Hansen writes: > Torsten Bronger wrote: > >> Peter Hansen writes: >> >>> What's your use case for del? >> >> Every instance represents a "session" to a measurement instrument. >> After the instance is deleted, the session should be closed to free >> resources. > > You mean like GPIB devices? Yes. > We've written a lot of software that talks to instruments, as well > as pumps, motors, and sensors of all kinds. I haven't even needed > to "free resources", other than by closing a serial port, for > example. [...] I've just finished a thin-wrappers implementation of VISA in Python, see . It calls functions in a proprietary VISA DLL/SO. The next step is to build a simple-to-use OO layer on top of it. Therefore, we don't communicate with the device directly, but via sessions (=handles) within the DLL. These sessions should be freed when the object instance representing the device is destroyed by Python. Using the __del__ method is the natural choice for this in my opinion. > [...] I'd recommend pretending __del__ does not exist and > restructuring your system to close these sessions explicitly, > under your direct control, at the appropriate point. This has > worked very well for us so far. I'd find this quite sad because so far it's drop-dead simple to use the OO layer, and I may even convince our in-house HT Basic fans of Python: keithley = GpibInstrument(14) keithley.write("*IDN?") print keithley.read() A keithley.close() would be a wart in my opinion; instead I want to hide the whole session thing from the programmer. Besides, I haven't yet given up the hope that the issues with __del__ can be tackled. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From gene.tani at gmail.com Tue Jun 21 15:00:58 2005 From: gene.tani at gmail.com (gene tani) Date: 21 Jun 2005 12:00:58 -0700 Subject: Create our own python source repository In-Reply-To: References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> <1118156654.634103.186390@o13g2000cwo.googlegroups.com> <1118170303.568984.242610@z14g2000cwz.googlegroups.com> <1119355109.640882.74380@g47g2000cwa.googlegroups.com> Message-ID: <1119380458.147145.155680@g14g2000cwa.googlegroups.com> Practical Python is quite a good book. And to re-iterate again, teh humongous tutorial list which has Hetland's Instant python among others: http://www.awaretek.com/tutorials.html Brian van den Broek wrote: > Michele Simionato said unto the world upon 21/06/2005 07:58: > > qwwee: > > > >>for a certain argument I'd prefer an application fully > >>explained (also if not covering all the features) to a more general > >>tutorial with only brief and unrelated code snippets. > >>Unfortunately, that's not the way things are normally done, because it > >>is much harder to build a useful application and fully comment it > > > > > > A part the Cookbook, I know of at least two Python books taking the > > approach you describe: > > > > 1. Dive into Python (Pilgrim) > > 2. Programming Python (Lutz) > > > > Dive into Python is free (and even translated in Italian on > > www.python.it, IIRC) > > > > Michele Simionato > > > > Not free, but: > > Practical Python, published by the same press as the Pilgrim, steps > through incremental approaches to large (by book standards) > applications. From the author's site: > > "Hetland devotes the second half of the book to project development, > taking great care to choose a series of ten increasingly complex > applications that are of timely and wide-ranging interest to > burgeoning and expert developers alike. Project focus includes > automated document conversion, newsgroup administration, graphical PDF > document generation, remote document maintenance, the creation of a > peer-to-peer system with XML-RPC, database integration, and GUI and > game development. > " > http://hetland.org/writing/practical-python/ > > best, > > Brian vdB From ramen at lackingtalent.com Tue Jun 28 15:58:21 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 28 Jun 2005 12:58:21 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <70iwe.89655$yV4.47526@okepread03> BORT wrote: > I am toying with the idea of teaching my ten year old a little about > programming. I started my search with something like "best FREE > programming language for kids." After MUCH clicking and high-level > scanning, I am looking at Python and Forth. Both have advocates that > say each is a great approach to learning computers. Kids your backwards talking like if forth love will they then. From austin at maxtronic.com.tw Tue Jun 14 03:32:02 2005 From: austin at maxtronic.com.tw (Austin) Date: Tue, 14 Jun 2005 15:32:02 +0800 Subject: windows directory Message-ID: I would like to write a program which creates the folders in specific directory. For example, I want to create folder in Program Files. How do I know which is in C:\ or D:\ Is there any function to get the active path? Thanks in advance. From andreas at kostyrka.org Fri Jun 17 05:12:56 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 17 Jun 2005 11:12:56 +0200 Subject: pyrex problem In-Reply-To: <1118995394.861014.317590@g49g2000cwa.googlegroups.com> References: <1118995394.861014.317590@g49g2000cwa.googlegroups.com> Message-ID: <20050617091255.GA8721@heaven.kostyrka.org> On Fri, Jun 17, 2005 at 01:03:14AM -0700, borges2003xx at yahoo.it wrote: > hi everyone > i'm newbie > > i try to compile the pyrex module: > def controlla(char *test): You cannot have a C datatype in a Python like that. Much better to use def controlla(test): Andreas From flupke at nonexistingdomain.com Tue Jun 7 17:07:58 2005 From: flupke at nonexistingdomain.com (flupke) Date: Tue, 07 Jun 2005 21:07:58 GMT Subject: poker card game revisited (code included) In-Reply-To: <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> References: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> Message-ID: Erik Max Francis wrote: > flupke wrote: > First of all, my apologies for the double posts. I can only see this reply and can't see my original messages. I posted the message from home and work and they didn't show up. We use the same isp at home and at work so it's probably a problem on their end. > It looks like you're not approaching this in a systematic manner. > Algorithms for determining poker hands are already pretty well-known; > there are several open source projects that do it efficiently which you > could learn from. Which projects are you talking about? I only found a library in c to evaluat ranks but i didn't find the code to be very understandable. > When you're evaluating poker hands, you're looking for three basic types > of card groups: matches, straights, and flushes. The most efficient > way to look for matches is with a histogram based on the card rank. Bin > the cards up by rank, and then build a second "histogram" of the counts > of those ranks indexing into a list of the ranks which had those cards > (sorted by rank, so you can pull off the highest ones). Now determining > all the rank-based hands is easy: quads have a hit with four matches, a > boat has a hit with two three matches (there's no "two trips" so this is > a boat at best) or both three and two matches, two pair has two hits > with two matches, etc. With histogram do you mean something like this: Card hand: 2 clubs, 3 diamonds, 10 of diamonds, 4 of hearts, 3 of hearts Histogram 1: list [2,3,4,10] 2 --------------------- 14 Histogram 2: list [1,2,1,0,0,0,0,0,1,0,0,0,0] or list [1,2,1,1] so index 0 is count of rank at index 0 of Histogram 1 index 1 is count of rank at index 1 of Histogram 1 > Searching for straights and flushes is much better done by masks. > Arrange all the possible cards in a huge masks based on both cards and > ranks (easy to do in Python with the long type) and then build up rank > masks that build up all possible straight combinations (sorted by the > highest rank so you can search them in order), and then build up card > mask ranks for each suit. For straights, just iterate through the > straight rank masks and see if you find one that's fully occupied; if > you do, that's a straight. For flushes, just iterate through the card > suit masks and see if you find one that has more five or more unique > cards in it. You need to iterate through all four and find the one with > the highest value (for games with lots of cards, you could have two > flushes; you want to count the highest one). Finally, to look for > straight flushes, first apply the suit masks and then turn it into ranks > and apply the straight masks. As for straights, if i understand correctly, you make all possible straights of the cards in the hand and then see if one matches? > Then will all this information you can easily arrange the code to select > the best existing hand. Note that these all use well-established > techniques and reveal nothing secret. Well, it's all new to me :) Regards, Benedict From kveretennicov at gmail.com Sat Jun 25 09:52:25 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 25 Jun 2005 15:52:25 +0200 Subject: Office COM automatisation - calling python from VBA In-Reply-To: <42BD3B0F.9030802@hotmail.com> References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> <42BD3B0F.9030802@hotmail.com> Message-ID: <4660fe3005062506522eaebf04@mail.gmail.com> On 6/25/05, Josef Meile wrote: > You could try to do an addin/addon for Word, Excel, and Outlook. You > don't need to code with VBA. Here you just need a language from where > you can access the microsoft interop assemblies (ie: C++ or C#; > IronPython maybe?) Hmm... Why jump through .NET hoops when all you need is COM? I suppose msoffice interops are no different than other .NET interops, which are just that - .NET/COM interoperability layer. There's no need for them unless you're calling COM from .NET. For CPython win32com should be enough. - kv From jepler at unpythonic.net Sun Jun 5 09:59:48 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 5 Jun 2005 08:59:48 -0500 Subject: Socket Speed In-Reply-To: <1117979261.996245.143810@g14g2000cwa.googlegroups.com> References: <1117979261.996245.143810@g14g2000cwa.googlegroups.com> Message-ID: <20050605135944.GA18270@unpythonic.net> 300KB/s sounds dreadfully low. I simply ran "python /usr/lib/python2.3/SimpleHTTPServer.py &", then "wget -O /dev/null http://0.0.0.0:8000/70megfile". On the best of 4 runs (when the file was cached) wget measured 225.20MB/s. The hardware is a Pentium-M laptop with 768MB RAM runnng at 1.5GHz. The OS is Fedora Core 2, kernel 2.6.12-rc5, Python 2.3. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From onurb at xiludom.gro Tue Jun 28 11:16:30 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 28 Jun 2005 17:16:30 +0200 Subject: Dictionary to tuple In-Reply-To: References: Message-ID: <42c169d0$0$23811$626a14ce@news.free.fr> Tim Williams (gmail) wrote: (snip) >>>>d = {1:'one',2:'two',3:'three'} >>>>t = tuple([(k,v) for k,v in d.iteritems()]) Err... don't you spot any useless code here ?-) (tip: dict.items() already returns a list of (k,v) tuples...) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From thomasbartkus at comcast.net Fri Jun 24 16:51:29 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 24 Jun 2005 15:51:29 -0500 Subject: Office COM automatisation - calling python from VBA References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: "guy lateur" wrote in message news:1119642545.750550.304450 at g44g2000cwa.googlegroups.com... > Hi all, > > I am trying to write some code (macro's, if you like) to glue together > our Office applications (mainly Word, Excel and Outlook). We have a lot > of different projects going on simultaneously. The idea is to develop a > centralized framework (starting point, common interface) for my users > to view/control their documents/correspondence, on a per project basis. > > As an example, I'd like to have a control (button, menu entry) in > Outlook that allows my users to bring up, say, an email for a certain > contact (architect, owner, engineer, ..) on a certain project, with > certain attachments, .. Currently, I have a 'public folder' in OL > (Exchange) that reflects our project structure. > > I'll be using COM, and I could probably make an application that > controls Outlook (externally). But I'd also like to have this > functionality exposed in OL itself. So I guess I'll need to use VBA, > but I don't really like VBA - relax, please, it's just an opinion.. ;) > > So, ideally, I'd like to program as much as possible in python (I'm > pretty new to that, too, btw), and only use VBA if needed - say, to > call python objects/methods (+ wxGUI, please). > > > Would that be an easy, a hard, or an insane strategy? Maybe there are > some tutorials on this (searched the list, but didn't quite find any). > If anyone happens to have any xp/tips on this, please, fire away! You are using Microsoft Windows. You are trying to integrate ("glue together") Microsoft Office applications. You want to use other Microsoft COM objects. You want to your software to *be* a COM object ("functionality exposed in OL itself") You want a robust GUI interface that has the look, feel, and fits in with, MS Office. You want to use --- Python ??? How, pray tell, do you add up (VBA+VBA+VBA+VBA+VBA) and have it come out equaling Python? Be reasonable here. You don't have to "like" VBA to see that this is the only practical choice in this situation. Imagine if Python had a robust GUI development system that fit right into your os platform AND was the native, built in, macro language for the top 5 high level applications you needed to work with. Do you think that might please a few of us here in this particular newsgroup? This is exactly what Microsoft has with Office/VBA. I don't particularly like VBA as a language either. And I don't like B. Gates And I may well be crazy. Just not *that* crazy! Thomas Bartkus From oren.tirosh at gmail.com Mon Jun 13 12:33:25 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 13 Jun 2005 09:33:25 -0700 Subject: ElementTree Namespace Prefixes References: Message-ID: <1118680405.635415.110740@f14g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Chris Spencer wrote: > > > If an XML parser reads in and then writes out a document without having > > altered it, then the new document should be the same as the original. > > says who? Good question. There is no One True Answer even within the XML standards. It all boils down to how you define "the same". Which parts of the XML document are meaningful content that needs to be preserved and which ones are mere encoding variations that may be omitted from the internal representation? Some relevant references which may be used as guidelines: * http://www.w3.org/TR/xml-infoset The XML infoset defines 11 types of information items including document type declaration, notations and other features. It does not appear to be suitable for a lightweight API like ElementTree. * http://www.w3.org/TR/xpath-datamodel The XPath data model uses a subset of the XML infoset with "only" seven node types. http://www.w3.org/TR/xml-c14n The canonical XML recommendation is meant to describe a process but it also effectively defines a data model: anything preserved by the canonicalization process is part of the model. Anything not preserved is not part of the model. In theory, this definition should be equivalent to the xpath data model since canonical XML is defined in terms of the xpath data model. In practice, the XPath data model defines properties not required for producing canonical XML (e.g. unparsed entities associated with document note). I like this alternative "black box" definition because provides a simple touchstone for determining what is or isn't part of the model. I think it would be a good goal for ElementTree to aim for compliance with the canonical XML data model. It's already quite close. It's possible to use the canonical XML data model without being a canonical XML processor but it would be nice if parse() followed by write() actually passed the canonical XML test vectors. It's the easiest way to demonstrate compliance conclusively. So what changes are required to make ElementTree canonical? 1. PI nodes are already supported for output. Need an option to preserve them on parsing 2. Comment nodes are already support for output. Need an option to preserve them on parsing (canonical XML also defines a "no comments" canonical form) 3. Preserve Comments and PIs outside the root element (store them as children of the ElementTree object?) 4. Sorting of attributes by canonical order 5. Minor formatting and spacing issues in opening tags oh, and one more thing... 6. preserve namespace prefixes ;-) (see http://www.w3.org/TR/xml-c14n#NoNSPrefixRewriting for rationale) From kveretennicov at gmail.com Wed Jun 22 19:08:08 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 23 Jun 2005 01:08:08 +0200 Subject: Python API to manipulate CAB files. In-Reply-To: References: <1119447992.300154@hqnntp01.autodesk.com> Message-ID: <4660fe3005062216084f063f1c@mail.gmail.com> On 6/22/05, Peter Maas wrote: > Isaac Rodriguez schrieb: > > Does anyone know of a Python API to manipulate CAB files? I guess you'll have to interface with setupapi.dll (SetupIterateCabinet) via ctypes, or with Microsoft Cabinet utilities via subprocess module. Neither is what people call fun... - kv From arigo at tunes.org Sun Jun 12 17:10:29 2005 From: arigo at tunes.org (Armin Rigo) Date: Sun, 12 Jun 2005 23:10:29 +0200 Subject: Post-EuroPython 2005 PyPy Sprint 1st - 7th July 2005 Message-ID: <20050612211029.GA26015@code1.codespeak.net> Post-EuroPython 2005 PyPy Sprint 1st - 7th July 2005 ====================================================== The next PyPy sprint is scheduled right after EuroPython 2005 in Gothenborg, Sweden. Its main focus is translation to lower level backends but there are also other possible topics. We'll give newcomer-friendly introductions. To learn more about the new PyPy Python-in-Python implementation look here: http://codespeak.net/pypy On a side note, there are a number of sub projects that may be interesting for participating in google's summer-of-code event (deadline June 14th!). The PyPy group is willing to mentor projects that have some link with PyPy, so if you are accepted in such a project, the sprint could also serve as a good meeting and kick-off point. Further down you'll find some examples, but there are certainly more and bigger ones :-) Goals and topics of the sprint ------------------------------ The main, though not the only, focus of the sprint will be on the "translation" aspect of PyPy. The goal here is to progress towards a completely translated PyPy. How much will already have been done before EuroPython is unknown; as a guess, we will be left with: - completing the "rtyper", the piece of code that assigns low-level C-like types to high-level RPython objects (lists, dicts, instances, etc.) and low-level control flow graphs to high-level ones; - polish off the GenC and GenLLVM back-ends, responsible for turning the low-level C-like flow graphs into real C or LLVM source code. See http://codespeak.net/pipermail/pypy-dev/2005q2/002136.html for more information (10th of June status). Non-translation-related topics are welcome too. Here are some suggestions from the issue tracker (https://codespeak.net/issue/pypy-dev/): - integrate the parser module, possibly making it RPython conformant; - rewrite in Python a C module you are familiar with (partial list of missing/incomplete modules: os, math, array, regular expressions, binascii...) - implement Python 2.3's import hook extensions (zip-imports etc.) - fix Windows-related issues, '%'-formatting rounding errors, add missing docstrings on app-level built-in types and functions, etc. - weakrefs (but this requires discussion and planning on pypy-dev before the sprint! feel free to start such a discussion, though.) Location & Accomodation ------------------------ The sprint will be held in the former Math Center building near the crossing of Gibraltargatan and Eklandagatan. Entrance is on the middle of the side facing Gibraltargatan. The doors to the building are normally locked, so you need the phone number of somebody inside to get in. Instructions on whom to call will be posted on the door. The sprint will be co-located with several other sprints. See the `EuroPython Wiki`_, to find out what other sprints will be running. Nearest, and probably cheapest is to book accomodation at SGS Veckobost??der through the Europython website. This option will be available until about 20 June. .. _`EuroPython special accomodation`: http://www.europython.org/sections/accomodation/special_accomodation .. _`EuroPython Wiki`: http://www.europython.org/sections/sprints_and_wiki Exact times ----------- The public Pypy sprint is held Friday 1st July - Thursday 7 July 2005. Hours will be from 09:00 until people have had enough. It's a good idea to arrive a day before the sprint starts. (There is a sprint for people who are familiar with the Pypy codebase before Europython as well. This will be held at Jacob & Laura's home on G??tabergsgatan 22.) Network, Food, currency ------------------------ Sweden is not part of the Euro zone. One SEK (krona in singular, kronor in plural) is roughly 1/10th of a Euro (9.15 SEK to 1 Euro). There are some pizzerias, kebab places and the like close to the venue. Their food is edible and cheap, but not very good. For good food, you need to go downtown. You need a wireless network card to access the network. You will be issued a login to the Chalmers NOMAD network. This will allow you to use access points all over Chalmers. However, we can likely provide a wireless/ethernet bridge. Sweden uses the same kind of plugs as Germany. 230V AC. Registration etc.pp. -------------------- Please subscribe to the `PyPy sprint mailing list`_, introduce yourself and post a note that you want to come. Feel free to ask any questions there! .. _`PyPy sprint mailing list`: http://codespeak.net/mailman/listinfo/pypy-sprint -- Armin Rigo & the PyPy team From steve at REMOVEMEcyber.com.au Wed Jun 15 01:19:55 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 15 Jun 2005 15:19:55 +1000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> Message-ID: <42AFBA7B.5000805@REMOVEMEcyber.com.au> Peter Hansen wrote: > Roy Smith wrote: > >> Steven D'Aprano wrote: >> >>> High and low tides aren't caused by the moon. >> >> >> They're not??? > > > Probably he's referring to something like this, from Wikipedia, which > emphasizes that while tides are caused primarily by the moon, the height > of the high and low tides involves the sun as well: > > "The height of the high and low tides (relative to mean sea level) also > varies. Around new and full Moon, the tidal forces due to the Sun > reinforce those of the Moon, due to the syzygy found at those times - > both the Sun and the Moon are 'pulling the water in the same direction.'" > > (If I'm right about this, then the statement is still wrong, since even > without the sun there would be high and low tides, just not of the > magnitude we have now.) Close :-) If tides are caused by the moon, then removing the moon would end tides. But this clearly isn't true: without the moon, we would still have tides, only smaller. On the other hand, the magnitude of the tides is much larger than the magnitude of the moon's effect on the oceans (up to forty times larger). So the moon is, at best, merely a minor cause of the tides. Of course, all this is quibbling. But it does illustrate exactly what Cohen and Stewart mean when they talk about "lies for children". The truth is a lot more complicated that the simple, easy to understand "the moon causes the tides". -- Steven. From frankabel at tesla.cujae.edu.cu Mon Jun 6 17:43:40 2005 From: frankabel at tesla.cujae.edu.cu (Frank Abel Cancio Bello) Date: Mon, 6 Jun 2005 17:43:40 -0400 Subject: About size of Unicode string In-Reply-To: <8m2pe.8937$Cz3.1120032@monger.newsread.com> Message-ID: <20050606213927.285F031806E@newton.cujae.edu.cu> Thanks to all. Andrew's answer was an excellent explanation. Thanks Leif for you suggestion. > -----Original Message----- > From: python-list-bounces+frankabel=tesla.cujae.edu.cu at python.org > [mailto:python-list-bounces+frankabel=tesla.cujae.edu.cu at python.org] On > Behalf Of Leif K-Brooks > Sent: Monday, June 06, 2005 4:29 PM > To: python-list at python.org > Subject: Re: About size of Unicode string > > Frank Abel Cancio Bello wrote: > > request.add_header('content-encoding', 'UTF-8') > > The Content-Encoding header is for things like "gzip", not for > specifying the text encoding. Use the charset parameter to the > Content-Type header for that, as in "Content-Type: text/plain; > charset=utf-8". > -- > http://mail.python.org/mailman/listinfo/python-list > From ods at strana.ru Fri Jun 17 05:10:21 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 17 Jun 2005 13:10:21 +0400 Subject: How to right align IPaddress? In-Reply-To: <20050617084652.41351.qmail@web8409.mail.in.yahoo.com> References: <1118740170.9602.236315256@webmail.messagingengine.com> <20050617084652.41351.qmail@web8409.mail.in.yahoo.com> Message-ID: <20050617131021.651b8bb4@ods.pravda.rfn.ru> On Fri, 17 Jun 2005 09:46:52 +0100 (BST) praba kar wrote: > Is it possible to right align > the Ipaddress? Normally we can > right align the list of numbers > by %3u or %7u. How we can right > align the Ipaddress? > > I expects below format output > eg 203.199.200.0 > 203.33.20.0 >>> for ip in ('203.199.200.0', '203.33.20.0'): ... print '%15s' % ip ... 203.199.200.0 203.33.20.0 >>> for ip in ('203.199.200.0', '203.33.20.0'): ... print ip.rjust(15) ... 203.199.200.0 203.33.20.0 -- Denis S. Otkidach http://www.python.ru/ [ru] From bugbear at trim_papermule.co.uk_trim Thu Jun 23 12:42:24 2005 From: bugbear at trim_papermule.co.uk_trim (bugbear) Date: Thu, 23 Jun 2005 17:42:24 +0100 Subject: newbie - modules for jython (under grinder 3) ? In-Reply-To: <3i00ndFho4uoU1@uni-berlin.de> References: <42bac1b8$0$2021$ed2e19e4@ptn-nntp-reader04.plus.net> <3i00ndFho4uoU1@uni-berlin.de> Message-ID: <42bae670$0$41928$ed2619ec@ptn-nntp-reader03.plus.net> Diez B. Roggisch wrote: > bugbear wrote: > >> I'm just trying to use Grinder 3 to beat >> up my http-app. >> >> Grinder 3 comes with its own jython.jar. >> >> Some of the sample scripts: >> http://grinder.sourceforge.net/g3/script-gallery.html >> use import statements that don't work for me. >> >> Reading around, these are reference to modules. >> >> Do I need a "proper" jython instead of the one >> that grinder ships with? > > > I guess so - at least there are jython-modules written as *py-files in > my jython installation, including the threading.py module. Now - I don't > exactly remember how to specify where to find those, but AFAIK there is > a system property that you have to set to that path. > > So - go, fetch jython from jython.org, install it and try to proceed. > OK - of course this means I'll have to tell Grinder to use "my" Jython, not "its" Jython. Hopefully that's well documented :-) BugBear From b at b.b Sun Jun 12 02:53:25 2005 From: b at b.b (Roose) Date: Sun, 12 Jun 2005 06:53:25 GMT Subject: What language to manipulate text files References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: Why do people keep asking what language to use for certain things in the Python newsgroup? Obviously the answer is going to biased. Not that it's a bad thing because I love Python, but it doesn't make sense if you honestly want an objective opinion. R ross wrote: > I want to do some tricky text file manipulation on many files, but > have only a little programming knowledge. > > What are the ideal languages for the following examples? > > 1. Starting from a certain folder, look in the subfolders for all > filenames matching *FOOD*.txt Any files matching in each folder should > be copied to a new subfolder within the current folder called EATING > with a new name of *FOOD*COPY.txt > > 2. Process each file as follows: > Here is a simplified example of what I want as input and output. > > ------------------------------------- input > ......................... 'several unknown lines of text file > Get apples from apples shop > Get oranges from oranges shop > Get plums from plums shop > Get pears from pears shop > Eat from apples, oranges, > plums, pears 'whitespace at start of line is unimportant > ......................... 'more unknown lines of text file > Chapter 1 > Several lines of text about apples in here > Chapter 2 > Several lines of text about oranges in here > Chapter 3 > Several lines of text about plums in here > Chapter 4 > Several lines of text about pears in here > > ------------------------------------- output > ......................... 'several unknown lines of text file > Get apples from apples shop > Get oranges from oranges shop > Get plums from plums shop > Get pears from pears shop > Get bagels from bagels shop 'the Get lines... > Get donuts from donuts shop 'can be in any order > Eat from apples, bagels, oranges, > plums, donuts, pears 'whitespace at start of line is unimportant > ......................... 'more unknown lines of text file > Chapter 1 > Several lines of text about apples in here > Chapter 2 > Several lines of text about bagels in here > Chapter 3 > Several lines of text about oranges in here > Chapter 4 > Several lines of text about plums in here > Chapter 5 > Several lines of text about donuts in here > Chapter 6 > Several lines of text about pears in here > > Summary: > I have added two new items to Get; > I have put them into the comma-delimited list after searching for a > particular fruit to put each one after; > The Chapters are renumbered to match their position in the > comma-delimited list. > The "several lines of text" about each new item can be pulled from a > new_foods.txt file (or a bagels.txt and a donuts.txt file). > > My first objective is to process the files as described. > My second objective is to learn the best language for this sort of > text manipulation. The language should run on Windows 98, XP and > Linux. > > Would Python be best, or would a macro-scripting thing like AutoHotKey > work? > I thought about Perl, but think I would learn bad habits and have hard > to read code. > > Thanks, Ross From jstroud at mbi.ucla.edu Tue Jun 28 17:52:44 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 28 Jun 2005 14:52:44 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <200506281452.44676.jstroud@mbi.ucla.edu> Frankly, I can't watch Shakespeare or movies like "the full monty" or "trainspotting" because I can't understand a damn word they say. British talk sounds like gibberish to me for the most part. Out of all of these movies, the only thing I ever could understand was something like "I've got the beast in my sights misses Pennymoney". Haaar! Wow, that's a good one. I think James Bond did it for Americans. He always wore a dinner jacket and played a lot of backarack--which is only cool because you have to bet a lot of money. Anyway, if you insist on making distinctions between the backwoods of apalachia and european aristocracy, I should remind you of the recessive genetic diseases that have historically plagued europe's nobility. On Tuesday 28 June 2005 11:27 am, muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. Many companies hire salespersons from Britain to > represent their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? > > Be blunt. We Americans need to know. Should we try to change the way we > speak? Are there certain words that sound particularly goofy? Please > help us with your advice on this awkward matter. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mwm at mired.org Mon Jun 6 16:50:38 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 06 Jun 2005 15:50:38 -0500 Subject: Destructive Windows Script References: Message-ID: <868y1n8b1d.fsf@guru.mired.org> "Terry Reedy" writes: > On *nix, one could open '/dev/rawdisk' (actual name depends on the *nix > build) and write a tracks worth of garbage for as many tracks as there are. > I don't how to programmaticly get the track size and number (if there is a > standard way at all). Modern Unix systems assume drives don't care much about geometry, what with sector forwarding and variable track lengths and the like. Just open the raw disk device (assuming your Unix has such), and start writing data to it. Keep going until the write fails at the end of the media. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From skn at skn.com Mon Jun 20 09:06:27 2005 From: skn at skn.com (skn) Date: Mon, 20 Jun 2005 18:36:27 +0530 Subject: JEP and JPype in a single process Message-ID: Hello, I have written a very simple java class file, which invokes a Python script using JEP. Code snippet:- ------------------- Jep jep = new Jep(false); jep.runScript("C:\\temp\\testscript.py"); jep.close(); Now inside this Python script I want to make Java calls using JPype. If I use startjvm() inside this Python script, a Runtime Error (exception) is thrown. Also tried attachThreadToJVM(), but doesn't work, again Runtime Error. Any clues as to how I could achieve my goal?? The interaction shown below should happen in a single process. JAVA ==> jep ==> PYTHON ==> jpype ==> JAVA Regards, skn From tzot at sil-tec.gr Tue Jun 21 06:31:33 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 21 Jun 2005 13:31:33 +0300 Subject: getting list of all available modules References: <87d5qgsddt.fsf@penguin.brutt.org> Message-ID: <41rfb11gtmk94k8gk6iciaomnbm6l370vi@4ax.com> On Tue, 21 Jun 2005 01:33:06 GMT, rumours say that Benjamin Rutt might have written: >I note that the help() function of interactive python can determine >all available modules: >I want to do the same (get all such modules in a python list); how can >I do so? Or where is the code for the REPL for help() itself so I can >find out myself? Try browsing the site.py file in your standard lib directory; there's a _Helper class that is what you are looking for. help is an instance of _Helper, as you can see by typing in the interactive prompt: >>> type(help) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From rkern at ucsd.edu Mon Jun 27 02:09:49 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 26 Jun 2005 23:09:49 -0700 Subject: A Module on Time & Date In-Reply-To: References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: Robert Maas, see http://tinyurl.com/uh3t wrote: >>From: John Abel >>time - http://docs.python.org/lib/module-time.html > > Ah, thanks! It works here, whereas: > >>datetime - http://docs.python.org/lib/module-datetime.html > > doesn't work, no such module, see: > http://groups-beta.google.com/group/comp.lang.python/msg/0e4307f5cfa28b6a > Message-ID: > > Anyway, I'll update my one-step-after-hello-world demo for Python > tomorrow or sometime to include the time stuff. As you can see in the datetime documentation, the module was introduced in Python 2.3. I recommend updating your Python installation. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From cravephi at hotmail.com Thu Jun 2 04:49:10 2005 From: cravephi at hotmail.com (cravephi at hotmail.com) Date: 2 Jun 2005 01:49:10 -0700 Subject: wxpython or PyQT to make a simulink clone ? In-Reply-To: References: <1117699017.376196.37930@f14g2000cwb.googlegroups.com> Message-ID: <1117702150.052730.83640@g14g2000cwa.googlegroups.com> thank you. I am watching the exemple of OGL. Very interesting! From fargo_01 at hotmail.com Mon Jun 13 08:00:33 2005 From: fargo_01 at hotmail.com (fargo) Date: Mon, 13 Jun 2005 14:00:33 +0200 Subject: MD5 problem Message-ID: <42ad7561$0$1325$636a15ce@news.free.fr> Hi. I'm in trouble with the md5 module. Under Linux, it's ok, I get real signatures. The problem is under Windows XP, with some kind of files. If I use the md5 module with .txt files, it'ok. The Problem comes from the .msg files. I get the same signature for every .msg file I try to hash with the md5 algorithm. I think some character are strange for python, and makes it stop before the end of the .msg file. So, my question is : Do anybody have a solution to this problem ? (I can post my source code if needed) Thank you. From patrick.down at gmail.com Tue Jun 7 11:18:33 2005 From: patrick.down at gmail.com (Patrick Down) Date: 7 Jun 2005 08:18:33 -0700 Subject: If - Or statements References: Message-ID: <1118157507.942274.45410@g43g2000cwa.googlegroups.com> What about: if True in [thefile.endswith(x) for x in ('mp3','mp4','ogg','aac','wma')]: From timr at probo.com Sat Jun 11 01:59:27 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 10 Jun 2005 22:59:27 -0700 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: Renato Ramonda wrote: >Tim Roberts ha scritto: > >> wx uses "sizers" to do the same thing. Same purpose, different philosophy. >> I find sizers more natural, but people should certainly stick to whatever >> makes them comfortable. > >I like sizers too, but in my experience wx apps do not use them. Are >they by chance something that came with the 2.5/2.6 development cycle? >That version is still pretty rare in real world applications. Hardly. Sizers have been the primary method of placing multiple controls in wx for as long as I've been using it, which goes back to 2.3. In fact, it's hard to create a non-trivial wx app WITHOUT using sizers. All of the wx GUIs place controls in nested sets of sizers. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From duikboot at localhost.localdomain Tue Jun 14 03:15:17 2005 From: duikboot at localhost.localdomain (db) Date: Tue, 14 Jun 2005 09:15:17 +0200 Subject: regarding cgi References: Message-ID: I think you should give another header: Content-type: text/html regards Arjen On Tue, 14 Jun 2005 07:00:09 +0100, praba kar wrote: > Dear All, > > I have doubt regarding headers in cgi > programming. If I gives "Content-Type:text/plain" > then I try to print html contents. Is right or wrong > after giving content-type: text/plain? > > regards > Prabahar > > > > > _______________________________________________________ > Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From baas at ira.uka.de Fri Jun 24 17:12:08 2005 From: baas at ira.uka.de (Matthias Baas) Date: Fri, 24 Jun 2005 23:12:08 +0200 Subject: ANN: Python Computer Graphics Kit v2.0.0alpha4 Message-ID: <8mtob1hofmkq9nvujo1d1ucc0sft3mcvbj@4ax.com> The fourth alpha release of version 2 of the Python Computer Graphics Kit is available at http://cgkit.sourceforge.net What is it? ----------- The Python Computer Graphics Kit is a generic 3D package written in C++ and Python that can be used for a variety of domains such as scientific visualization, photorealistic rendering, Virtual Reality or even games. The package contains a number of generic modules that can be useful for any application that processes 3D data. This includes new types such as vectors, matrices and quaternions. Furthermore, the package can read and store 3D models in memory where they can be manipulated by Python programs. The kit comes with tools that can be used to display the scene either interactively or by rendering it offline via a RenderMan renderer. What's new? ----------- - The render tool can now also be used to bake texture maps (using the technique from the Stupid RAT Tricks 2001 by J. Litt and D. Goldman, so no special renderer functionality required). A tutorial is available on the web site: http://cgkit.sourceforge.net/tutorials/baking/baking.html) - PLY import and export using Diego Nehab's RPly library - A Maya .ma file parser and partial support for importing the contents of a .ma file (polys without history, cameras, lights, skeletons, ...) - The near and far plane of the cameras can now be controlled explicitly - New RMLightSource object that wraps a RenderMan light source shader - A new MEL script to export ASF/AMC files + several other enhancements and bugfixes (see changelog) Windows binary versions are available for Python 2.3 and Python 2.4. For more information, visit: http://cgkit.sourceforge.net - Matthias - From zren at amylin.com Fri Jun 17 13:19:04 2005 From: zren at amylin.com (zren at amylin.com) Date: 17 Jun 2005 10:19:04 -0700 Subject: Programmatically bring a window to front Message-ID: <1119028744.722262.320000@z14g2000cwz.googlegroups.com> Hi, I wonder if anyone knows how to programmatically make a python window get focus and bring it to front. Here a python window means the Tkinter Toplevel widget. Thanks. Zhen From http Thu Jun 9 22:04:36 2005 From: http (Paul Rubin) Date: 09 Jun 2005 19:04:36 -0700 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: <7xk6l33r2j.fsf@ruckus.brouhaha.com> "wooks" writes: > I am somewhat nonplussed that the opportunity to buy a Python book > cheaply is off limits for this NG. There have been alot of hits and as > there are very few Python books listed on Ebay I presume they came from > here. One really annoying thing is when the subject line doesn't indicate that the message is about an item for sale or for auction. It's also annoying when the subject says "for sale" but it's really an auction. If you have a Python book for sale, that's reasonably on-topic for the newsgroup, but the subject should say "For sale, copy of Python developer's handbook", and the post should include the selling (not auction) price. "For sale" can be abbreviated FS. If it's an auction, use "For auction" or "FA" instead of "For sale" or "FS". Such posts might still, strictly speaking, be off-charter, but as long as they're only occasional and noncommercial, and clearly labelled as described, IMO they are not too bothersome. From skip at pobox.com Thu Jun 23 09:58:30 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 23 Jun 2005 08:58:30 -0500 Subject: pydoc - suppressing builtins? In-Reply-To: <1119519053.138956.298930@z14g2000cwz.googlegroups.com> References: <1119519053.138956.298930@z14g2000cwz.googlegroups.com> Message-ID: <17082.49158.719652.850993@montanaro.dyndns.org> Alan> Is it possible to persuade pydoc not to include documentation for Alan> methods inherited from built-in classes? .... Alan> I'm sure I could qite easily write something to post-process the Alan> HTML files; just wondering if there might be an easier way. If you're going to go to the trouble of writing something to post-process the HTML, maybe it would be no more difficult to simply patch pydoc, then everyone wins. Skip From bdesth.quelquechose at free.quelquepart.fr Wed Jun 1 16:35:37 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Jun 2005 22:35:37 +0200 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117649335.285175.95350@g49g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> <1117648438.079178.92490@z14g2000cwz.googlegroups.com> <1117649335.285175.95350@g49g2000cwa.googlegroups.com> Message-ID: <429e16b6$0$28699$626a14ce@news.free.fr> infidel a ?crit : > Oh great, just when I thought I was starting to grok this mess. +1 dont-worry-no-normal-humain-brain-can-handle-this-kind-of-stuff-ly'yrs From bogus@does.not.exist.com Fri Jun 10 09:35:02 2005 From: bogus@does.not.exist.com () Date: Fri, 10 Jun 2005 13:35:02 -0000 Subject: No subject Message-ID: #! rnews 2612 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Generating HTML from python X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 70 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <67Xpe.2446$%j7.824 at newssvr11.news.prodigy.com> Mime-Version: 1.0 Date: Fri, 10 Jun 2005 13:16:36 GMT Xref: news.xs4all.nl comp.lang.python:381106 "Philippe C. Martin" writes: > PS: I am looking at the formatter module which seems to be related to HTML > somehow, but without any code sample I'm a bit lost As others have noted, if you need any computation at all, it is easier to write directly in python. I came to python from perl, where I used CGI.pm. To get that effect, I wrote my own CGIpm.py and used it for a while. http://www.seanet.com/~hgg9140/comp/index.html But (at the suggestion of others in this newsgroup), I then tried writing directly. The net effect is trivial html generation, with all the power of python at your fingertips. Note: To save even more time, I made a CGI template that includes this main: #============================ if __name__=="__main__": mystart() #cgi.print_environ_usage() #cgi.print_environ() form = cgi.FieldStorage() try: if len(form)==0: send_form1() else: form_name=form['form_name'].value if form_name=='form1': recv_form1() except StandardError, e: print "\n
ERROR: %s\n" % e myend() To support a stateless world: 1. Each form has a send_xyz and recv_xyz function. The end of each recv_xyz decides what send_xyz to do next. 2. mystart and myend handle opening and closing the http and html. They also handle state save/restore as needed (pickle or database). > > > Philippe C. Martin wrote: > > > Hi, > > > > I wish to use an easy way to generate reports from wxPython and feel > > wxHtmlEasyPrinting could be a good solution. > > > > I now need to generate the HTML wxHtmlEasyPrinting can print: I need to > > have a title followed by lines of text that do not look too ugly. If > > possible I would like to use an existing module. > > > > Q1) Is there such a module ? > > Q2) Is my approach fairly good ? > > > > Regards, > > > > Philippe > -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From dkirby at blueyonder.co.uk Fri Jun 24 16:33:44 2005 From: dkirby at blueyonder.co.uk (dkirby at blueyonder.co.uk) Date: 24 Jun 2005 13:33:44 -0700 Subject: ANN: Python Mock 0.1.0 released Message-ID: <1119645224.083176.257460@g49g2000cwa.googlegroups.com> I am pleased to announce the first release of Python Mock (version 0.1.0) on SourceForge: http://sourceforge.net/projects/python-mock/ About Python Mock ----------------- The Python Mock library enables the easy creation and use of Mock objects for Python unit testing, inspired by the various Java mock object tools. Mock objects facilitate unit testing by acting as replacements for classes that the object being tested must interact with. The Mock object can accept any method call and return a canned value. The call is recorded by the Mock object and can be examined later by the test code. The Mock objects can have expectations about how they are used, to assert that they are being used correctly. The Mock objects can also validate themselves against the class being mocked, checking that the methods called exist on the real object and have the right parameters. This ensures that the tests stay in sync with the classes being mocked. The Mock class can also be used to as a mixin with a regular Python class to provide recording of method calls and setting expectations on non-Mocked methods. This enables the Mock class to be used for diagnostic purposes as well as for testing. Python Mock was originally launched in 2001 on the Extreme Programming Yahoo Group by Dave Kirby, but has not been widely available outside of the group. It has recently been updated and enhanced with the assistance of Bruce Cropley. It is under active development by both Dave and Bruce, so expect more releases in the near future. Python Mock is released under the BSD license and is free for both commercial and non-commercial use. Dave Kirby From Joost.Jacob at gmail.com Tue Jun 21 10:26:20 2005 From: Joost.Jacob at gmail.com (Joost Jacob) Date: 21 Jun 2005 07:26:20 -0700 Subject: use a regex or not? References: <1119363495.274573.131630@g14g2000cwa.googlegroups.com> Message-ID: <1119363980.041597.127140@g44g2000cwa.googlegroups.com> Oops, the 3rd test should be fill('bb', p='Aa') resulting in the empty dict {} because no binding for A can be found. From kamenzky at inf.fu-berlin.de Mon Jun 6 15:07:08 2005 From: kamenzky at inf.fu-berlin.de (Nico) Date: Mon, 6 Jun 2005 21:07:08 +0200 Subject: OT: Survey facing design patterns and communication Message-ID: Hello everybody! We are a group of students at "Freie Universitaet Berlin". As part of our computer science studies we are going to do a survey facing the use of design patterns in communication. Examples of design patterns are "Abstract Factory", "Singleton", "Composite", "Iterator" and "Listener". If you know what we are talking about, you are welcome to take part in our survey. It takes about 5 minutes to fill out the form. Just jump to: http://study.beatdepot.de If you agree, we will send you the results of our survey. Thanks in advance for your participation! And sorry for the interruption of your discussion. From andreas at kostyrka.org Fri Jun 10 10:57:35 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 10 Jun 2005 16:57:35 +0200 Subject: Perl s/ To Python? In-Reply-To: <42A99C41.6050207@plus.net> References: <42A99C41.6050207@plus.net> Message-ID: <20050610145735.GA3771@heaven.kostyrka.org> I'd consider taking a look at the re module ;) Andreas On Fri, Jun 10, 2005 at 02:57:21PM +0100, John Abel wrote: > Does anyone know of a quick way of performing this: > > $testVar =~ s#/mail/.*$##g > > The only way I can think of doing it, is: > > mailPos = testVar.find( "mail" ) > remainder = testVar[ :mailPos ] > > Any ideas would be appreciated. I'm iterating over a lot of entries, > and running these lines for each entry. > > J > > > -- > http://mail.python.org/mailman/listinfo/python-list From deetsNOSPAM at web.de Thu Jun 2 08:34:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 02 Jun 2005 14:34:47 +0200 Subject: DOM question References: Message-ID: > However, I got exactly the same problem: each time I use this function I > just get a DOM Text node with a few white space (tabs and returns) in > it. I guess this is the indentation in my source document? But why do I > not get the propert element nodes? Welcome to the wonderful world of DOM, Where insignificant whitespace becomes a first-class citizen! Use XPath. Really. It's well worth the effort, as it is suited for exactly the tasks you presented us, and allows for a concise formulation of these. Yours would be (untested) //section[id==$id_param]/node()[!name() == section] It looks from the root throug all the descending childs // after nodes with name section section that fulfill the predicate [id==$id_param] >From this out we collect all immediate children /node() that are not of type section [!name() == section] -- Regards, Diez B. Roggisch From fphsml at gmail.com Fri Jun 17 23:42:24 2005 From: fphsml at gmail.com (James) Date: 17 Jun 2005 20:42:24 -0700 Subject: UML to Python/Java code generation In-Reply-To: <873brhufez.fsf@hector.domek> References: <873brhufez.fsf@hector.domek> Message-ID: <1119066144.174522.193340@f14g2000cwb.googlegroups.com> Peter Dembinski wrote: > "Grigoris Tsolakidis" writes: > > > There is tool to generate UML from Python Code... > > The best is human brain. No! It isn't. In fact, it's the worst. The brain may be fine for generating Python from UML but it is MANY MANY orders of magnitude harder to generate UML from code with just your brain than using a tool (usually zero effort and error free) no matter how good you are at Python. From michele.simionato at gmail.com Thu Jun 16 01:24:28 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jun 2005 22:24:28 -0700 Subject: dynamic In-Reply-To: References: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> Message-ID: <1118899468.786811.326800@g43g2000cwa.googlegroups.com> I think using __new__ when a plain old factory method would work is horrible. But I am not saying that there no use cases for __new__. I used it once, when I wanted a class working for the final user as a factory function. I just wrote the class in lower case and gave it a custom __new__ method. Michele Simionato From mauriceling at acm.org Wed Jun 1 01:42:44 2005 From: mauriceling at acm.org (Maurice LING) Date: Wed, 01 Jun 2005 15:42:44 +1000 Subject: something like CPAN, PPMs? References: Message-ID: Hi Alex, I am actually working on something like that as an academic project. At this stage, at least for the purpose of my scope, it will not be as extensive as CPAN but a set of mechanisms for the same effect for Python. maurice Alex Gittens wrote: > I'm new to Python from Perl, and loving it. Has there ever been any > discussion of creating a similar resource as CPAN for Python, or a > similar distribution method as PPMs? Seems like it would make a great > language even better. > > Alex From listserver at tdw.net Thu Jun 9 12:23:53 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 9 Jun 2005 17:23:53 +0100 Subject: help with sending mail in Program References: Message-ID: <007101c56d0f$a0afa5d0$ccbefea9@twilliams> ----- Original Message ----- From: "Ivan Shevanski" I think this seems like it would work, but I still can't seem to get it to work. I turned on the debugging and everything seemed alright. I'll post how I modified it (I probally made a simple mistake). Can someone help here? #!/usr/local/bin/python ''' Send mail to me ''' from smtplib import SMTP def sendToMe(subject, body): me = '"Ivan Shevanski" ' send(me, me, subject, body) def send(frm, to, subject, body): s = SMTP() #///On or off for test\\\ #s.set_debuglevel(1) s.connect('mail.hotmail.com',) s.ehlo('69.137.27.32') # IP address of my computer, I don't remember why I needed this msg = '''From: %s Subject: %s To: %s %s ''' % (frm, subject, to, body) s.sendmail(frm, to, msg) s.sendmail(frm, [to], msg) s.quit() if __name__ == '__main__': sendToMe('test', 'test') It says it sends it but I get nothing in my inbox or anywhere! This is really frustrating me. _________________________________________________________________ [tim williams]> No it definitely works, but Hotmail will blackhole your constructed email as it is obviously fake. It has no headers, dates, msg-id etc. [tim williams]> View the source of a real email in your mail client, then cut & paste the whole thing into your message variable like this msg = ''' ''' [tim williams]> you should remove the " % (frm, subject, to, body) " at the end of the msg string [tim williams]> for correctness, you also need an " s.rset() " in between each " s.sendmail " (but the script does work in its current form) [tim williams]> HTH :) From jatinder at textualanalytics.com Mon Jun 6 02:42:50 2005 From: jatinder at textualanalytics.com (Jatinder Singh) Date: Mon, 6 Jun 2005 01:42:50 -0500 Subject: No subject In-Reply-To: References: <1117875121.42a16bb150ac2@mailbox.textualanalytics.com> <1118035080.42a3dc88558e4@mailbox.textualanalytics.com> Message-ID: <1118040170.42a3f06aad73e@mailbox.textualanalytics.com> B and C are subdirectories of Parent Directory A. I am executing a file in Directory C which is importing a file f' in directory B. Now while running python file m getting an error of can't open f'. If I copy f' in current directory B. then It is running. I want to get rid of that and run the programme without copying the other f' files( even .txt also) in the current directory. and I have so many files in directory B,otherwise I wou;ld have wppended the path while opening the file. I don't want to do it for each file and also If i need to change directory structure then also I should change one path and able to run the Programme. Quoting Tiago St?rmer Daitx : > Well, I still quite don't get what you want to do. I mean, you do need > to be more specific. Maybe you can post part of your code or explain > in details what you are trying to do. Anything that would help me > understand what's going on. > > In the mean time, check these sites... > The file section in the Tutorial (there's not much to see, but hey, > who knows?): > http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000 > > The online book DiveIntoPython > http://diveintopython.org/file_handling/file_objects.html > > Or some common questions about files (maybe you can find the answer > for your troubles - not all of them, of course) =) > http://www.faqts.com/knowledge_base/index.phtml/fid/552 > > Regards, > Tiago S Daitx > > On 6/6/05, Jatinder Singh wrote: > > I am reading a only. But what if I want read write and execute that file. > > > > -- > > Regards, > > Jatinder Singh > > > > " Everyone needs to be loved... especially when they do not deserve it." > > > XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX > > Quoting Tiago St?rmer Daitx : > > > > > That depends on what "using" a file means. You could check the thread > > > "executing a command" ( > > > http://mail.python.org/pipermail/python-list/2005-June/283963.html) and > see > > > if there's something related there, otherwise it would help if you could > > > post what exactly you are trying to do (execute a file, open a file, > write > > > into a file, etc). > > > > > > Regards, > > > Tiago S Daitx > > > > > > On 6/4/05, Jatinder Singh wrote: > > > > > > > > Hi guys > > > > I am working in a complex directory structure. I want to use a file > (not > > > > .py) > > > > which is in some other directory. I couldn't do it.but if I copy the > file > > > > in > > > > the same directory then it is working fine. Can anybody guide me how > and > > > > where > > > > to add the path of the file. I have tried it with sys.path but it is > not > > > > for > > > > that. > > > > > > > > > > > > -- > > > > Regards, > > > > Jatinder Singh > > > > > > > > " Everyone needs to be loved... especially when they do not deserve > it." > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards, Jatinder Singh ? Everyone needs to be loved... especially when they do not deserve it.? From ikang at MIT.EDU Sun Jun 19 17:44:16 2005 From: ikang at MIT.EDU (In Han Kang) Date: Sun, 19 Jun 2005 17:44:16 -0400 Subject: calling subclass constructor question Message-ID: <42B5E730.6070208@mit.edu> Hello everyone and thank you for being such a good community. Anyway, I was wondering...I have an super class which is the superclass for 5 other classes. However, I want to be able to call the subclass constructors from the super class. Is this possible? Thank you in advance From skip at pobox.com Thu Jun 30 22:59:10 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 30 Jun 2005 21:59:10 -0500 Subject: Escaping commas within parens in CSV parsing? In-Reply-To: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> Message-ID: <17092.45438.57220.801572@montanaro.dyndns.org> Ramon> I am trying to use the csv module to parse a column of values Ramon> containing comma-delimited values with unusual escaping: Ramon> AAA, BBB, CCC (some text, right here), DDD Ramon> I want this to come back as: Ramon> ["AAA", "BBB", "CCC (some text, right here)", "DDD"] Alas, there's no "escaping" at all in the line above. I see no obvious way to distinguish one comma from another in this example. If you mean the fact that the comma you want to retain is in parens, that's not escaping. Escape characters don't appear in the output as they do in your example. Ramon> I can probably hack this with regular expressions but I thought Ramon> I'd check to see if anyone had any quick suggestions for how to Ramon> do this elegantly first. I see nothing obvious unless you truly mean that the beginning of each field is all caps. In that case you could wrap a file object and : import re class FunnyWrapper: """untested""" def __init__(self, f): self.f = f def __iter__(self): return self def next(self): return '"' + re.sub(r',( *[A-Z]+)', r'","\1', self.f.next()) + '"' and use it like so: reader = csv.reader(FunnyWrapper(open("somefile.csv", "rb"))) for row in reader: print row (I'm not sure what the ramifications are of iterating over a file opened in binary mode.) Skip From rrr at ronadam.com Mon Jun 20 02:36:42 2005 From: rrr at ronadam.com (Ron Adam) Date: Mon, 20 Jun 2005 06:36:42 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: Message-ID: <_ttte.94827$VH2.91696@tornado.tampabay.rr.com> Ron Adam wrote: > You might be able to use a dictionary of tuples. > > call_obj = {(type_obj1,0):obj1a, > (type_obj1,0):obj1b, > (type_boj2,1):obj2a, > (type_obj2,1):obj2b, > etc... } > call_obj[(type_of_obj,order)]() > > > Regards, Ron This won't work like I was thinking it would. But to get back to your is there a ? operator question... Try this. def foo(): return "foo" def boo(): return "boo" print (foo, boo)[1>0]() # prints "boo" print (foo, boo)[1<0]() # prints "foo" Regards, Ron From siyer at Princeton.EDU Fri Jun 24 14:45:21 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Fri, 24 Jun 2005 14:45:21 -0400 Subject: Frame widget (title and geometry) Message-ID: Here is an example of what I tried to do: from Tkinter import * import classtitle import classtitle2 BLUE1 = '#7080B0' RED1 = '#B08080' class Master(Frame): def createWidgets(self): self.FrameOne = Frame(self) self.FrameOne.grid(sticky = NW) self.FrameOne["background"] = BLUE1 self.FrameOneClassInstance = classtitle.constructor(self.FrameOne) self.FrameTwo = Frame(self) self.FrameTwo.grid(sticky = SW) self.FrameTwo["background"] = RED1 self.FrameTwoClassInstance = classtitle2.constructor(self.FrameTwo) def __init__(self,master = None): Frame.__init__(self,master) self.pack() self.createWidgets() app = Master() app.mainloop() The constructor methods in the two classes call, for example, self.FrameOne.geometry or self.FrameTwo.title and then I get errors which claim that these attributes do not exist. I do think, however, that the Frame widget is what I want to use. I want to partition my root window into several smaller sections. Shankar From rbt at athop1.ath.vt.edu Sun Jun 5 21:16:34 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 05 Jun 2005 21:16:34 -0400 Subject: Destructive Windows Script In-Reply-To: References: Message-ID: Chris Lambacher wrote: > The reason they are slow and tedious is that they need to write to > every byte on the disk. Depending on the size of the disk, there may > be a lot of data that needs to be written, and if they are older > computers, write speed may not be particularly fast. OK, I accept that, but if you have a HDD that's 8GB total and it has 1GB of files, why must every byte be written to? Why not just overwrite the used portion? From petr at tpc.cz Tue Jun 21 23:14:23 2005 From: petr at tpc.cz (McBooCzech) Date: 21 Jun 2005 20:14:23 -0700 Subject: subprocess.call(*args **kwargs) on Linux In-Reply-To: References: <1119265420.031534.29250@g49g2000cwa.googlegroups.com> Message-ID: <1119410063.822694.243370@f14g2000cwb.googlegroups.com> Thanks a lot :) Petr From trentm at ActiveState.com Thu Jun 9 11:29:58 2005 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 9 Jun 2005 08:29:58 -0700 Subject: killing process in windows In-Reply-To: <20050609090629.GM3544@zoran.com> References: <20050606134839.36485.qmail@web32510.mail.mud.yahoo.com> <20050609090629.GM3544@zoran.com> Message-ID: <20050609152958.GA22482@ActiveState.com> [Miki Tebeka wrote] > Hello Veronica, > > > I am using Trent's process.py but I have a problem with killing the > > processes in windows. > > For example : > > > > import process,time > > > > p=process.ProcessOpen('C:\Program Files\Windows Media > > Player\wmplayer') > > time.sleep(3) > > p.kill() > > > > will start Media Player without terminating it. > > Any suggestions? > A brutal way will be to use win32process.TerminateProcess (from win32all > package - http://starship.python.net/crew/mhammond/). Miki, actually my process.py *is* using TerminateProcess under the hood here. Veronica, Sorry, I really don't know what might be causing the problem here. Does your little snippet work properly for other applications like, say, Notepad, iexplore.exe, Word? Note that I'm am going to put the path in a list to be sure that the it gets quoted properly. It *might* be correct as just a string (as you had it) but I'd have to check. If you do this in the interactive shell (don't quit the shell): >>> import process >>> p = process.ProcessOpen(["C:\Program Files\Windows Media Player\wmplayer"]) Does media player start? Is there a "wmplayer.exe" is the process list (press Ctrl+Esc to open Task Manager)? Now try this is the same interactive shell: >>> p.kill() Trent -- Trent Mick TrentM at ActiveState.com From chinook.nr at tds.net Tue Jun 28 02:14:02 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 02:14:02 -0400 Subject: OO refactoring trial ?? Message-ID: <0001HW.BEE662EA001C5E91F00FF3B0@smtp.tds.net> OO refactoring trial ==================== Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy "if" sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the "doit" methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach 2) The implications of using this in a recursive approach (referenced from but outside the recursive function) and if the decorators help with such. 3) Any other comments you might offer Thank you, Lee C =========== ootest.py ============ class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): if tv == 'relates to A': return True else: return False def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): if tv == 'relates to B': return True else: return False def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() ======== Test run ============== Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> import ootest # did B # # did A # >>> From ramen at lackingtalent.com Tue Jun 7 20:49:15 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 07 Jun 2005 17:49:15 -0700 Subject: Help! File objects and scoping In-Reply-To: References: Message-ID: bens wrote: > I'm trying to return an 'mmap' object from a function. The return > works, but some of the object's methods crash. Here are two examples > > doesntwork.py > --------------------------- > import mmap > import os > > name="/any/real/file/on/my/hard/drive" > > def getfile(name): > somefile=file(name, 'r+b') > mmapped = mmap.mmap(fileno=somefile.fileno(), \ > length=os.path.getsize(name)) > return mmapped Here's the problem: the "mmap" object doesn't have a reference to "somefile", only to its file descriptor number. So, when getfile() goes out of scope, there are no references left, and the file gets closed automatically. One way to avoid this problem is to return the file object as well as the "mmap" object, ie.: def getfile(name): somefile = file(name, 'r+b') mmapped = mmap.mmap(fileno=somefile.fileno(), length=os.path.getsize(name)) return (somefile, mmapped) (somefile, mmapped) = getfile(name) # do something with mmapped... Now, as long as you keep "somefile" in scope, the file won't get closed. You could also build an object and make both "somefile" and "mmapped" attributes of this object. Caveat: There may be a better way of doing this. I've never used "mmap". Dave From steve at REMOVETHIScyber.com.au Mon Jun 13 19:23:07 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 14 Jun 2005 09:23:07 +1000 Subject: \r\n or \n notepad editor end line ??? References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> <0q-dnXbbdaJNAzDfRVn-gA@powergate.ca> Message-ID: On Mon, 13 Jun 2005 10:52:52 -0400, Peter Hansen wrote: > Steven D'Aprano wrote: >> When you read a Windows text file using "r" mode, what happens to the \r >> immediately before the newline? Do you have to handle it yourself? Or will >> Python cleverly suppress it so you don't have to worry about it? >> >> And when you write a text file under Python using "w" mode, will the >> people who come along afterwards to edit the file in Notepad curse your >> name? Notepad expects \r\n EOL characters, and gets cranky if the \r is >> missing. > > This is Python. Fire up the interactive interpreter and try it out! It > will take all of two or three minutes... Which I would have done, except see comment below: >> How does this behaviour differ from "universal newlines"? > > If you open a text file created with a different line-ending convention > than that used on your own platform, you may get "interesting" results. I'm using Linux, not Windows. Of course I *could* try to fake reading and writing Windows files from Linux, but that would require me actually understanding how Python deals with line endings across the platforms in order to generate them in the first place. But if I understood it, I wouldn't have needed to ask the question. And I would still be none the wiser about Python's behaviour when running under Windows -- that's hard to fake on a Linux box. > If you use "rU" instead, you will receive only \n line endings and not > have anything to worry about. (For example, reading a Windows text file > on Linux will give you lines that have \r\n endings in them... not what > you really want. Using "rU" will give you just \n line endings whether > you are on Linux or Windows.) So going back to the original question... if I open in "r" mode a text file which was created under Windows, I will get \r characters in the text and have to deal with them regardless of what platform I am running Python under. Correct? If I use "rU" mode Python suppress the \r characters. When I write a string back, I'm responsible for making sure the EOL markers are correct for whatever platform I expect the file to be read under. Unless Python can somehow magically read my mind and know that even though I'm writing the file under Linux it will be read later under Windows. Am I close? (Ew, I hate cross-platform issues. They make my head hurt.) -- Steve. From rschroev_nospam_ml at fastmail.fm Wed Jun 15 16:37:25 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 15 Jun 2005 20:37:25 GMT Subject: Does Python cause tides? In-Reply-To: References: <42AFB8FD.1060504@REMOVEMEcyber.com.au> Message-ID: <9k0se.121693$jS6.7008313@phobos.telenet-ops.be> Terry Hancock wrote: > "Plants consume CO2 and make O2" > > Well, yes, but they also consume O2, just like animals. *On balance*, > the statement is *usually* true. But most plants would probably > die in a pure-CO2 environment (unless they can drive the atmosphere > to a better composition fast enough). Ha, finally one I can comment one with a reasonable level of confidence. On balance, plants consume CO2 and produce O2 *as long as they are growing*. You see, they use the C from the CO2 to build the material they are made of. Once they are full-grown, the amount of O2 produced by their photosynthesis is balanced by the amount of O2 consumed by their respiration; the same goes for the CO2 produced in consumed in both processes. This can be generalized to whole forests too. Often people think that the Amazon rain forests produce large quantities of O2, but that's just not true. During their initial growth, they indeed produced large quantities of O2. As long as they stay the same size (the same amount of biomass actually), there is no net effect. Now that large areas are burnt to make place for roads and agriculture, the CO2 comes back in the atmosphere while O2 from the atmosphere is consumed in the flames. It's very well possible that this is a simplification that glosses over a few details such as other sources of carbon, but in general it's good enough. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mwm at mired.org Sun Jun 5 20:31:38 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 05 Jun 2005 19:31:38 -0500 Subject: GUI builders considered harmful References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> <86fyvwa91z.fsf_-_@guru.mired.org> <87acm48rh7.fsf@cenderis.demon.co.uk> Message-ID: <86slzw8gwl.fsf@guru.mired.org> Bruce Stephens writes: > Mike Meyer writes: > > [...] > >> The first, and most obvious, thing that GUI builders do is force the >> developer to specify an exact position - if not size - for the >> graphical elements of the UI. > > They do? I don't remember them doing that. I just downloaded SpecTcl > (a oldish example) just to check, and that doesn't. I presume more > recent ones work no less well? > > I seem to remember that the GUI builder in Visual Studio didn't seem > to be particularly sane (I couldn't seem to work out how to get a > dialog to resize appropriately to accommodate different font sizes, > for example), but I assumed that was just me failing to understand > something. In my experience, they do. But as noted, my experience is limited. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From peter at engcorp.com Thu Jun 9 08:02:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 08:02:54 -0400 Subject: Premature script error In-Reply-To: References: Message-ID: Jatinder Singh wrote: > I am running a CGI Programme. > which is throwing Premature script error for some inputs. > I have checked and couldn't fig out the problem. > Even error log is empty. > Can anybody help me out of this or can I use try except to catch the Error and > how? > plz get back soon .Its urgent Please always post the *exact* error message you are getting, including as much context as possible. Cut and paste the text from your output window: do _not_ just retype it and remove critical information as you have done above. -Peter From fredrik at pythonware.com Wed Jun 1 09:33:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 1 Jun 2005 15:33:58 +0200 Subject: Elementtree and CDATA handling References: <1117631202.723453.20060@z14g2000cwz.googlegroups.com> Message-ID: alainpoint at yahoo.fr wrote: > There are two problems: the // > and && have been replaced by their equivalent entities (CDATA should > have prevented that). > I am no XML/HMTL expert, so i might be doing something wrong... you're confusing the external representation of something with the internal data model. consider this: >>> "hello" >>> 'hello' >>> "hell\x6f" >>> "hell\157" >>> "hell" + "o" >>> 'h' 'e' 'l' 'l' 'o' the above are six ways to write the same string literal in Python. all these result in a five-character string containing the letters "h", "e", "l", "l", and "o". if you type the above at a python prompt, you'll find that Python echoes the strings back as 'hello' in all six cases. in XML, entities, character references, and CDATA sections are three different way to represent reserved characters. once you've loaded the file, they all "dis- appear". From mg.mailing-list at laposte.net Fri Jun 3 12:10:22 2005 From: mg.mailing-list at laposte.net (mg) Date: Fri, 03 Jun 2005 18:10:22 +0200 Subject: bdist_wininst to distribute a patched python Message-ID: <42A080EE.1030502@laposte.net> Hi, Because of I have patched Python, I would like to create a Windows installer containing my patched-Python. So, I try to use the option 'bdist_wininst' on the setup.py file distributed by python.... it is supported ? If yes, I have a problem : the run tell me that pyconfig.h does not exist. What is the solution ? Thanks From thys at sentechsa.com Wed Jun 8 06:03:35 2005 From: thys at sentechsa.com (Thys Meintjes) Date: Wed, 08 Jun 2005 12:03:35 +0200 Subject: School Administration Software In-Reply-To: <42A5BEB2.3040505@novasyshealth.com> References: <42A5BEB2.3040505@novasyshealth.com> Message-ID: <1118225015.21472.1.camel@localhost.localdomain> On Tue, 2005-06-07 at 10:35 -0500, Greg Lindstrom wrote: I would check out the shuttleworth foundation's schooltool http://www.schooltool.org/ > Hello- > > I just picked up my daughters' report cards for the year (they did well, > thank-you) and was approached by the school administrator about writing > an Acess application to help track attendance for next year > (excused/unexcused, after so many unexcused absences a letter will be > generated, etc.). Since I have a feel for how large this request will > become, I googled for school administration software on the Python site > and was pleased to get 312 "hits". There's software out there but -- > alas -- it's difficult to tell what is being used, what people think, > what's being maintained, etc. > > So...do any of you have experience with any of this software? This is > for a small (~400 students k-12), private school that is not swimming in > taxpayer dollars and I would rather use Open Source because we will > probably need to customize some reports, etc. Any advice you have would > be welcome. > > Thanks, > --greg > > -- > Greg Lindstrom 501 975.4859 (office) > Senior Programmer 501 219-4455 (fax) > NovaSys Health greg.lindstrom at novasyshealth.com > Little Rock, Arkansas > > "We are the music makers, and we are the dreamers of dreams." W.W. > > From erinhouston at gmail.com Fri Jun 24 16:42:51 2005 From: erinhouston at gmail.com (erinhouston at gmail.com) Date: 24 Jun 2005 13:42:51 -0700 Subject: Office COM automatisation - calling python from VBA In-Reply-To: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <1119645771.152174.7170@g43g2000cwa.googlegroups.com> Can you make python into a com object? I think you can I just don't rember. If so you want to find a page about com add-ins for office. This is a com object that you can teach office to look for when It is started. I wrote one in vb years ago and havn't looked back. But I think that would be the way to go. From kveretennicov at gmail.com Sat Jun 25 05:01:11 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 25 Jun 2005 11:01:11 +0200 Subject: windows service problem In-Reply-To: References: Message-ID: <4660fe30050625020175da3d75@mail.gmail.com> On 6/24/05, Austin wrote: > def __init__(self,args): > win32serviceutil.ServiceFramework.__init__(self,args) > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > self.check = 1 Change last two lines to self.check = 1 self.hWaitStop = win32event.CreateEvent(None, 0, 1, None) (SvcDoRun is waiting for hWaitStop event, but you never signal it.) - kv From nospam at nospam.nospam Mon Jun 27 11:58:46 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Mon, 27 Jun 2005 08:58:46 -0700 Subject: Favorite non-python language trick? References: Message-ID: On 24 Jun 2005 19:09:05 +0400, Sergei Organov wrote: >Steven D'Aprano writes: > >> On Fri, 24 Jun 2005 00:55:38 -0600, Joseph Garvin wrote: >> >> > I'm curious -- what is everyone's favorite trick from a non-python >> > language? And -- why isn't it in Python? >> >> Long ago, I used to dabble in Forth. You could say, the entire Forth >> language was a trick :-) It was interesting to be able to define your own >> compiler commands, loop constructs and so forth. >> >> One of the things I liked in Pascal was the "with" keyword. You could >> write something like this: >> >> with colour do begin >> red := 0; blue := 255; green := 0; >> end; >> >> instead of: >> >> colour.red := 0; colour.blue := 255; colour.green := 0; >> >> Okay, so maybe it is more of a feature than a trick, but I miss it and it >> would be nice to have in Python. > >... that quickly becomes quite messy: - When abused - >with A do begin > ..... > with B do begin > ..... > with C do begin > x := y; > end; > end; >end; Like many features that can be helpful when used well, and harmful when used poorly, it's not a simple question whether it should be in any given language. It also makes sense to consider whether other features already in the language can fill the same need (though I don't know Python well enough to address that yet). Even though I like "With" in VB and use it often, I always consider its use a warning that perhaps that code should be factored into the class somehow. From usenet.20.evilspam at spamgourmet.com Sun Jun 12 10:40:26 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 14:40:26 GMT Subject: How to get/set class attributes in Python In-Reply-To: References: Message-ID: Kalle Anke wrote: > On Sun, 12 Jun 2005 13:59:27 +0200, deelan wrote > (in article ): > > void doSomething( data : SomeClass ){ ... } > > and I would be sure at compile time that I would only get SomeClass objects > as parameters into the method. Being an untyped language, Python does not require you to enforce types. However, for those that require such functionality, you can get away with using the "assert" statement. For example, if I wanted to make sure my function foo was only given instances of class Bar, I'd write something like: >>> class Bar: pass >>> def foo(bar): ... assert isinstance(bar, Bar), "argument is not of type Bar" ... print "argument must be of type Bar" ... >>> bar = Bar() >>> foo(bar) argument must be of type Bar >>> foo(123) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in foo AssertionError: argument is not of type Bar >>> Chris From jhefferon at smcvt.edu Mon Jun 13 07:50:02 2005 From: jhefferon at smcvt.edu (Jim) Date: 13 Jun 2005 04:50:02 -0700 Subject: What language to manipulate text files References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: <1118663402.137850.95990@g43g2000cwa.googlegroups.com> Roose wrote: > Why do people keep asking what language to use for certain things in the > Python newsgroup? Obviously the answer is going to biased. > > Not that it's a bad thing because I love Python, but it doesn't make sense > if you honestly want an objective opinion. It will, however, have the side-effect of helping people who google for it tomorrow. I've often found a several months old answer that people on a group had taken the trouble of patiently answering, which was a big help to me. In this case I can imagine a person who has heard that Python is in a class of languages like Perl and Ruby, and who googles around with some keywords to get some idea of whether it can solve their problem. Jim From rkern at ucsd.edu Sat Jun 11 03:01:42 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 11 Jun 2005 00:01:42 -0700 Subject: Abstract and concrete syntax In-Reply-To: References: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > Beauty is in the eye of the beholder. It seems that relative pythonicity > sometimes is also ;-). Ah, the curse of Pythonicity Relativism! What has society come to that it cannot recognize Absolute Pythonicness and Absolute Perlishness? The measure of Pythonicness was given to us in the inerrant Gospel of Tim! Every word of it is literally True! Incant the words "import this" and you shall see in glowing letters before you the Gospel of Tim. Count the number of verses For and the number Against. If the For verses outnumber the Against, the construct is Pythonic, absolutely and without equivocation for all people as Guido indented. ask-me-how-to-calculate-the-age-of-the-universe-ly y'rs, Acolyte Kern -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jorge at bcs.org.uk Sun Jun 26 08:10:20 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Sun, 26 Jun 2005 13:10:20 +0100 Subject: Background thread or non-blocking raw_input Message-ID: Hi, I've posted this before but the answer given made use of twisted functions that do not work on windows, so i'm forced to repost. Basically, is there a way to have a thread running on the background that over rules the raw_input function? The example I'm working on is something like having a thread that prints "You're taking too long" every 10 seconds, while waiting for input from the user. The problem is that I can only read (and in batch) the thread printout messages on the console after giving something to the raw_input function. Is it not possible to have the thread print its stuff and then return to raw_input() ? Any code examples or pseudo-code or documentation directions will be highly appreciated. Thanks in advance jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: From lambacck at gmail.com Thu Jun 9 17:33:08 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Thu, 9 Jun 2005 17:33:08 -0400 Subject: Remove duplicates from list In-Reply-To: <17fc2016050609125328857d82@mail.gmail.com> References: <17fc2016050609114439ad3fb0@mail.gmail.com> <17fc2016050609125328857d82@mail.gmail.com> Message-ID: You are probably going about solving the problem from the wrong direction: Try something like this, overly verbose variable names used on purpose: regHours = context.getMainPrint(); #let a dictionary do the grouping for us hours_to_libraries_dic = {} for lib in regHours: key = lib.Monday + lib.Tuesday + lib.Wednesday + lib.Thursday + lib.Friday + lib.Saturday + lib.Sunday try: # if the key already exists add to the list of libraries hours_to_libraries_dic[key].append(lib) except KeyError: # if the key does not exists, create a new library list hours_to_libraries_dic[key] = [lib] #print out the timetable for lib_group in hours_to_libraries_dic.values(): print " and ".join([lib.libraryName for lib in lib_group]) a_lib = lib_group[0] print " Monday", a_lib.Monday print " Tuesday", a_lib.Tuesday print " Wednesday", a_lib.Wednesday ....(you get the idea) print " Sunday", a_lib.Sunday print -Chris On 6/9/05, Derek Perriero wrote: > Sorry for not being more clear. I'm using Zope to store the hours of each > library on the campus. The hours of each library will be set on a basis of > Monday - Friday. i.e. Monday for a specific library, let's say Downtown > Campus Library will stored as an attribute of 8am - 9pm, in Zope, and each > day till Friday will be stored as the hours dictate. I'm generating a > print-out based on these hours and info for the general public. The goal of > mine is to group all the libraries under one heading if they have the exact > same hours, to cut back on redundancy when a user looks at it. > So when I say: collect = item.Monday + item.Tuesday + item.Wednesday + > item.Thursday + item.Friday + item.Saturday + item.Sunday, the order is > already this preset configuration. I want 'collect' to be static so it can > compare it against another libraries hours and group it if necessary. The > libraries that fail to be duplicates of other libraries will be generated as > usual under the grouped libraries. They will have a single heading. > > An example can be seen here of what I am trying to achieve: > http://www.libraries.wvu.edu/hours/summer.pdf > These are the outputs I failed to mention last time. > What I want: > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', '8am - > 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - > 8pm9am - 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - > 5pm9am - 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - > 5pm10am - 5pm10am - 5pmClosed'] > > What I am getting now: > > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', '8am - > 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am - > 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - > 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - 5pm9am - > 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - > 5pm10am - 5pmClosed'] > > Thanks, > -Derek > > > On 6/9/05, Chris Lambacher wrote: > > It is very unclear what you are trying to do. Why not explain what > > you want the output to be. You will get better answers. > > > > As a first stab at what you are doing wrong: > > collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday > > + item.Friday + item.Saturday + item.Sunday > > > > The above is string addition and the result is a string. The ouput > > you provide is in fact a list with no duplicates, i.e. there are no > > two strings the same. > > > > If order is not important to you a structure that will give you an > > 'unordered list with no duplicates' is a set (available in the std > > library in Python 2.3 and 2.4, see the cookbook for recipies for > > earlier versions of Python). Note that sets are unordered, i.e. no > > guarentee is made about what order the elements are accessed in when > > you iterate over them. > > > > -Chris > > > > On 6/9/05, Derek Perriero < derek.perriero at gmail.com> wrote: > > > I've been un-triumphantly trying to get a list of mine to have no > repeats in > > > it. First, I'm pulling attributes from Zope and forming a list. Next, > I'm > > > pulling those same values and comparing them against the same list and > if > > > the values equal each other and are not already in the list, they append > to > > > my 'nodupes' list. My current result is showing what I put in I am > getting > > > out. Below the code is my output of 'nodupes' list. Here's the > snippet. > > > > > > regHours = context.getMainPrint(); <---attributes from Zope > > > > > > libslist = [] > > > nodupes = [] > > > > > > #collect libraries > > > for libs in regHours: > > > cache = libs.Monday + libs.Tuesday + libs.Wednesday + libs.Thursday + > > > libs.Friday + libs.Saturday + libs.Sunday > > > libslist.append (cache) > > > > > > #pull repeated values > > > for item in regHours: > > > collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday > + > > > item.Friday + item.Saturday + item.Sunday > > > libName = item.libraryName > > > > > > for libs in libslist: > > > if collect == libs and libs not in nodupes: > > > nodupes.append(libs) > > > > > > My Current Output: > > > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', > '8am - > > > 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am > - > > > 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - > > > 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - > 5pm9am - > > > 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am > - > > > 5pm10am - 5pmClosed'] > > > > > > Thanks > > > > > > > > > > > > > > > > > > -- > > > Perriero, Derek > > > derek.perriero at gmail.com > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > -- > > Christopher Lambacher > > lambacck at computer.org > > > > > > -- > Perriero, Derek > derek.perriero at gmail.com > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Christopher Lambacher lambacck at computer.org From steven.bethard at gmail.com Tue Jun 21 13:17:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Jun 2005 11:17:35 -0600 Subject: utf8 silly question In-Reply-To: <1119373208.663784.230850@g14g2000cwa.googlegroups.com> References: <1119373208.663784.230850@g14g2000cwa.googlegroups.com> Message-ID: <95adnemgWKkt1iXfRVn-rQ@comcast.com> Grig Gheorghiu wrote: >>>>import codecs >>>>print codecs.encode(c, 'utf-8') > > ?? some text Or simply: py> print c.encode('utf-8') ?? some text From der.rudi at planet-dot-nl.no-spam.invalid Tue Jun 28 09:54:44 2005 From: der.rudi at planet-dot-nl.no-spam.invalid (DeRRudi) Date: Tue, 28 Jun 2005 13:54:44 +0000 (UTC) Subject: Open running processes References: Message-ID: It is a wxWindow app. It is a kind of datamanager. it is possible to minimize it to the systray. hmm.. i've thought of an solution using memorymapping. see if it works.. don't know if it is the 'best' or 'safest' way.. but ok. Greetz. ps. I'm always willing to learn! :D From donn at u.washington.edu Thu Jun 16 12:35:02 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 16 Jun 2005 09:35:02 -0700 Subject: __str__ vs __repr__ References: <42b021ba$1@griseus.its.uu.se> <11b16e3mld1s9b7@news.supernews.com> <1118898421.887013@yasure> <11b2rnf9his2qd9@news.supernews.com> Message-ID: In article <11b2rnf9his2qd9 at news.supernews.com>, "John Roth" wrote: > "Donn Cave" wrote in message > news:1118898421.887013 at yasure... > > Quoth "John Roth" : > > ... > > | str() should be something that's meaningful to a human being when > > | it's printed or otherwise rendered. > > > > I can't believe how many people cite this explanation - meaningful, > > friendly, pretty to a human being. What on earth does this mean, > > that couldn't be said more unambiguously? > > > > According to my impression of common applications for Python programs, > > rarely would anyone be looking at the output for esthetic gratification. > > I mean, imagine your users casting an appraising eye over the contours > > of a phrase emitted by the program, and praising the rhythmic effect of > > the punctuation it chose to use, or negative space created by tabs. heh. > > > > Whether for human eyes or any destination, properly formed output will > > carry the information that is required for the application, in a complete > > and unambiguous way and in the format that is most readily processed, > > and it will omit extraneous information. Are we saying anything other > > than this? > > I thought that's what I said. I fail to see how you derive any other > meaning from it. Possibly less verbiage and a concerete example > of how "meaningful" equates to "esthetics that obfustificate understanding" > and does not equate to "immediately useable, without having to wade > through a lot of irrelvant mental transformations" would help my > understanding. Not sure if that's a question. Maybe I can state this more clearly. Observation: Most who responded to this question offered an explanation of __str__ like "friendly to a human being", using one or more of meaningful, friendly or pretty. The online manual uses "informal". 1. These words are woefully ambiguous, to be applied in computer programming. While there may be some kind of absolute basis for esthetic appreciation, that clearly doesn't apply here, and terms like this have to be strictly relative to context created by the application. Summary: By itself, friendly to a human being is a vacuous notion and doesn't help anyone. 2. If we attempt to support the explanation with a more rigorous examination of the principles and how they'd apply to a string conversion, it's hard to make this come out favoring str over repr. In the end, they should both be meaningful and friendly, by any uncontorted definition of those terms. Summary: To the extent that they have any meaning, they are probably applied incorrectly as an explanation of __str__. So, among other conclusions, the documentation should be changed to offer a more sensible explanation of __str__. Donn Cave, donn at u.washington.edu From philippe at philippecmartin.com Sun Jun 12 06:54:26 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sun, 12 Jun 2005 10:54:26 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: I guess because I have mostly worked with embedded systems and that, although I have always tried to put abstraction layers between my applications and the hardware, some constraints still remain at the application level: (memory, determinism, re-entrance,...). You will notice that 99% of the embedded systems with realtime constaints use assembly, C/C++, or ADA. I agree with you and Peter though that these issues need not be treated on a first course. Yet, and depending on the ultimate goal (John spoke of IT versus CS) some of the newly trained folks should know about it. We could not enjoy Python if no one were here to implement its VM, I have not looked at the code, but I gather it is fairly complex and does require an amount of "low level" skills. Regards, Philippe Roy Smith wrote: > "Philippe C. Martin" wrote: >> Yet, many issues that a future software engineer should know are >> mostly hidden by Python (ex: memory management) and that could be >> detrimental. > > I know I'm going out on a limb by asking this, but why do you think future > software engineers should know about memory management? > > I used to worry about register allocation. Today, I don't even know how > many registers any machine I work on has. I used to worry about word > size, > and byte order. I used to worry about whether stacks grew up or down and > addressing modes and floating point formats. Sure, somebody's got to > worry about those things, but most people who write software can be > blissfully ignorant (or, at best, dimly aware) of these issues because > somebody else (compiler writer, hardware designer, operating system > writer, etc) has already done the worrying. > > There used to be a time when you had to worry about how many tracks to > allocate when you created a disk file. When's the last time you worried > about that? From hancock at anansispaceworks.com Wed Jun 22 17:39:37 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 22 Jun 2005 16:39:37 -0500 Subject: A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... In-Reply-To: <7uednX3FwvgU-yTfRVn-pA@powergate.ca> References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> <7uednX3FwvgU-yTfRVn-pA@powergate.ca> Message-ID: <200506221639.37816.hancock@anansispaceworks.com> On Wednesday 22 June 2005 08:23 am, Peter Hansen wrote: > Jack Diederich wrote: > > The '.info' domain also defeats > > the linux 'whois' command to dig for registrar info. > > Maybe so, but it's always pretty easy to Google for "whois" plus the > domain to find a way of doing it via the web, in this case with > http://www.afilias.info/cgi-bin/whois.cgi . > > (It's registered to something called the Institute of Pamela, which > seems to stand for "Peaceful Alliances facilitated by Multilingual, > multiracial Education, handicapable outreach and native Language > Accessibility". I think this thing really exists, making this spam and > not just a farce.) Although there is something ironic about an organization that wants to establish world peace through education and communication without bothering to pay attention to netiquette. Seems like that would've been an obvious first step in making peace on Usenet, anyway. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From robin at reportlab.com Wed Jun 15 11:38:32 2005 From: robin at reportlab.com (Robin Becker) Date: Wed, 15 Jun 2005 16:38:32 +0100 Subject: non OO behaviour of file In-Reply-To: References: Message-ID: <42B04B78.8000601@chamonix.reportlab.co.uk> Michael Hoffman wrote: ..... > > Well, you could use python -u: > unfortunately this is in a detached process and I am just reopening stdout as an ordinary file so another process can do tail -F on it. I imagine ther ought to be an os dependant way to set the file as unbuffered, but can't remember/find out what it ought to be. > """-u Force stdin, stdout and stderr to be totally unbuffered. > On systems where it matters, also put stdin, stdout and stderr in binary > mode. Note that there is internal buffering in xreadlines(), > readlines() and file-object iterators ("for line in sys.stdin") which > is not influenced by this option. To work around this, you will want > to use "sys.stdin.readline()" inside a "while 1:" loop.""" > > Within pure Python there's not a better way that I know of. I keep a > slightly-more generalized Surrogate class around to deal with this > pattern, and then my LineFlusherFile would be a subclass of that. But > it's the same thing, really. -- Robin Becker From philippe at philippecmartin.com Sat Jun 25 15:36:06 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 19:36:06 GMT Subject: Excellent Site for Developers References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: Hi, Not being from anglo-saxon heritage, I keep wondering why spammers always (or very often) get called 'trolls' ? I mean fantasy fiction has brought us many hugly beasts (goblin, warlock, orc, dark elf ....) The trolls, as I recall, grow back their limns once those have been cut by the nice folks. Is that the reason ? Regards, Philippe Do Re Mi chel La Si Do wrote: > > rather... super troll From pdemb at gazeta.pl Mon Jun 13 13:38:27 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Mon, 13 Jun 2005 19:38:27 +0200 Subject: implicit variable declaration and access References: Message-ID: <877jgy88do.fsf@hector.domek> Benji York writes: [snap] >> code = x + '= 0' >> exec(code) > > You should generally stay away from exec for lots of reasons. Code 'refactorizability' is one of them. From Bill at SynectixLtd.com Wed Jun 1 05:40:40 2005 From: Bill at SynectixLtd.com (Bill Davy) Date: Wed, 1 Jun 2005 09:40:40 +0000 (UTC) Subject: DLL load failed: The specified procedure could not be found References: <429cf3cf$1@news.eftel.com> Message-ID: "John Machin" wrote in message news:429cf3cf$1 at news.eftel.com... >> a) What "specified procedure " >> b) SHIP was made by SWIG > > and so presumably was _SHIP ... therefore it appears that you might be > better off asking for help on the SWIG mailing list. I will too. > >> c) Is there some way to find out which DLL and which procedure is >> involved? > > One would expect given the reported context (import _SHIP) that it has > found (somewhere!) a DLL called "_SHIP.pyd" and is looking in it > (unsuccessfully) for an entrypoint called "init_SHIP". > > The usual suspect here would be the C (or C++) compiler messing with the > name of the entrypoint; possible messes include underscores at the front > and/or frame size at the end e.g. "_initfoo at 12" instead of just "initfoo". > Possibly you are using a C[++] compiler that's not the one that SWIG > thinks you are using. > > But exactly which DLL? Given your "interesting" sys.path, it might be an > idea to run python with the -v argument, so you can see where all your > imports are resolved. I've not been able to find where sys.path finds its components and would happily sort them out. It does not seem to be PYTHONPATH or PATH or PYTHON_LIB. I had to make Python as I wanted a debug build for Win32 (and hence E:\Bill\Python-2.4.1\PCbuild\python24_d.zip on sys.path though why the zip I have no idea). I have discovered the symbol __debug__ is True for debug builds. > > Once you have worked out which _SHIP.pyd is the cause, you can inspect it > and determine what entrypoint(s) it has. > > HTH, > John Dear John (and all) That's a great help, really. A simple thing like reminding me of -v (give a man a fish, etc) will help now and hereafter. So, now we can see what Python is trying to do: Python 2.4.1 (#65, May 24 2005, 11:31:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. # trying H:\Husky\HostPC\V1\SHIP\Debug\SHIP_d.pyd # trying H:\Husky\HostPC\V1\SHIP\Debug\SHIP_d.dll # trying H:\Husky\HostPC\V1\SHIP\Debug\SHIP.py # H:\Husky\HostPC\V1\SHIP\Debug\SHIP.pyc matches H:\Husky\HostPC\V1\SHIP\Debug\SHIP.py import SHIP # precompiled from H:\Husky\HostPC\V1\SHIP\Debug\SHIP.pyc # trying H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd # clear[2] __name__ # clear[2] __file__ Traceback (most recent call last): File "H:\Husky\HostPC\V1\SHIP\test1.py", line 15, in ? import SHIP File "H:\Husky\HostPC\V1\SHIP\Debug\SHIP.py", line 5, in ? import _SHIP ImportError: DLL load failed: The specified procedure could not be found. # clear __builtin__._ It's still not clear what procedure could not be found (surely not __file__?!). However, the output from "dumpbin /exports H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd" is: H:\Husky\HostPC\V1\SHIP\Debug>dumpbin /exports H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd Microsoft (R) COFF Binary File Dumper Version 6.00.8447 Copyright (C) Microsoft Corp 1992-1998. All rights reserved. Dump of file H:\Husky\HostPC\V1\SHIP\Debug\_SHIP_d.pyd File Type: DLL Section contains the following exports for SHIP.pyd 0 characteristics 429D76E4 time date stamp Wed Jun 01 09:50:44 2005 0.00 version 1 ordinal base 1 number of functions 1 number of names ordinal hint RVA name 1 0 00001096 init_SHIP Summary 6000 .data 2000 .idata 3000 .rdata 2000 .reloc 1000 .rsrc 20000 .text So _SHIP_d.pyd does export init_SHIP. The odd thing there (to me) is the reference to "SHIP.pyd". Is that coming from SHIP.def which has: LIBRARY "SHIP" The thing that is really bugging me is that this was all working before the weekend :-( I am also posting this to the SWIG mailing list as suggested. TIA Bill From cjw at sympatico.ca Wed Jun 1 09:36:08 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 01 Jun 2005 09:36:08 -0400 Subject: AM_PATH_PYTHON - version problem In-Reply-To: References: Message-ID: <2Rine.14206$_r1.680416@news20.bellglobal.com> Uwe Mayer wrote: > Hi, > > I use the GNU autotools for packaging my python applications. My problem is > that as I have both python2.3 and python2.4 installed the automake macros > always detects the newest version and sets it path variables accordingly. > > How can I package the program for different versions of Python? > (i.e. for generating binary packages) > > Any ideas? > > Thanks, > Ciao > Uwe wxPython provides a method for linking to different Python versions. Robin Dunn's approach might help. Colin W. From borges2003xx at yahoo.it Fri Jun 17 04:03:14 2005 From: borges2003xx at yahoo.it (borges2003xx at yahoo.it) Date: 17 Jun 2005 01:03:14 -0700 Subject: pyrex problem Message-ID: <1118995394.861014.317590@g49g2000cwa.googlegroups.com> hi everyone i'm newbie i try to compile the pyrex module: def controlla(char *test): cdef int limitem,lunghezz,li,l2,f,ii,kk cdef char *t1 cdef char *t2 limitem=4 lunghezz=len(test) l1=lunghezz-limitem+1 l2=lunghezz-limitem+1 f=0 for ii from 0 <= ii < l1-1: for kk from 0 <= kk < l2-1: t1=test[ii:ii+limitem] t2=test[kk:kk+limitem] if (ii<>kk): if t1==t2: f=1 if f==1: break if f==0: return test else: return 'no' but i receive the error: obtaining char * from temporary python value what happens? thanx everyone sorry for silly question. giorgio borghi From dotpyFE at gmail.com Thu Jun 9 20:21:39 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Fri, 10 Jun 2005 00:21:39 GMT Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: Aahz wrote: > In article , > Lucas Raab wrote: > >>Terry Reedy wrote: >> >>>Perhaps you have never seen a newgroup ruined by commercial announcements >>>like I have. >> >>O wise one, we bow to you with your deep knowledge. > > > If that's sarcasm, I suggest you reconsider your attitude. Sorry, but Terry just seemed to come off a little too strong. I'm well aware of the dangers of clicking on a link in an email and the whole nine yards. I realize that Terry is right, but his attackdog respose was offputting. -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From lee at example.com Mon Jun 13 17:08:38 2005 From: lee at example.com (Lee Harr) Date: Mon, 13 Jun 2005 21:08:38 GMT Subject: Show current ip on Linux References: Message-ID: On 2005-06-13, David Van Mosselbeen wrote: > Hi, > Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine > man :-) > > My question is : How can i rwite a script that show my current ip. If i have > more than one network card, the script must then show all used ip. > > It's important that this will work on a linux. i Have rwite some piece of > code that realy work under Windows XP, but the same script wil not work on > Linux. > > Verry thanks to all vulunteers. > This comes up at least once a month. Google. Is. Your. Friend. http://mail.python.org/pipermail/python-list/2005-January/258883.html From gsakkis at rutgers.edu Wed Jun 8 15:08:47 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Jun 2005 12:08:47 -0700 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> <1118256927.157329.87650@o13g2000cwo.googlegroups.com> Message-ID: <1118257727.657073.217730@f14g2000cwb.googlegroups.com> "Jordan Rastrick" wrote: > I'd suggest the only nessecary change is, if objects a,b both define > __eq__ and not __ne__, then a != b should return not (a == b) > > If a class defines __ne__ but not __eq__, well that seems pretty > perverse to me. I don't especially care one way or another how thats > resolved to be honest. > > The ordering comparisons (__lt__, __ge__ etc) are fine as they are I'd > say, since they only come up in the rare cases where __cmp__ isn't > sufficient. > > I'll wait for a bit more discussion on here before starting a PEP - as > I've said I'm only a beginner, and a more experience Pyonista may yet > give a perfectly good argument in favour of the current behaviour. > I've been bitten by this particular wart more than once, so I wrote a metaclass for automating the addition of the missing rich comparisons with the expected semantics: == and != are complementary, and given either of them and one of <, >, <=, >=, the other three are defined. You can check it out at http://rafb.net/paste/results/ymLfVo81.html. Corrections and comments are welcome. Regards, George From spam.csubich+block at block.subich.spam.com Wed Jun 8 20:57:50 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 20:57:50 -0400 Subject: Fast text display? In-Reply-To: <7xvf4otrxd.fsf@ruckus.brouhaha.com> References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> <7xll5ka7mv.fsf@ruckus.brouhaha.com> <7xvf4otrxd.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > We're just talking about a scrolling text window that has to run at > human reading and typing speeds, right? It shouldn't be a problem. > I've used the text widget and found it to be fast enough for what I > was doing, though I didn't exactly stress it. It should have burst speeds of 2-10x reading speed; given the stop-and-start nature of most muds, the data comes in bursts that the player processes and reacts to before the next burst. It's good to know that my concerns seem mostly unfounded. When I get to a reasonable state of implementation, I'll post here if I've made any unexpected discoveries. -- PS: Really sorry to everyone about all the e-mails I've generated. I'm not quite used to Thunderbird, and it puts "reply to sender only" where I'd expect "reply to newsgroup" to be. From Scott.Daniels at Acm.Org Wed Jun 1 11:11:36 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 01 Jun 2005 08:11:36 -0700 Subject: Unhappy with numarray docs In-Reply-To: References: Message-ID: <429dc954$1@nntp0.pdx.net> Matt Feinstein wrote: > I spent all day yesterday trying to figure out how to do file IO in > the numarray module-- I -did- (I think) figure it all out, eventually, > but it's left me in a rather sour mood. > > .... Grr. Propose some fixes to the documents that will make this easier for the next one in line. You don't even need to get it exactly right; the person after you can fix the mistakes you make. This is the process we use for this. See this as an opportunity to contribute, not simply a frustration about how much you overpaid for the product. --Scott David Daniels Scott.Daniels at Acm.Org From tdaitx at gmail.com Sun Jun 5 13:14:23 2005 From: tdaitx at gmail.com (=?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=) Date: Sun, 5 Jun 2005 14:14:23 -0300 Subject: maybe a bug in python In-Reply-To: References: Message-ID: Just as everyone said, use ('a',) instead of ('a'). As Steve said there are lots of documentation about it. Check the Library Reference at http://www.python.org/doc/current/lib/typesseq.html#l2h-155 or to make things more clear you could read the tuples section in the tutorial at http://docs.python.org/tut/node7.html#SECTION007300000000000000000 my 2 cents Regards, Tiago S Daitx On 6/5/05, flyaflya wrote: > > > >>> a = {1: ("a")} > >>> a[1] > 'a' > why not ('a')? when > >>> a = {1: ((("a")))} > >>> a[1] > 'a' > the result is 'a' too,not ((("a"))).but when use["a"] or ("a","b"),the > tuple is longer than 1, it's no problem. > > > > > > > > > > -- > [http://www.flyaflya.com/] > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jrastrick at student.usyd.edu.au Wed Jun 8 17:09:33 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 8 Jun 2005 14:09:33 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: <1118264973.349272.173370@z14g2000cwz.googlegroups.com> I'm a Maths and Philosophy undergraduate first and foremost, with Computer Science as a tacked on third; I've studied a fair bit of logic both informally and formally, and am familiar with things such as the non-nessecity of the law of the excluded middle in an arbitrary propositional calculus farmework. I can now also see the usefulness of overriding != and == to do things other than simple equality comparison. Kay Schueler's Expr class seems like a particularily elegant and beautful example! (and seems to me a much better justification for rich comparisons than the rather mundane typying-reduction case of Numeric arrays) So I'm not arguing Python should demand != and not(a == b) return the same thing all the time (although I did question this in my original post). My argument is simply one of pragmatism - cases where this is not the case are the highly unusual ones, and so they should be the ones forced to write seperate __eq__ and __ne__ methods, In *every* example that's been rased so far - Floats, Numeric.array, Expr, (hypothetically) some unusual Symbolic Logic program without the law of excluded middle - these methods are both by nessecity independently defined, and my suggestion would not change the status quo at all. Mahesh raised the argument some posts back that Python should not 'just guess' what you want. But the problem is, it *already does* - it guesses you want object identity comparison if you haven't written __ne__. But if __ne__ is not provided, than the negation of a==b is *surely* a better guess for a != b than the negation of a is b As always, explicit is better than implicit. But if we're going to be implicit, lets be implicit in the way that makes the most sense. I can't stand Perl's autoconversion from strings to integers. But how much worse would it be if strings were auto-converted to, for example, the sum of the ordinal value of their ascii characters? OK, thats about as compelling as I can make the argument. If Perl bashing won't sway Python fans over, I don't know what will :) P.S. Excuse the excessive presence typos throughout all my posts, its been a long night. From mab at iee.lu Wed Jun 8 01:35:44 2005 From: mab at iee.lu (Marco Bartel) Date: Wed, 08 Jun 2005 07:35:44 +0200 Subject: Garbage collection with QT Message-ID: <42a683b0$1@news.vo.lu> Hello, I got a question regarding garbage collection in python when using PyQT. How can i safely get rid of an Object instance and delete it permanently. For example when having a QTable with a bunch of records inside and closing the window hosting it, the memory space will not being freed up and when opening it again, the memory usage will grow. This ends up, when opening and closing the window serval times, in having all swapspace occupied and OS crashing. Is there a way, to find out all references to the QMainWindow or its hosted QTable, for having a mechanism to destroy them? THX Marco From rkern at ucsd.edu Fri Jun 24 00:09:07 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 23 Jun 2005 21:09:07 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <1f7befae05062309012e86599d@mail.gmail.com> References: <11bh7ffsps4ea3@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> <1f7befae05062309012e86599d@mail.gmail.com> Message-ID: Tim Peters wrote: > OK, I looked, and it made no difference to me. Really. If I had an > infinitely tall monitor, maybe I could see a difference, but I don't > -- the sign of 0 on the nose makes no difference to the behavior of > 1/x for any x other than 0. On my finite monitor, I see it looks like > the line x=0 is an asymptote, and the graph approaches minus infinity > on that line from the left and positive infinity from the right; the > value of 1/0 doesn't matter to that. Well, the value of 1/0 is undefined. Occasionally, it's useful to report +inf as the value of 1.0/+0.0 because practically we're more concerned with limiting behavior from an assumed limiting process than being correct. By the same token, we might also be concerned with the limiting behavior coming from the other direction (a different limiting process), so we might want 1.0/-0.0 to give -inf (although it's still actually undefined, no different from the first expression, and inf is really the same thing as -inf, too). Although I haven't read the paper you cited, it seems to me that the branch cut issue is the same thing. If you're on the cut itself, the value, practically, depends on which end of the branch you're deciding to approach the point from. It's arbitrary; there's no correct answer; but signed zeros give a way to express some of the desired, useful but wrong answers. And floating point is about nothing if not being usefully wrong. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sjmachin at lexicon.net Mon Jun 20 09:14:27 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Jun 2005 23:14:27 +1000 Subject: catch argc-argv In-Reply-To: References: <42B68463.90501@lexicon.net> Message-ID: <42B6C133.6040203@lexicon.net> Duncan Booth wrote: > John Machin wrote: > > >>>So, my question is: does the Python API containe fonctions like >>>'get_argc()' and 'get_argv()' ? >>> >> >>If you can't see them in the documentation, they aren't there. If they >>aren't there, that's probably for a good reason -- no demand, no use >>case. >> >> > > > Leaving aside whether or not there is a use-case for this, the reason they > aren't there is that they aren't needed. "no use-case" == "no need" in my book > As the OP was already told, to > access argv, you simply import the 'sys' module and access sys.argv. Simple in Python, not in C. > > There are apis both to import modules and to get an attribute of an > existing Python object. I know that; my point was why should you do something tedious like that when you shouldn't be interested in accessing sys.argv from a C extension anyway. > So all you need is something like (untested): > > PyObject *sys = PyImport_ImportModule("sys"); > PyObject *argv = PyObject_GetAttrString(sys, "argv"); > int argc = PyObject_Length(argv); > if (argc != -1) { > ... use argc, argv ... > } > Py_DECREF(argv); > Py_DECREF(sys); From snail at objmedia.demon.co.uk Sat Jun 25 05:57:35 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Sat, 25 Jun 2005 10:57:35 +0100 Subject: Tracing down segfault References: Message-ID: <4WvSWlCPqSvCFwt7@objmedia.demon.co.uk> In message , Tony Meyer writes >I have (unfortunately) a Python program that I can consistently (in a >reproducible way) segfault. However, I've got somewhat used to Python's >very nice habit of protecting me from segfaults and raising exceptions >instead, and am having trouble tracking down the problem. Python Bug Validator, a flow tracer, is in beta. Should show you the program execution history, line by line, with variables, params and return codes and exceptions right up until the point the application dies. http://www.softwareverify.com Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From rhall at thiess.com.au Thu Jun 2 09:02:05 2005 From: rhall at thiess.com.au (Bloke) Date: 2 Jun 2005 06:02:05 -0700 Subject: dictionaries and threads In-Reply-To: References: <20050601231009.396072.becbe514@goombah.com> <1117702209.058492.187520@f14g2000cwb.googlegroups.com> Message-ID: <1117717325.091490.284660@g43g2000cwa.googlegroups.com> thanks. Looks good. From listserver at tdw.net Sat Jun 11 07:46:30 2005 From: listserver at tdw.net (Tim Williams) Date: Sat, 11 Jun 2005 12:46:30 +0100 Subject: help with sending mail in Program References: Message-ID: <00be01c56e7c$5c9759b0$ccbefea9@twilliams> ----- Original Message ----- From: "Ivan Shevanski" To: Sent: Saturday, June 11, 2005 3:32 AM Subject: Re: help with sending mail in Program > > >>from smtplib import SMTP > > > >>def sendToMe(subject, body): > >> me = '"Kent Johnson" ' > >> send(me, me, subject, body) > >> > >> > >>def send(frm, to, subject, body): > >> s = SMTP() > >># s.set_debuglevel(1) > >> s.connect('mail.mycompany.com') > >> s.ehlo('10.0.3.160') # IP address of my computer, I don't remember >why I needed this > >> > >> msg = '''From: %s > >>Subject: %s > >>To: %s > >> > >>%s > >>''' % (frm, subject, to, body) > >> > >> s.sendmail(frm, to, msg) > > > > > > s.sendmail(frm, [to], msg) > > > > > >> s.quit() > >> > >> > >>if __name__ == '__main__': > >> sendToMe('Testing', 'This is a test') > >From: "Tim Williams" > >To: "Ivan Shevanski" > >Subject: Re: help with sending mail in Program > >Date: Thu, 9 Jun 2005 22:48:38 +0100 > > > >Hi Ivan, did you have any luck with the email source I sent you ? > > > >The hotmail server would have been overly sensitive to "fake" emails, if > >you were using a different server your original code would probably work. > > > >HTH > > > >Tim > >----- > Nope no luck. . .What server do you suggest I use? Yahoo doesnt have one, > and I don't feel like downloading gmail. . .What do you think? > > -Ivan Ivan, the MIMEText module should create a properly constructed email from your own text, try something like this (untested) ---------------------------- from email.MIMEText import MIMEText from smtplib import SMTP def sendToMe(subject, body): me = '"Kent Johnson" ' send(me, me, subject, body) def send(frm, to, subject, body): s = SMTP() s.set_debuglevel(1) s.connect('mail.mycompany.com') s.ehlo('10.0.3.160') msg = MIMEText(body) msg['To'] = to # '"Text Name"
' msg['Subject'] = subject msg['From'] = frm # '"Kent Johnson" ' to2 = to.split()[-1] # =
frm2 = frm.split()[-1] # can use rsplit() in 2.4 s.sendmail(frm2, [to2], msg.as_string()) s.quit() if __name__ == '__main__': sendToMe('Testing', 'This is a test') From rune.strand at gmail.com Tue Jun 28 01:25:16 2005 From: rune.strand at gmail.com (Rune Strand) Date: 27 Jun 2005 22:25:16 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <1119936316.527306.162900@g47g2000cwa.googlegroups.com> BORT wrote: > Please forgive me if this is TOO newbie-ish. > > I am toying with the idea of teaching my ten year old a little about > programming. I started my search with something like "best FREE > programming language for kids." After MUCH clicking and high-level > scanning, I am looking at Python and Forth. Both have advocates that > say each is a great approach to learning computers. You may find RUR interesting http://rur-ple.sourceforge.net/ ("Learning Python: Child's Play with RUR-PLE!") From prabapython at yahoo.co.in Fri Jun 17 04:46:52 2005 From: prabapython at yahoo.co.in (praba kar) Date: Fri, 17 Jun 2005 09:46:52 +0100 (BST) Subject: How to right align IPaddress? In-Reply-To: <1118740170.9602.236315256@webmail.messagingengine.com> Message-ID: <20050617084652.41351.qmail@web8409.mail.in.yahoo.com> Dear all, Is it possible to right align the Ipaddress? Normally we can right align the list of numbers by %3u or %7u. How we can right align the Ipaddress? I expects below format output eg 203.199.200.0 203.33.20.0 with regards, Prabahar _______________________________________________________ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From rkern at ucsd.edu Mon Jun 6 13:28:00 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 06 Jun 2005 10:28:00 -0700 Subject: Reading a CSV file into a list of dictionaries In-Reply-To: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> References: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> Message-ID: RFQ wrote: > Hi, I'm struggling here to do the following with any success: > > I have a comma delimited file where each line in the file is something > like: > > PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... > > So each line is intended to be: key1,value1,key2,value2,key3,value3... > and each line is to be variable in length (although it will have to be > an even number of records so that each key has a value). > > I want to read in this csv file and parse it into a list of > dictionaries. So each record in the list is a dictionary: > > {"PNumber":"3056","Contractor":"XYZ Contracting", ... } > > I have no problem reading in the CSV file to a list and splitting each > line in the file into its comma separated values. But I can't figure > out how to parse each resulting list into a dictionary. First, don't process the CSV stuff yourself. Use the csv module. In [9]:import csv In [10]:f = open('foo.csv') In [11]:cr = csv.reader(f) In [12]:for row in cr: ....: print dict(zip(row[::2], row[1::2])) ....: {'Architect': 'ABC Architects', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} {'Architect': 'ABC Architects', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} [etc.] -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From grante at visi.com Tue Jun 21 19:18:08 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 21 Jun 2005 23:18:08 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> Message-ID: <11bh81gkhq34tb2@corp.supernews.com> On 2005-06-21, Grant Edwards wrote: > I finally figured out why one of my apps sometimes fails under > Win32 when it always works fine under Linux [...] Oh, I forgot, here's pickletest.py: #!/usr/bin/python import pickle f1 = (1e300*1e300) f2 = f1/f1 o = (f1,f2) s = pickle.dumps(o) d = pickle.loads(s) print o,d > $ python pickletest.py > (inf, nan) (inf, nan) > Under Win32: > > $ python pickletest.py > Traceback (most recent call last): > File "pickletest.py", line 8, in ? > d = pickle.loads(s) > File "C:\PYTHON23\lib\pickle.py", line 1394, in loads > return Unpickler(file).load() > File "C:\PYTHON23\lib\pickle.py", line 872, in load > dispatch[key](self) > File "C:\PYTHON23\lib\pickle.py", line 968, in load_float > self.append(float(self.readline()[:-1])) > ValueError: invalid literal for float(): 1.#INF -- Grant Edwards grante Yow! Here I am in 53 at B.C. and all I want is a visi.com dill pickle!! From uche.ogbuji at gmail.com Sat Jun 4 23:59:41 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 4 Jun 2005 20:59:41 -0700 Subject: Elementtree and CDATA handling In-Reply-To: <1117651003.858779.274950@g43g2000cwa.googlegroups.com> References: <1117631202.723453.20060@z14g2000cwz.googlegroups.com> <1117651003.858779.274950@g43g2000cwa.googlegroups.com> Message-ID: <1117943981.604181.323810@g44g2000cwa.googlegroups.com> "If, instead, you want to keep track of where the CDATA sections are, and output them again without change, you'll need to use an XML-handling interface that supports this feature. Typically, DOM implementations do - the default Python minidom does, as does pxdom. DOM is a more comprehensive but less friendly/Python-like interface for XML processing. " Amara in CVS makes it easy to perform the output part of this: text=""" Document """ from amara.binderytools import bind_string doc = bind_string(text) print doc.xml(cdataSectionElements=[u'script']) Output: Document Unfortunately, in cooking up this example I did find a bug in the Amara 1.0b1 release that requires a workaround. I should be releasing 1.0b2 this weekend, which fixes this bug (among other fixes and improvements). "If you're generating output for legacy browsers, you might want to just use a 'real' HTML serialiser. " Amara does provide for this, e.g.: from amara.binderytools import bind_string doc = bind_string(text) print doc.xml(method=u"html") Which automatically and transparently brings to bear the full power of the XSLT HTML output method. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Use CSS to display XML, part 2 - http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html XML Output with 4Suite & Amara - http://www.xml.com/pub/a/2005/04/20/py-xml.htmlUse XSLT to prepare XML for import into OpenOffice Calc - http://www.ibm.com/developerworks/xml/library/x-oocalc/ Schema standardization for top-down semantic transparency - http://www-128.ibm.com/developerworks/xml/library/x-think31.html From __peter__ at web.de Sat Jun 25 17:19:48 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 25 Jun 2005 23:19:48 +0200 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1119730516.936848.195640@f14g2000cwb.googlegroups.com> Message-ID: Mandus wrote: > 25 Jun 2005 13:15:16 -0700 skrev Devan L: >> But by using the builtin reduce, you need to specify a function, which >> probably slows it down more than any speed-up from the loop in C. > > Sounds reasonable, but not always the case, especially when dealing with > numpy arrays. At least that what some of my test shows. But then I > should probably write c-functions that deals with the numeric arrays > anyway. > > Besides, functions like 'operator.add' is also in c, maybe that helps. Yes, the C-coded operator.mul() was the counterexample that John Lenton came up with when I challenged the speed advantage of reduce() over the equivalent for-loop. > But I admit it's not a perfect example. Python is more about readability than raw speed, and I prefer a for-loop over reduce() in that respect, too. If you need the best possible efficiency you would probably have to code the loop in C. Incidentally, for add() this has already been done with the sum() builtin. Peter From rrr at ronadam.com Mon Jun 27 21:10:41 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 28 Jun 2005 01:10:41 GMT Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: Message-ID: Dave Benjamin wrote: > Guido gave a good, long interview, available at IT Conversations, as was > recently announced by Dr. Dobb's Python-URL! The audio clips are available > here: > > http://www.itconversations.com/shows/detail545.html > http://www.itconversations.com/shows/detail559.html Thanks for the links Dave. :-) He talked a fair amount on adding type checking to python. From reading his blog on that subject, it seems Guido is leaning towards having the types as part of function and method definitions via the 'as' and/or '->' operator in function and class argument definitions. My first thoughts on this was to do it by associating the types to the names. Limiting reassignment of a names to specific types would be a form of persistent name constraint that would serve as a dynamic type system. Has any form of "name constraints" been discussed or considered previously? Regards, Ron From alex at quad.com.ar Fri Jun 10 16:23:22 2005 From: alex at quad.com.ar (Alex Verstraeten) Date: Fri, 10 Jun 2005 17:23:22 -0300 Subject: IMAP Proxy In-Reply-To: <42A99B1C.7020507@nuxeo.com> References: <42A99B1C.7020507@nuxeo.com> Message-ID: <42A9F6BA.6060206@quad.com.ar> Tarek Ziad? wrote: >Hi, > >I want to write a small TCP Server in Python to make an IMAP Proxy for >post-processing client requests. > >It is not long either complicated but needs to be very robust so... >maybe someone here has already done such a thing I can use or know where >i can get it ? > >Cheers, > >Tarek > > I wrote one with twisted.. it's quite easy and minimal.. you can start hooking stuff to it, I only use "dataReceived" as I only need to watch what cmds are imap client sending. from twisted.protocols.portforward import ProxyFactory from twisted.protocols.portforward import ProxyClientFactory from twisted.protocols.portforward import ProxyClient from twisted.protocols.portforward import ProxyServer from twisted.internet import reactor class PS(ProxyServer): def dataReceived(self, data): print "PS->dataReceived(%s)" %repr(data) ProxyServer.dataReceived(self, data) pfactory = ProxyFactory('192.168.1.1',143) pfactory.protocol = PS reactor.listenTCP(143, pfactory) reactor.run() this will bind to port 143 and proxy all requests to the real imap server at 192.168.1.1, while printing the commands being sent to stdout. Here, my proxy runs on different box than imap server... if you need to put both of them on same box you'll need to change the port number of , either imap server, or imap proxy. well.. hope it helps Alex From vinay_sajip at yahoo.co.uk Sun Jun 5 16:18:54 2005 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sun, 5 Jun 2005 20:18:54 +0000 (UTC) Subject: couple of new python articles on onlamp References: <42A08381.9070404@bellsouth.net> Message-ID: Jeremy Jones bellsouth.net> writes: > Python Standard Logging > http://www.onlamp.com/pub/a/python/2005/06/02/logging.html > To echo Thomas Heller's comment - nice article on logging. I'll update the docs so that the stuff about the 4-byte length is a little clearer. Vinay Sajip From jepler at unpythonic.net Sun Jun 5 22:36:04 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 5 Jun 2005 21:36:04 -0500 Subject: PyArg_ParseTuple and dict In-Reply-To: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> References: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> Message-ID: <20050606023601.GB24794@unpythonic.net> I tried to recreate the problem based on what you described in your message. I was unable to recreate the problem. I wrote the following file "sjh.c": #include PyObject *f(PyObject *self, PyObject *args) { PyObject *ob = NULL; if(!PyArg_ParseTuple(args, "O", &ob)) return NULL; Py_INCREF(Py_None); return Py_None; } PyMethodDef methods[] = { {"f", (PyCFunction)f, METH_VARARGS, "test function"}, {NULL} }; void initsjh() { Py_InitModule3("sjh", methods, "test module"); } I compiled it for Python 2.3: $ gcc sjh.c -I/usr/include/python2.3 -L/usr/lib/python2.3/config -lpython2.3 -shared -o sjh.so and I tested it: $ python -c 'import sjh; print sjh.f(1)' None $ python -c 'import sjh; print sjh.f({})' None $ python -c 'import sjh; print sjh.f({None: None})' None Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From zanesdad at bellsouth.net Tue Jun 21 22:18:52 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 21 Jun 2005 22:18:52 -0400 Subject: tree functions daily exercise: Table In-Reply-To: <1119392216.168822.314580@f14g2000cwb.googlegroups.com> References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119392216.168822.314580@f14g2000cwb.googlegroups.com> Message-ID: <42B8CA8C.2040009@bellsouth.net> Xah Lee wrote: >Very very nice! I don't know scheme well... but oh the macros, such a >wonderful facility... > > Macros suck. They created by moron so-called computer scientists and IT puntits in order opress the programming masses. But I say we must bring freedom to all programmers. In order abolish this criminality against humanity and even programmers, I recommend creating a flurry of irrelevant messages cross-posting to noncommonalitous groups. If you need dictionary to find what that word means, you a moron! F*ck dictionaries! F*ck macros! F*ck ignoramous computer scientists! F*ck so-called netiquette! Power to programmers! Only when we have created sufficient confusion and frustration among all programming entities, then they will beg us to shut up. Only then they be willing remove macros from all languages if we willing shut up. Then we shut up and see macros removed. But only for a little while. Then we campaign to get floating point roman numerals implemented. >Functional lang never let me down. > > Functional languages evil. Any language support functions come from ivory tower brain lacking idiots who think they know something. All other languages should take a lesson from Python which does not support functions. If Python supports functions, I have not read that informations. >I haven't worked on a Java version yet... but i wonder what pain i'll >have to endure for a lang that lacks eval. Since i'm not Java expert... >i wonder if i can even do it in a few days. > > Xah > xah at xahlee.org >? http://xahlee.org/ > > Power to programmers! JJ From peter at engcorp.com Thu Jun 2 12:52:03 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 12:52:03 -0400 Subject: wxPython In-Reply-To: References: Message-ID: Michael wrote: > Hi, > I've got a question about wxPython, wheres the best place to ask?? The wxPython mailing list. Visit www.wxpython.org to find it and more. From dan at nospam.com Wed Jun 22 15:02:17 2005 From: dan at nospam.com (Dan) Date: Wed, 22 Jun 2005 14:02:17 -0500 Subject: create a pdf file In-Reply-To: References: <42C7E766869C42408F0360B7BF0CBD9B014B61B4@pnlmse27.pnl.gov> Message-ID: On 6/22/2005 1:58 PM, Alberto Vera wrote: > Hello: > > I found a script that convert a file to PDF format , but it was made in PHP > > Do you know any script using Python? > > Regards See http://www.reportlab.org/rl_toolkit.html From guy at NOSPAM.r-e-d.co.nz Fri Jun 24 07:20:11 2005 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Fri, 24 Jun 2005 23:20:11 +1200 Subject: howto load and unload a module Message-ID: Hello, I have a directory of python scripts that all (should) contain a number of attributes and methods of the same name. I need to import each module, test for these items and unload the module. I have 2 questions. 1.. How do unload an imported module? 2.. how do I test for the existance of a method in a module without running it? TIA, Guy From prabapython at yahoo.co.in Tue Jun 21 00:30:58 2005 From: prabapython at yahoo.co.in (praba kar) Date: Tue, 21 Jun 2005 05:30:58 +0100 (BST) Subject: regarding cache clearing header in python cgi In-Reply-To: Message-ID: <20050621043059.61710.qmail@web8404.mail.in.yahoo.com> Dear All, In Php the following headers base we can clean the cache in the url "header('Cache-Control: no-store, no-cache, must-revalidate'); " I want to know Php equivalent headers in Python-cgi If any know regarding this kindly mail me. regards, Prabahar __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From steven.bethard at gmail.com Mon Jun 6 14:52:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 06 Jun 2005 12:52:10 -0600 Subject: the python way? In-Reply-To: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> Message-ID: Grooooops wrote: > Hi All, > > I've been lurking the list for a month and this is my first post. I am > hoping this post is appropriate here, otherwise, my apologies. > > I'm somewhat new to Python, (I'm reading all the tutorials I can find, > and have read through Andre Lessa's Developers Handbook.) > I am trying to learn the Python way of thinking as well as the syntax. > > I popped this bit of code together for fun, based on a previous post > regarding randomizing a word. > This shuffles a word, then splits out the vowels and then reassembles > it with the vowels interpolated between consonants. > (To create plausible sounding gibberish) > > The code just seems kind of bulky to me. I am wondering, is this an > efficient way to do things, or am I making things harder than > necessary? > > #--------------------------begin code------------------ > """scrambles a word, but creates plausable gibberish""" > import random > def shuffled(s): > """ scrambles word""" > l = list(s) > random.shuffle(l) > return ''.join(l) > > def contains(alist,b): > """...is letter b in list a...""" > ret = [] > for all in alist: > #print all > if all==b: > return 1 > return 0 "contains(alist, b)" can be more easily written as "b in alist" > > def newZip(a1,a2): > """ reassemble """ > l1=len(a1) > l2=len(a2) > > longest = [a1,a2][l1 shortest = [a1,a2][longest == a1] longest, shortest = sorted([a1, a2], key=len) > diff = max(l1,l2)-min(l1,l2) > #print longest > seq = len(longest) > ret = "" Don't build up strings using +. Create a list of strings, and use str.join at the end. > for j in range(seq): > if len(longest)>0: The len() > 0 is unnecessary, simply use: if longest: > ret = ret + longest.pop() > if len(shortest)>0: if shortest: > ret = ret + shortest.pop() > return ret If I understand you right, you want to do the usual thing zip does, but guaraneeing that the first element is always from the longer list, and not throwing away elements. Note that map(None, ...) probably does what you want: longest, shortest = sorted([a1, a2], key=len, reverse=True) return ''.join(item for pair in map(None, longest, shortest) for item in pair if item is not None) > def reinterpolate(word): > """ main function """ > wlist = shuffled(list(word)) > vlist = list('aeiouy') # ok, y isn't really a vowel, but... no need to make vlist a list; contains should work fine on strings. > vees = filter(lambda x: contains(vlist,x),wlist) vees = [c in vlist for c in wlist] > cons = filter(lambda x: not(contains(vlist,x)),wlist) cons = [c not in vlist for c in wlist] > a=list(vees) > b=list(cons) The above are unnecessary. vees and cons are already lists. > return newZip(a,b) > > word = "encyclopedia" > print reinterpolate(word) So I think overall, my rewrite of your code would look something like (untested): def reinterpolate(word) wlist = list(word) random.shuffle(wlist) vlist = 'aeiouy' vees = [c for c in wlist if c in vlist] cons = [c for c in wlist if c not in vlist] longest, shortest = sorted([vees, cons], key=len) return ''.join(item for pair in map(None, longest, shortest) for item in pair if item is not None) From fingermark at gmail.com Tue Jun 7 16:11:03 2005 From: fingermark at gmail.com (fingermark at gmail.com) Date: 7 Jun 2005 13:11:03 -0700 Subject: Trouble Encoding In-Reply-To: References: <1118135690.961381.207490@o13g2000cwo.googlegroups.com> Message-ID: <1118175063.877898.314940@z14g2000cwz.googlegroups.com> why is it even trying latin-1 at all? I don't see it anywhere in feedparser.py or my code. deelan wrote: > fingermark at gmail.com wrote: > > I'm using feedparser to parse the following: > > > >
Adv: Termite Inspections! Jenny Moyer welcomes > > you to her HomeFinderResource.com TM A "MUST See &hellip;
> > > > I'm receiveing the following error when i try to print the feedparser > > parsing of the above text: > > > > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in > > position 86: ordinal not in range(256) > > > > Why is this happening and where does the problem lie? > > it seems that the unicode character 0x201c isn't part > of the latin-1 charset, see: > > "LEFT DOUBLE QUOTATION MARK" > > > try to encode the feedparser output to UTF-8 instead, or > use the "replace" option for the encode() method. > > >>> c = u'\u201c' > >>> c > u'\u201c' > >>> c.encode('utf-8') > '\xe2\x80\x9c' > >>> print c.encode('utf-8') > > ok, let's try replace > > >>> c.encode('latin-1', 'replace') > '?' > > using "replace" will not throw an error, but it will replace > the offending characther with a question mark. > > HTH. > > -- > deelan From martin.witte at gmail.com Sat Jun 18 10:30:46 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 18 Jun 2005 07:30:46 -0700 Subject: MixIn method to call the method it overrides: how? In-Reply-To: <1119097682.444797.159470@g44g2000cwa.googlegroups.com> References: <1119097682.444797.159470@g44g2000cwa.googlegroups.com> Message-ID: <1119105046.650821.168590@g47g2000cwa.googlegroups.com> Something like this will do what you want to achieve. I think the above does as well what you want, but to me my solution is much more clear class Base(object): def foo(self): print 'Base foo' class Derived(Base): def foo(self): super(Derived, self).foo() print 'Derived foo' d = Derived() d.foo() From mcherm at mcherm.com Fri Jun 10 16:00:26 2005 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 10 Jun 2005 13:00:26 -0700 Subject: lstat(fileName)[ST_SIZE] Message-ID: <20050610130026.uezwvp759xgksc4s@login.werra.lunarpages.com> Siva writes: > What is the type of > os.lstat(fileName)[stat.ST_SIZE]. In python 2.0 I am getting it as int and > in 2.3 it is long. I don't know the answer to your question, but I *can* point out that Python 2.0 was released in October 2000... nearly 5 years ago. I am entirely unsurprised to learn that it doesn't handle file sizes larger than MAXINT on your box... hardly any OS's allowed such a thing back then. I recomend using a newer version... 2.4.1 is quite nice. -- Michael Chermside From spam.csubich+block at block.subich.spam.com Sun Jun 12 12:29:27 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 12 Jun 2005 12:29:27 -0400 Subject: TKinter -- '' event executing more than once? In-Reply-To: References: <6EKqe.115932$J25.63349@bignews6.bellsouth.net> <0SPqe.90792$8S5.63138@bignews3.bellsouth.net> Message-ID: Jeff Epler wrote: > For me, an 'is' test works to find out what widget the event is taking > place on. ... yes, I am apparently as stupid as I look. In my test code, I was trying "if event is widget," and I just now saw that. Thanks! :) From bogus@does.not.exist.com Tue Jun 28 15:15:02 2005 From: bogus@does.not.exist.com () Date: Tue, 28 Jun 2005 19:15:02 -0000 Subject: No subject Message-ID: #! rnews 2994 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 57 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1119898281.201400.85040 at o13g2000cwo.googlegroups.com> <1119956464.362328.290370 at o13g2000cwo.googlegroups.com> Mime-Version: 1.0 Date: Tue, 28 Jun 2005 18:58:08 GMT Xref: news.xs4all.nl comp.lang.python:383798 phil writes: > > > > You are quite correct to point out how much better it is to know what is > > going on behind the scenes. But heck, once you know how to extract square > > roots - you need to let the computer do it! > > GUI interfaces should be the same deal! > > Thomas Bartkus > > > I think I pretty much agree. I essentially code my own gui builder > > but in text files. > > I just think it is really important to emphasise the operative > "but once you know how" in your comments. > > Then some would counter with "oh, so we should code everthing > in assembler?" Ouch. No, I will admit there is judgement > required. Everything should be done the easiest way, with the > qualification that you need to understand how using someone > else's shortcut leaves you vulnerable. I agree with your comments on Python and java and IDEs. I'd like to expand on the "code in assy" complaint. Compiled-to-assy-to-machine-to-execution is understood and algorithmic. Any one person may no know it al,l but every step of the way has been thought out and optimized by someone who knew what he/she was doing. There are very few places where anyone has to dive down into assy, much less microcode or VLSI layouts. Therefore, we can trust the abstract model provided by the programming language, and can stay in that model. This is not the case for GUIs. We can't safely stay in the abstract GUI IDE. In fact, most require you to dive into the generated code to finish the task. Bouncing up and down the abstraction ladder is hard and made harder by being forced to live in the IDE's idea of generated code. Given that, GUI IDEs are still helpful if your base langauge is a pain to write and debug (e.g., C++, Java). But if your language is actually easier to use than the GUI IDEs, then the equation shifts. With Python, the clarity of thought and the opportunities for higher-level programming (dynamic code genration et al) make GUI IDEs just a waste of time or worse. I also have moved to text-based inputs to my own GUI builders. Maybe there is a sourceforge project waiting to be borne here :-) [snip] -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From prinster at mail.com Thu Jun 2 00:18:49 2005 From: prinster at mail.com (Stephen Prinster) Date: Thu, 02 Jun 2005 04:18:49 GMT Subject: Beginner question: Logs? In-Reply-To: <1117685058.142351.123660@g47g2000cwa.googlegroups.com> References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: Svens wrote: > Hey thanks... > > Still getting an error message though. Here's what i'm doing: > ------ > import math > log10(15625) > ------ > -It says that log10 is not defined, but it is since the module is > imported, right? > try this: import math math.log10(15625) From tomlis at notmyisp.pl Tue Jun 14 08:18:00 2005 From: tomlis at notmyisp.pl (Tomasz Lisowski) Date: Tue, 14 Jun 2005 14:18:00 +0200 Subject: Where is Word? In-Reply-To: References: <42aeae07@news.home.net.pl> Message-ID: <42aecaf8$1@news.home.net.pl> > Thanks, but could you pretty please post some code that does this? I'm new > to Python, let alone COM.. > > TIA, > g import win32com.client wordCOMID = "Word.Application" word = win32com.client.Dispatch(wordCOMID) Then you can use the methods of the word object, provided by the COM object definition. Unfortunately I don't know them - you may do a research by making a reference to the Microsoft Word type library in Visual Basic, declaring the variable of type Word.Application, and then watching the code assistant showing the available methods and properties. You may also use the object browser. Tomasz Lisowski > > "Tomasz Lisowski" schreef in bericht > news:42aeae07 at news.home.net.pl... > >>You may try to launch Word as a COM object and control it directly from >>Python using the COM object methods. This does not require you to know the >>application's path, only the COM object identifier. >> >>TLis > > > From utabintarbo at gmail.com Fri Jun 24 09:13:00 2005 From: utabintarbo at gmail.com (utabintarbo at gmail.com) Date: 24 Jun 2005 06:13:00 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <1119618780.475725.22580@o13g2000cwo.googlegroups.com> >with colour do begin >red := 0; blue := 255; green := 0; >end; > >instead of: > >colour.red := 0; colour.blue := 255; colour.green := 0; Why not: from color import * red := 0 blue := 255 green := 0 ... From spam.csubich+block at block.subich.spam.com Tue Jun 28 11:25:25 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 28 Jun 2005 11:25:25 -0400 Subject: DParser binaries on Win32 with Python 2.4? In-Reply-To: <1119955026.276799.117500@f14g2000cwb.googlegroups.com> References: <1119955026.276799.117500@f14g2000cwb.googlegroups.com> Message-ID: woodsplitter at rocketmail.com wrote: > 1) http://mingw.org > 2) python setup.py build --compiler=mingw32 > 3) python setup.py install Thank you very much, it looks like this worked perfectly; it even picked up on the cygwin-mingw32 libraries and compiled with the cygwin compiler and -mno-cygwin. From saint.infidel at gmail.com Wed Jun 1 12:41:53 2005 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2005 09:41:53 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> Message-ID: <1117644113.523658.173830@g43g2000cwa.googlegroups.com> Why in the name of all that is holy and just would you need to do such a thing? From lbates at syscononline.com Mon Jun 20 09:52:43 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 20 Jun 2005 08:52:43 -0500 Subject: dll files In-Reply-To: <1119265966.661838.186320@g44g2000cwa.googlegroups.com> References: <1119265966.661838.186320@g44g2000cwa.googlegroups.com> Message-ID: <42B6CA2B.3030909@syscononline.com> You are most likely better off creating COM objects than trying to create old .dll files. Good treatment of COM object creation is in the book titled Python Programming on Win32. Most other languages have no problem interfacing with COM objects. -Larry Sabin wrote: > How can i create dll files in Python? > Is it possible? > > If yes, > how to enclose image and font files in a dll ? > > Plis reply. > SABIN. > B'lore. > From ptmcg at austin.rr.com Tue Jun 7 16:29:47 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 7 Jun 2005 13:29:47 -0700 Subject: split up a list by condition? References: <3gjpk0FcrnknU1@individual.net> Message-ID: <1118176187.316126.283610@g14g2000cwa.googlegroups.com> Re-run this with the input string "The quick brown fox is named 'Aloysius'." and we discover that 'A', 'y', "'" and '.' are also consonants. (Actually, this is bug-compatible with the OP's original example.) -- Paul From edhillmann at yahoo.com Mon Jun 6 00:31:24 2005 From: edhillmann at yahoo.com (Ed) Date: 5 Jun 2005 21:31:24 -0700 Subject: Building Python with gdbm support Message-ID: <1118032284.704599.89030@g14g2000cwa.googlegroups.com> I am trying to use a Perl script which requires a Database module other than "dbm" to be the default Mod. So, what the script is checking is import anydbm if (anydbm._defaultmod.__name__ == 'dumbdbm' or anydbm._defaultmod.__name__ == 'dbm'): First of, I'm doing this on a Sparc/Solaris 8 box. So, I'm trying to get gdbm to be the default mod. I've downloaded and built gdbm-1.8.3. It has not been build to /usr (I don't have root access). I've built this fine. When I build Python 2.4.1, it at first doesn't pick up on the gdbm module ("dbm" is still the default module, and Modules directory in the Python source doesn'thave a .o file for the gdbmmodule file). I've nosed around, and found the a line commented out Modules/Setup file, regarding building the gdbm module. I uncommented it (being sure that the approrpiate directories for the .h and lib files are provided), and it looked like it built the module. But when I attempt to start python, I get an error: ld.so.1: python: fatal: libgdbm.so.3: open failed: No such file or directory Killed Look, the bottom line is I don't know what the correct steps are to get the gdbm module built in as part of the Python installation (as well as setting it as the default database module). I've tried to piece together bits and pieces of various newsgroup messages, as I haven't found a decent spot for any doco. Can anyone point me in the right direction, in regards to how to get my Python installation set up the way I want? Is it correct to edit the Modules/Setup file? I would have thought that the configure approach would support these types of isses, rather than manually editing a file? Should I be using the setup.py script? I have no idea what that does, or where I would call it, but the name of it sounds like it should be included? Thanks for any help, Ed From benji at benjiyork.com Thu Jun 23 11:54:46 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 23 Jun 2005 11:54:46 -0400 Subject: Loop until condition is true In-Reply-To: <86u0jpytg7.fsf@guru.mired.org> References: <86u0jpytg7.fsf@guru.mired.org> Message-ID: <42BADB46.4010708@benjiyork.com> Mike Meyer wrote: > Making None a constant broke existing code (and I just saw old code > that assigned to None). Are True and False that much more common as > variable names than None? I would think so. I know that my pre-booleans-in-Python code routinely did something like "from booleans import True, False". Of course the fix is easy, but it still must be applied before the code will run. -- Benji York From agriff at tin.it Wed Jun 15 03:25:18 2005 From: agriff at tin.it (Andrea Griffini) Date: Wed, 15 Jun 2005 07:25:18 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> <863brlzmy9.fsf@guru.mired.org> <86ekb4y5ut.fsf@guru.mired.org> Message-ID: On Tue, 14 Jun 2005 16:40:42 -0500, Mike Meyer wrote: >Um, you didn't do the translation right. Whoops. So you know assembler, no other possibility as it's such a complex language that unless someone already knows it (and in the specific architecture) what i wrote is pure line noise. You studied it after python, I suppose. >> or, even more concrete and like what I learned first >> >> lda $300 >> clc >> adc $301 >> sta $302 >> >> is simpler to understand. > >No, it isn't - because you have to worry about more details. In assembler details are simply more explicit. Unfortunately with computers you just cannot avoid details, otherwise your programs will suck bad. When I wrote in an high level language or even a very high level one the details are understood even if I'm not writing down them. After a while a programmer will even be able to put them at a subconscius level and e.g. by just looking at O(N^2) code that could be easily rewritten as O(N) or O(1) a little bell will ring in you brain telling you "this is ugly". But you cannot know if something is O(1) or O(N) or O(N^2) unless you know some detail. If you don't like details then programming is just not the correct field. In math when I write down the derivative of a complex function it doesn't mean I don't know what is the definition of derivative in terms of limits, or what are the conditions that must be met to be able to write down it. Yet I'm not writing them every time (some times I'll write them when they're not obvious, but when they're obvious it doesn't mean I'm not considering them or, worse, I don't know or understand them). If you don't really understand what a derivative is and when it makes sense and when it doesn't, your equations risk to be good just for after dinner pub jokes. >In particular, when programming in an HLL the compiler will take care of >allocating storage for the variables. In assembler, the programmer has >to deal with it. These extra details make the code more complicated. Just more explicit. So explicit that it can become boring. After a while certain operations are so clearly understood that you are able to write a program to do them to save us some time (and to preventing us to get bored). That's what HLL are for... to save you from doing, not to save you from understanding. What the HLL is doing for you is something that you don't do in the details, but that you better not taking without any critic or even comphrension, because, and this is anoter very important point, *YOU* will be responsible of the final result, and the final result will depend a lot (almost totally, actually) on what you call details. Just to make another example programming without the faintes idea of what's happening is not really different from using those "wizards" to generate a plethora of code you do not understand. When the wizard will also take the *responsability* for that code we may discuss it again, but until then if you don't understand what the wizard does and you just accept its code then you're not going to go very far. Just resaying it if you don't understand why it works there is just no possibility at all you'll understand why it doesn't work. Think that "a = b + c" in computes the sum of two real numbers and your program will fail (expecting, how fool, that adding ten times 0.1 you get 1.0) and you'll spend some time wondering why the plane crashed... your code was "correct" after all. >For instance, whitesmith had a z80 assembler that let you write: > > a = b + c > >and it would generate the proper instructions via direct >translation. To use that I've to understand what registers will be affected and how ugly (i.e. inefficient) the code could get. Programmin in assembler using such an high level feature without knowing those little details woul be just suicidal. >Also, you can only claim that being closer to the chip is "simpler" >because you haven't dealt with a sufficiently complicated chip yet. True that one should start with something reasonable. I started with 6502 and just love its semplicity. Now at work we've boards based on DSP TMSC320 and, believe me, that assembler gives new meanings to the word ugly. >> But saying for example that >> >> del v[0] >> >> just "removes the first element from v" you will end up >> with programs that do that in a stupid way, actually you >> can easily get unusable programs, and programmers that >> go around saying "python is slow" for that reason. > >That's an implementation detail. It's true in Python, but isn't >necessarily true in other languages. Yeah. And you must know which is which. Otherwise you'll write programs that just do not give the expected result (because the user killed them earlier). >Yes, good programmers need to know that information - or, >as I said before, they need to know that they need to know >that information, and where to get it. I think that a *decent* programmer must understand if the code being written is roughly O(n) or O(n^2). Without at least that the possibility of writing useful code, excluding may be toy projects, is a flat zero. Looking that information later may be just "too" late, because the wrong data structure has already been used and nothing can be done (except rewriting everything). >That may well be true of the standard C++ library - I don't write >it. But it certainly doesn't appear to be true of, for instance, >Python internals. I've never seen someone explain why, for instance, >string addition is O(n^2) beyond the very abstract "it creates a new >string with each addition". No concrete details at all. The problem is that unless you really internalized what that means you'll forget about it. Don't ask me why, but it happens. Our mind works that way. You just cannot live with a jillion of unrelated details you cannot place in a scheme. It doesn't work. One would do thousand times the effort that would be done using instead a model able to justify those details. >> The problem with designing top down is that when >> building (for example applications) there is no top. > >This is simply false. The top of an application is the >application-level object Except that the marketing will continuosly shift what you application is supposed to do. And this is good, and essential. This is "building". Sometimes marketing will change specifications *before* you complete the very first prototype. For complex enough projects this is more the rule than the exception. In the nice "the pragmatic programmer" book (IIRC) is told that there's no known complex project in which specification was changed less than four times before the first release... and the only time they were changed just three times it was when the guy running with the fourth variations was hit by a lightning on the street. >> Unfortunately sometimes there >> is the OPPOSITE problem... we infer general rules >> that do not apply from just too few observations. > >Your opposite problem is avoided by not teaching the details until >they are needed, and making sure you teach that those are >implementation details, so they student knows not to draw such >conclusions from them. What you will obtain is that people that will build wrong models. Omitting details, if they can really affect the result, is not a good idea. This is completely different from omitting details that no one without a 3km particle accellerator could detect to kids in 4th grade school. >>>The critical things a good programmer knows about those >>>concrete details is which ones are platform specific and which aren't, >>>and how to go about learning those details when they go to a new >>>platform. >> >> I never observed this problem. You really did ? > >As mentioned, you see it all the time in c.l.python. People come from >other languages, and try to write Python as if the rules for that >other language apply. That's exactly because they don't know the details of any of the languages you used. Someone knowing the details would be curious to know *how* "del v[0]" is implemented in python. Actually it could be changed easily in an O(1) operation with just a little slowdown in element access (still O(1) but with a bigger constant). This is a compromise that has not been accepted and this very fact is important to know if you plan to use python seriously. >It can be fixed from the start by teaching the student the difference >between abstract programming concepts and implementation details. Sorry, but I really don't agree that big O is a "detail" that could be ignored. Only bubble-and-arrow powerpoint gurus could think that; I'm not in that crew. Ignore those little details and your program will be just as good as ones that don't even compile. >It tackled abstract problems like "sorting". The students I'm talking >about never dealt with anything that abstract. Sorting is abstract ? >> Pairing this with that teaching >> abelian groups first to kids (why not fiber spaces then ?) >> and that TAOCP is too "abstract" tells me that apparently >> you're someone that likes to talk just for talking, or >> that your religion doesn't allow you to type in smileys. > >Now you're resorting to straw men and name-calling. That's an >indication that you no longer have any real points. I'll blame my bad english for understanding that you said that abelian groups should be taught before relative numbers (somehow I crazily thought the point of discussion was what's the correct order of learning how to program), that TAOCP is too abstract (a book where every single code listing is in assembler!) and that big-o when programming is a detail that can be safely ignored (good luck, IMO you'll need hell a lot of it). Andrea From duncan.booth at invalid.invalid Thu Jun 2 05:42:06 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Jun 2005 09:42:06 GMT Subject: how to convert string to list or tuple References: <1117383768.099922.308760@o13g2000cwo.googlegroups.com> <429e1546$0$1372$5fc3050@dreader2.news.tiscali.nl> Message-ID: Ruud de Jong wrote: > Steven Bethard schreef: >> But unless the person eval-ing your code *only* writes immaculate >> code I can see that you can probably screw them. ;) I wonder why >> __subclasses__ isn't a restricted attribute... Is it ever used for >> something that isn't evil? ;) >> >> STeVe > > Completely off topic, but I just cannot resist showing off. > Some time ago I used __subclasses__ in a way that is not evil. I > think. > > The details are described in the following thread: > http://groups.google.nl/group/comp.lang.python/browse_thread/thread/5c1 > ccb986c66cdc1/ > > A summary: I used __subclasses__ to apply the Chain-of-Responsibility > pattern to object creation. The code would appear to instantiate > an object of the root of a class hierarchy, but the actual object > that was created would be an instance of a subclass. > > So to get back to your question: yes, there are non-evil > uses for __subclasses__. Weird perhaps, but non-evil. > Non-standard, sure . Too clever for my own good, very likely. I've done almost exactly the same thing. The base class uses __subclasses__ to find the best matching subclass based on the factory parameters. In my case I was retrieving files from the web, so I had a base Handler class and created HtmlHandler, ImageHandler &c. class Handler(object): '''Class to process files''' __map = {} @classmethod def _resolveClass(klass, isdir, name): map = Handler.__map if not map: for c in klass.__subclasses__(): for ext in c.Extensions: map['.'+ext.lower()] = c if isdir: klass = FolderHandler else: ext = os.path.splitext(name)[1].lower() if ext not in map: map[ext] = DefaultHandler klass = map[ext] return klass(name) @classmethod def fromPathname(klass, name, path, uri, db): isdir = os.path.isdir(os.path.join(path, name)) obj = klass._resolveClass(isdir, name) obj._initialize(name, path, uri, db) return obj @classmethod def fromUrl(klass, uri, text, db=None): ... and so on ... and then subclasses such as: class ImageHandler(Handler): Extensions = ('jpg', 'jpeg', 'gif', 'png') type = 'Image' class DefaultHandler(Handler): Extensions = ('',) type = 'Ignored' This also contains the only code I think I've written with a class definition in a for loop: # General categories EXTENSIONS = { 'js': 'javascript', 'php': 'php', 'doc': 'Word Document', 'xls': 'Spreadsheet', 'ppt': 'Powerpoint', 'css': 'Stylesheet', 'swf': 'Flash', 'pdf': 'File', 'rtf': 'File', 'zip': 'File', } Classes = [] for ext in EXTENSIONS: class GeneralHandler(Handler): Extensions = (ext,) type = EXTENSIONS[ext] Classes.append(GeneralHandler) From bdesth.quelquechose at free.quelquepart.fr Sun Jun 12 16:16:08 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 12 Jun 2005 22:16:08 +0200 Subject: How to get/set class attributes in Python In-Reply-To: References: <42ac6b5b$0$27173$626a14ce@news.free.fr> Message-ID: <42ac9250$0$4934$636a15ce@news.free.fr> Chris Spencer a ?crit : > Bruno Desthuilliers wrote: > >> And *this* is highly unpythonic. And un-OO too, since it makes foo() >> dependant on *class* Bar, when it should most probably be enough that >> it only depends on (probably part of) the *interface* of class Bar. > > I was providing the original poster with a simple way to ensure > appropriate type. s/appropriate type/specific implementation/ Hint : the appropriate type for print >> XXX is "whatever has a 'write(anything_that_can_be_coerced_to_a_string)' method". From andreas at kostyrka.org Fri Jun 24 08:14:01 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 24 Jun 2005 14:14:01 +0200 Subject: help! In-Reply-To: <03FB1C8A0749414494FE4726AADD7D4302A8C5B4@vkomexch1.zh.corp> References: <03FB1C8A0749414494FE4726AADD7D4302A8C5B4@vkomexch1.zh.corp> Message-ID: <20050624121401.GA7890@heaven.kostyrka.org> Just out of curiosity, does the filesystem support seperate a/m/c times? Andreas On Fri, Jun 24, 2005 at 02:49:01PM +0300, Eser ?etinkaya wrote: > > > In your documentation, it is written : > " > os.path.getatime(path) > Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. > " > > what do you mean by "access" ? this function gives same outputs with the " os.path.getmtime(path) " > What can change an acess time of a path different from modification? > Is there any mistakes in the implementation or am i missing some points? > > M.Eser Cetinkaya > -- > http://mail.python.org/mailman/listinfo/python-list From chinook.nr at tds.net Tue Jun 28 07:31:43 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 07:31:43 -0400 Subject: OO refactoring trial ?? Message-ID: <0001HW.BEE6AC5F00035045F0407550@news.gmane.org> [[ This message was both posted and mailed: see the 'To' and 'Newsgroups' headers for details. ]] Clarifications: 1) Truth test simplified after a %) by Peter Otten - thanks. In reality the "testit" methods will all be quite different as you might imagine (as will the "doit" methods). 2) A final subclass will always return True, so there will always be a valid factory (?) result. ==================== Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy "if" sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the "doit" methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach and/or how I might improve it 2) The implications of using this in a recursive approach (referenced from but outside the recursive function). 3) Any other comments you might offer Thank you, Lee C =========== ootest.py ============ class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): return (tv == 'relates to A') def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): return (tv == 'relates to B') def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() ======== Test run ============== Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> import ootest # did B # # did A # >>> From fuzzyman at gmail.com Wed Jun 29 14:48:49 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jun 2005 11:48:49 -0700 Subject: urllib2, https, and proxies Message-ID: <1120070929.090189.81680@g14g2000cwa.googlegroups.com> Hello all (well, some of you I guess), Is it true that you can't configure a proxy handler for urllib2 to fetch https URLs through a proxy ? I know that you pass a dictionary, keyed by protocol, to the proxy handler - but when we get an exception when we fetch an https URL. Fetching the same URL, through the same proxy, with a browser works fine. Sorry I can't post code and a traceback - can do that tomorrow if necessary. Best Regards, Fuzzy http://www.voidspace.org.uk/python From deets at web.de Wed Jun 1 19:31:19 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 02 Jun 2005 01:31:19 +0200 Subject: Monitoring a USB-drive / Card-reader using python? In-Reply-To: <1117631833.428067.305950@o13g2000cwo.googlegroups.com> References: <1117631833.428067.305950@o13g2000cwo.googlegroups.com> Message-ID: Thomas W wrote: > I want to monitor a given USB-device, like a Memory Card-reader, and > when a memory card is inserted I want to move the data on the card to a > different location on the filesystem ( or do something else with the > files). > > Does anybody know how to do this ( on Linux and/or windows ) or if it's > even do-able ? Under linux use FAM and udev, together with Python FAM binding From travis.ray at gmail.com Mon Jun 13 19:26:51 2005 From: travis.ray at gmail.com (travis ray) Date: Mon, 13 Jun 2005 19:26:51 -0400 Subject: reading a python file object in c extension crashes python Message-ID: Hi, I have an extension in which a file object is created in python and passed down to a c extension which attempts to read from it or write to it. Writing to the file pointer seems to work okay, but reading from it results in EBADF and causes python to crash on exit. I've attached the minimal (I think) c code, python code, build script, build log, and run log. Any and all help is greatly appreciated. Thanks. System: Win-XP Professional Compiler: Vc7 (MSVS 2003) Python: Python 2.4.1 Builder: SCons 0.96.1 -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: my_module.c URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: my_module.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: SConstruct Type: application/octet-stream Size: 541 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: build.log Type: application/octet-stream Size: 384 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: run.log Type: application/octet-stream Size: 199 bytes Desc: not available URL: From Holger.Joukl at LBBW.de Thu Jun 9 11:41:09 2005 From: Holger.Joukl at LBBW.de (Holger Joukl) Date: Thu, 9 Jun 2005 17:41:09 +0200 Subject: XML + SOAP + Webservices In-Reply-To: <12629969.1118316112666.JavaMail.tbone@ssmg102> Message-ID: This may be of some help for you. It?s unfinished business, though. So far, the ZSI stuff has worked quite well for me, but as mentioned I am also a web services beginner. I am writing this in lyx so I might be able to post in other formats. For the time being, this is the first part in pure text. Cheers, Holger >>> Interoperable WSDL/SOAP web services introduction: Python ZSI , Excel XP & gSOAP C/C++ Holger Joukl LBBW Financial Markets Technologies Abstract Despite the hype & buzzword-storm, building web services servers and clients still is no piece of cake. This is partly due to the relative newness of technology. For the most part, though, this results from the actual complexness of the protocols/specs, the toolkit magic behind which this complexness is hidden, and the documentation gaps that exist for the toolkits. This document is intended to be an example-loaded simple tutorial, to ease the use for web services newcomers (like I am one). It features the Python ZSI module that is used to build the server side machinery and clients that access the exposed services from Python, MS Excel XP, and C/C++ using gSOAP. Copyright ? 2005 Holger Joukl. All rights reserved. Redistribution and use in source (LyX, LaTeX) and 'compiled' forms (SGML, HTML, PDF, PostScript, RTF and so forth) with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code (LyX, LaTeX) must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified. 2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS DOCUMENTATION IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 1 Introduction We assume the reader is familiar with Python, C/C++ and MS Excel/VisualBasic. While some basic concepts regarding WSDL, SOAP, HTTP servers etc. might be touched this document is NOT a tutorial on these. If you want to know more there?s plenty of stuff on the web. Please note that currently, throughout most examples, certain host names and ports are used - substitute them with the setup for your site.. Versions used: * Python 2.3 * PyXML 0.8.3 * ZSI 1.6.1 * ... To Describe: WS-I, rpc/literal 2 The SquareService This first example will implement a service that exposes a function which takes a double argument and returns the square of it ( x{}^{\textrm{2}} ) as a double. I.e. this examples uses simple scalar datatypes, one single argument and one single return value. 2.1 The SquareService WSDL This is the WSDL file that determines the contract for the SquareService, called SquareService.wsdl: the square method Returns x^2 (x**2, square(x)) for a given float x Comments: * The style "rpc" and the use "literal" are used, to be WS-I-compliant. WS-I only supports rpc/literal and document/literal. 2.2 A Python ZSI server for the SquareService The Python ZSI package [key-1] is one of two pywebsvcs packages implementing web services for Python, namely SOAP messaging and WSDL capabilities. It is powerful and very easy to get started with, but lacks some documentation enhancements when it comes to WSDL-driven service generation. While the tools to do that are already there, documentation is sparse and examples are hard to find. All examples here are based on ZSI 1.6.1. 2.2.1 Generating stubs from WSDL ZSI comes with two python scripts to generate code from a WSDL file: * wsdl2py is used to generate python bindings for the service. * wsdl2dispatch generates a server frame for service dispatch where the actual worker functions will be hooked into. If you have installed ZSI on top of your python installation you can invoke the scripts like this (change your installation base path according to your setup):The installation base path for all examples here is /apps/pydev/gcc/3.4.3/. 1. wsdl2py: /apps/pydev/gcc/3.4.3/bin/wsdl2py -f SquareService.wsdl This will generate the file SquareService_services.py. 2. wsdl2dispatch: /apps/pydev/gcc/3.4.3/bin/wsdl2dispatch -f SquareService.wsdl This will generate the file SquareService_services_server.py. What do we have now? We have bindings to work with the services in python and a skeleton for dispatching to the actual worker methods. What we still need is * the main program that runs a (HTTP-) server with a request handler for the services and * the hooks to invoke the worker methods. Luckily, ZSI includes the ZSI.ServiceContainer module which implements the server for us. 2.2.2 Writing the web services server This is our main program mySquareServer.py: #! /apps/pydev/gcc/3.4.3/bin/python2.3 from ZSI.ServiceContainer import ServiceContainer, SOAPRequestHandler from SquareService_services_server import SquareService import os class MySOAPRequestHandler(SOAPRequestHandler): """Add a do_GET method to return the WSDL on HTTP GET requests. Please note that the path to the wsdl file is derived from what the HTTP invocation delivers (which is put into the self.path attribute), so you might want to change this addressing scheme. """ def do_GET(self): """Return the WSDL file. We expect to get the location from the invocation URL ("path"). """ wsdlfile = os.path.join('.', self.path.replace('/', "", 1) + ".wsdl") print ">>>>> using wsdlfile", wsdlfile wsdl = open(wsdlfile).read() self.send_xml(wsdl) # Copied from ZSI.ServiceContainer, extended to instantiate with a custom # request handler def AsServer(port=80, services=(), RequestHandlerClass=SOAPRequestHandler): '''port -- services -- list of service instances ''' address = ('', port) sc = ServiceContainer(address, RequestHandlerClass=RequestHandlerClass) for service in services: path = service.getPost() sc.setNode(service, path) sc.serve_forever() AsServer(port=8080, services=[SquareService()], RequestHandlerClass=MySOAPRequestHandler) We wouldn?t have needed to write the custom request handler MySOAPRequestHandler if not for the do_GET method. But both Python ZSI clients using the ServiceProxy class and MS VisualBasic SOAP clients expect to receive the WSDL when issueing HTTP GET, which is actually common behaviour to get the service description (apart from UDDI). Similarly, the AsServer(...) function had to be extended to make use of our custom request handler. 2.2.3 Hooking-in the service implementation The only thing left now is to hook in the implementation of the service. We need to * dispatch to the correct service method, * feed it the arguments received via a SOAP request and * set the return values for the SOAP response. This is the implementation for the SquareService getSquare method (or operation, in WSDL terms): from SquareService_services import * from ZSI.ServiceContainer import ServiceSOAPBinding class SquareService(ServiceSOAPBinding): # This dictionary is used to dispatch to the appropriate method. # Not that the dict key(s) are identical to the soapAction attributes of the # field(s) in the WSDL: # ... # # ... # The value(s) for the key(s) are the generated soap_<...> method names. soapAction = { 'http://dev-b.handel-dev.local:8080/SquareService/getSquare': 'soap_getSquare', } def __init__(self, post='/SquareService', **kw): ServiceSOAPBinding.__init__(self, post) def soap_getSquare(self, ps): # input vals in request object # MANUALLY CORRECTED: # args = ps.Parse( getSquareRequestWrapper() ) # Use the class instead of an instance of the class. # Note: The erroneous code generation happens for rpc/literal, but not # for rpc/encoded, where using an instance works (?). args = ps.Parse( getSquareRequestWrapper ) # assign return values to response object response = getSquareResponseWrapper() # >>> ADDED MANUALLY # Here we hook in the actual worker method response._return = self.getSquare(args._x) # <<< return response # the (handwritten) worker code def getSquare(self, x): """Return square(x). """ return x**2 Note that ZSI does almost all the work for us, again. The only additions we had to do are: * Implementing the getSquare(...) worker method. We could also have invoked a function, used a lambda, put the worker code into soap_getSquare, etc. * Hooking getSquare in. This is done in the ... # >>> ADDED MANUALLY # Here we hook in the actual worker method response._return = self.getSquare(args._x) # <<< ... bits where * the x input argument is taken from the incoming SOAP request and handed to the getSquare method * the return field of the SOAP response message to be sent out is set with the getSquare result As you can see in the WSDL above the "getSquareRequest" message has a "part" with the name "x"; ZSI exposes this as attribute "_x" of the incoming parsed SOAP request message "args" instance. The same applies to the "return" part of the response message. ZSI exposes this to python as attribute "_return" of the getSquareResponseWrapper instance. * Correcting the line # args = ps.Parse( getSquareRequestWrapper() ) to args = ps.Parse( getSquareRequestWrapper ) This seems to be a bug in the code generation.When experimenting with rpc/encoded-style first, this line works "as is". 2.3 A Python ZSI client for the SquareService We implement a client that calls getSquare from the SquareService in myServiceProxyClient.py as follows: #!/apps/pydev/gcc/3.4.3/bin/python2.3 import sys import getopt from ZSI import ServiceProxy import ZSI.wstools.WSDLTools #------------------------------------------------------------------------------ # default configuration #------------------------------------------------------------------------------ port = 8080 host = 'dev-b' #------------------------------------------------------------------------------ # command line parsing #------------------------------------------------------------------------------ def usage(rcode=1): print "usage: myServiceProxyClient.py [--host= --port=,-c --help, -h]" sys.exit(rcode) try: optlist, args = getopt.getopt(sys.argv[1:], "hp:", ['help', 'port=']) except getopt.GetoptError: usage() for opt, arg in optlist: print opt, arg if opt in ["-h", "--help"]: usage(0) elif opt in ["--host"]: host = arg continue elif opt in ["-p", "--port"]: port = int(arg) continue url = 'http://' + host + ':' + str(port) + '/SquareService' # Hmm, if we want to send to the correct service location we # must set use_wsdl. service = ServiceProxy(url, use_wsdl=True, tracefile=sys.stdout, ns='http://dev-b.handel-dev.local:8080/SquareService') print 'service is', service print service.__dict__ print '\nAccessing service getSquare...' while 1: # Must use keyword arguments if use_wsdl was set x = float(raw_input("Enter number: ")) result = service.getSquare(x=x) print 'result:', result References Salz, Rich; Blunck Christopher: ZSI: The Zolera Soap Infrastructure. , Release 1.6.1, December 08, 2004. Der Inhalt dieser E-Mail ist vertraulich. Falls Sie nicht der angegebene Empf?nger sind oder falls diese E-Mail irrt?mlich an Sie adressiert wurde, verst?ndigen Sie bitte den Absender sofort und l?schen Sie die E-Mail sodann. Das unerlaubte Kopieren sowie die unbefugte ?bermittlung sind nicht gestattet. Die Sicherheit von ?bermittlungen per E-Mail kann nicht garantiert werden. Falls Sie eine Best?tigung w?nschen, fordern Sie bitte den Inhalt der E-Mail als Hardcopy an. The contents of this e-mail are confidential. If you are not the named addressee or if this transmission has been addressed to you in error, please notify the sender immediately and then delete this e-mail. Any unauthorized copying and transmission is forbidden. E-Mail transmission cannot be guaranteed to be secure. If verification is required, please request a hard copy version. From jnoller at gmail.com Fri Jun 24 15:20:08 2005 From: jnoller at gmail.com (Jesse Noller) Date: Fri, 24 Jun 2005 15:20:08 -0400 Subject: OT: Boston-Area QA/Python Job Message-ID: <4222a8490506241220b90a43@mail.gmail.com> Sorry for the off-topic post everyone. The company I work for has a job opening for a Senior QA/Automation person, and they are looking for someone strong in Python to help develop tests/testing frameworks/etc. The complete job description follows - you can feel free to email resumes and questions to jnoller at gmail dot com the company website is http://www.archivas.com Job description: Senior QA Engineer ? Test Automation Archivas is actively seeking a highly motivated, self-starting QA Engineer with a strong development background to help in the development of automated tests. In this position, you will be responsible for defining, executing and developing tests to help to increase or test coverage and to ensure product quality. This will require strong development skills and solid QA skills . You will also be responsible for the analysis, report generation, and communication of test results. Responsibilities This position will be responsible for the following: - Develop test plans and test cases to ensure product quality. - Automate tests (preferably in Python or Java) to be executed in our Automated Test Framework (written in Python) - Test development and execution at all levels (unit, component, integration and system, white box and black box) - Develop and maintain testing tools/scripts (preferably written in Python or Java) - Report product defects and track defects to closure. - Work closely with development to resolve escalated issues. - Help prioritize product defects and feature requests. - Help review and contribute to product documentation. - Act as backup and escalation path for Technical Support. - Assist in the support of beta customers. Position requirements include: - 5+ years experience testing systems products - Comprehensive knowledge and application of Software Quality Assurance methodologies - Experience developing automated test cases - Strong development experience in scripting or programming languages (specifically: Python or Java). - Experience testing and developing automated tests for a mixed Linux (*nix) and Windows environments required. - Strong written and verbal communication skills. - Computer Science Degree or equivalent experience. Additional Skills (a plus): - Experience with relational databases such as PostgresQL or SQL - Experience with QA testing tools: code coverage analysis tools, performance testing tools, automated test tools - Experience with software development tools: source code control system such as Perforce or ClearCase, build tools such as ant or make, and bugtracking tools like Bugzilla or ClearQuest. Desired Personal Characteristics: - Independent: Able to grasp high level product requirements and translate these to detailed test plans. Capable of gathering required information from engineers and product marketing to perform job function. - Strong sense of ownership: Sees defects throughout their lifecycle; from detection to resolution. - Assertive: Champions causes that will benefit the company. Willing to engage engineers and management in discussions on bug resolution. - Communicative: Takes an "open source" attitude to quality assurance. Keeps others in the company informed and up to date on his or her priorities, current tasks and work completed. Encourages constructive criticism on his or her work. - Accountable: He or she should be a results-oriented team player who leads by example, holds themselves accountable for performance, takes absolute ownership, and champions all aspects of quality initiatives. - Sense of urgency. Escalates quality issues when appropriate; maintains a sense of "bug ownership" to see all issues through to a successful resolution. Strives to turn around issues with an efficient and effective approach. - Flexible and adaptable. Should be able to switch gears in various high-stress situations and apply themselves to quickly learning new technologies and adopting new methodologies. From steve at REMOVETHIScyber.com.au Sat Jun 18 10:27:01 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 19 Jun 2005 00:27:01 +1000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 18 Jun 2005 15:00:02 +0200, Renato Ramonda wrote: > cpunerd4 ha scritto: >> thanks all for the advice. The reason I was thinking about using java >> (or C or something) was that it is a little more secure than >> distributing the source code isn't it? > > As in "protecting your code from prying eyes"? Code isn't damaged by prying eyes, so why does it need to be protected? I don't know what cpunerd4 (or whatever she, or he, prefers to be called) means by "more secure". But to me, "secure" means "there are no security holes or bugs with security implications in my software". Hiding the source code does not make software more secure. Any bugs and security holes will be there whether the software is distributed in source code, object code, or something in between. Anybody who thinks that hiding the source code makes their programs more secure is in for a rude shock. The basic premise of security by obscurity is that you try to ensure security by hiding certain facts about the software or algorithm from regular users, hoping that nobody will find out what those facts are. This is equivalent to putting an unlocked door in your house, then draping some branches over it, trusting that the burglars won't see the secret door and gain access to your house. Anybody who doesn't understand why keeping source code secret does not increase security should google for "security by obscurity". -- Steve. From guy.lateur at b-b.be Thu Jun 9 11:18:57 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 09 Jun 2005 15:18:57 GMT Subject: how to retrieve info about print jobs References: <3EAne.108100$xW2.6437935@phobos.telenet-ops.be> Message-ID: Hmm, this only seems to work for jobs that originate on the machine running the script. I really need something that actually gathers the info from the printers (net-based). Would that be possible at all? "Simon Brunning" schreef in bericht news:mailman.392.1117713984.18027.python-list at python.org... On 6/2/05, Guy Lateur wrote: > We have several printers in our company network. I would like to know if > it > is possible to check the current print jobs/queues for each of them. That > way, if a user wants to print something (big), I could give her a hint as > to > which printer would get the job done first. We're using win2k and xp, btw. You can probably do this with WMI. Ah yes, see . You can drive WMI from Python with Tim Golden's WMI module - . Do let us know what you come up with! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From x at jwp.name Thu Jun 30 21:45:17 2005 From: x at jwp.name (James William Pye) Date: Thu, 30 Jun 2005 18:45:17 -0700 Subject: ANN: PL/Py 0.1 Release Message-ID: After much hacking, and many liters of caffeinated beverages, it is my pleasure to announce the first development release of PL/Py, the PostgresPy Project[1]'s Backend elements for the PostgreSQL ORDBMS. The very terse project news item can be found here[2]. PL/Py, PostgresPy's Backend Project, is a procedural language extension for PostgreSQL, and a Python extension module providing Python interfaces to PostgreSQL internals. It provides a PostgreSQL DBA with the necessary functionality to create and execute functions written in Python within the backend. It has been designed with the principle of separating the embedding instance from the extension module(interfaces), so as to provide a very clean implementation. The PL features the following: * Set Returning Functions. * State keeping (think generators, etc, yes even for SRFs!). * Type system interface (Single dimensional arrays and Composites). * Direct Database Function Calls. * Objectified Queries. * Exception management and interfaces. * Encoding Choreography (Works with the Database's encoding). * HeapTuple/TupleDesc interface types. * Transaction Dictionary. * Direct Portal interface. * Internal Subtransactions. * file like Large Object interface. * Full tracebacks and exception information in uncaught exceptions. * Procedure validation (Syntax check on CREATE and Code storage). * Direct Relation interface (coming soon). * Boogs. Yes, there are bugs. For the quickest way to get started, see the Quick Start page[3]. The documentation for this project has yet to be completed. Some doc-strings exist, so using the sandbox mentioned in the Quick Start is the best way to discover the features of the PL. [1] http://python.projects.postgresql.org [2] http://pgfoundry.org/forum/forum.php?forum_id=449 [3] http://python.projects.postgresql.org/quick.html From Aiwass333 at gmail.com Thu Jun 2 15:26:48 2005 From: Aiwass333 at gmail.com (RunLevelZero) Date: 2 Jun 2005 12:26:48 -0700 Subject: Easy way to detect hard drives and partitions in Linux In-Reply-To: References: <1117730941.946683.88840@g44g2000cwa.googlegroups.com> Message-ID: <1117740408.061933.185050@g43g2000cwa.googlegroups.com> Jeff Epler wrote: > You're not going to find a single portable "unix" way of doing this. > The format of /etc/fstab and /etc/mtab are pretty portable, but they > only list mountable/mounted partitions, not all partitions. > > In addition to the linux possibilities mentioned in another reply, there > is also /proc/partitions. Finally, if you only want to recognize > FDISK.EXE-type partitions (used by many types of Linux, though that > seems to be changing in Fedora Core 4), it shouldn't be hard to write a > Python program to read the partition table directly from the disk. The > details will be readily available online. > > Jeff Well thanks for the responses and so quickly. I'm very new to programming and am not afraid to say it. I'll see what I can come up with. at least this is a good start. Thanks. From cotyspend at yahoo.com Wed Jun 1 12:53:12 2005 From: cotyspend at yahoo.com (nephish) Date: 1 Jun 2005 09:53:12 -0700 Subject: cgi help In-Reply-To: <429dac47$0$28450$636a15ce@news.free.fr> References: <1117581222.027646.25710@o13g2000cwo.googlegroups.com> <429dac47$0$28450$636a15ce@news.free.fr> Message-ID: <1117644792.256751.54650@g14g2000cwa.googlegroups.com> whoa, thanks been trying to figgure this out for a week. cant wait to try it this weekend. thanks again. From tim.golden at viacom-outdoor.co.uk Wed Jun 29 06:35:22 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 11:35:22 +0100 Subject: Open running processes Message-ID: <9A28C052FF32734DACB0A288A3533991EBB947@vogbs009.gb.vo.local> [DeRRudi] | It is a wxWindow app. It is a kind of datamanager. it is possible to | minimize it to the systray. | | hmm.. i've thought of an solution using memorymapping. see if it | works.. don't know if it is the 'best' or 'safest' way.. but ok. Did your idea work out? If it didn't (or if it did!) could you post some code? I'd be interested in seeing a working solution to this. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From noreply at gcgroup.net Mon Jun 13 12:27:27 2005 From: noreply at gcgroup.net (William Gill) Date: Mon, 13 Jun 2005 16:27:27 GMT Subject: string formatting using the % operator In-Reply-To: References: Message-ID: Dan Sommers wrote: > On Mon, 13 Jun 2005 15:12:54 GMT, > William Gill wrote: > > >>I am using the % operator to create queries for a db app. It works fine >>when exact strings, or numbers are used, but some queries need partial >>matching that use the '%' as a wildcards. So for example the resultant >>string should be 'WHERE name LIKE %smith%' (would match silversmith, >>smithy, and smith). Is there any way to get something like > > >> searchterm = 'smith' >> sql += 'WHERE name LIKE %s' % searchterm > > >>to return 'WHERE name LIKE %smith%' I have tried using escapes, >>character codes for the % sign, and lots of other gyrations with no >>success. The only thing that works is if I modify searchterm first: > > >> searchterm = 'smith' >> searchterm ='%'+'smith'+'%' >> sql += 'WHERE name LIKE %s' % searchterm > > >>Any Ideas? > > > Let the DB-API do more work for you: > > cursor = connection.cursor( ) > sql = """SELECT column2, columns3 FROM table WHERE name LIKE %s""" > values = ('%%%s%%' % searchterm,) # note that this is a tuple > cursor.execute( sql, values ) > > HTH, > Dan > I can't tell you how many times I looked at the table of format codes and missed this. Thanks everyone! From kent37 at tds.net Fri Jun 17 13:02:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 13:02:18 -0400 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? In-Reply-To: References: Message-ID: <42b3019c$1_1@newspeer2.tds.net> kj wrote: > I'm a Perlhead (there, I said it). Years ago I made a genuine > attempt to learn Python, but my intense disappointed with the way > Python deals with scopes ultimately sapped my enthusiasm. I couldn't > live without closures and without the fine control over scopes that > Perl provides. Python has supported nested (lexical) scopes and closures since version 2.1, maybe this gives you enough control; see http://www.amk.ca/python/2.1/index.html#SECTION000300000000000000000 Kent From dalke at dalkescientific.com Fri Jun 3 11:46:56 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 03 Jun 2005 15:46:56 GMT Subject: Formatting Time References: Message-ID: Coates, Steve (ACHE) wrote: >>>> import time >>>> t=36100.0 >>>> time.strftime('%H:%M:%S',time.gmtime(t)) > '10:01:40' But if t>=24*60*60 then H cycles back to 0 >>> import time >>> t=24*60*60 >>> time.strftime('%H:%M:%S',time.gmtime(t)) '00:00:00' >>> Andrew dalke at dalkescientific.com From adurdin at gmail.com Mon Jun 20 00:17:25 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Mon, 20 Jun 2005 14:17:25 +1000 Subject: case/switch statement? In-Reply-To: References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Message-ID: <59e9fd3a050619211773c1da80@mail.gmail.com> On 6/18/05, D H wrote: > I would hardly call using a > dictionary as a switch statement, the "equivalent". The fact that > people use a dictionary as a conditional is a python wart. Not at all. A case statement is nothing more than a literal mapping of constant values to the execution of code blocks; a dictionary is a (not necessarily literal) mapping of hashable (not just constant) values to other values. A dictionary is a very close match for the operation of a case statement. In the common (in my experience) instance where the case statement is like (using C notation): switch(x) { case 1: y = foo; break; case 2: y = bar; break; case 3: y = baz; break; default: y = qux; } In this case the dictionary is obviously a better and clearer choice. I've generally found for other circumstances where I've used switch statements that the code ends up more readable if it's reorganised so that the switch statements are all of the form above, or are eliminated entirely--so I don't miss a switch/case statement in Python. And, just because we can, the most direct equivalent (in terms of written code) of a switch/case statement in Python is: exec { 1: "y = foo", 2: "y = bar", 3: "y = baz" }.get(x,"y = qux") But I didn't say it was nice... From jussij at zeusedit.com Thu Jun 23 09:29:54 2005 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Thu, 23 Jun 2005 23:29:54 +1000 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: <42BAB952.69F3@zeusedit.com> Dennis Lee Bieber wrote: > Firebird might be a contender... I recently completed a 5 user Java based Windows reporting system that used Firebird as the SQL server based database. I found Firebird performed very well and I would not hesitate to use it again. Jussi Jumppanen Author of: Zeus for Windows Editor (New version 3.94 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl folding editor" Home Page: http://www.zeusedit.com From newsgroups at jhrothjr.com Tue Jun 21 20:30:49 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 21 Jun 2005 18:30:49 -0600 Subject: need to strip stuff off email References: Message-ID: <11bhc9u7925cv38@news.supernews.com> "nephish" wrote in message news:mailman.723.1119399951.10512.python-list at python.org... > hey there, > i have a script that retrieves my email, but i need it to > be able to strip all the stuff off except the body (the message itself) > so i can later write it to a text file. > > anyone know how to accomplish this? > thanks See the example at the end of the email package documentation. John Roth From jrastrick at student.usyd.edu.au Wed Jun 8 15:36:37 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 8 Jun 2005 12:36:37 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> Message-ID: <1118259397.502842.260270@z14g2000cwz.googlegroups.com> Well, I'll admit I haven't ever used the Numeric module, but since PEP207 was submitted and accepted, with Numeric as apparently one of its main motivations, I'm going to assume that the pros and cons for having == and ilk return things other than True or False have already been discussed at length and that argument settled. (I suppose theres a reason why Numeric arrays weren't just given the same behaviour as builtin lists, and then simple non-special named methods to do the 'rich' comparisons.) But again, it seems like a pretty rare and marginal use case, compared to simply wanting to see if some object a is equal to (in a non object identity sense) object b. The current situation seems to be essentially use __cmp__ for normal cases, and use the rich operations, __eq__, __gt__, __ne__, and rest, only in the rare cases. Also, if you define one of them, make sure you define all of them. Theres no room for the case of objects where the == and != operators should return a simple True or False, and are always each others complement, but <, >= and the rest give an error. I haven't written enough Python to know for sure, but based on my experience in other languages I'd guess this case is vastly more common than all others put together. I'd be prepared to bet that anyone defining just __eq__ on a class, but none of __cmp__, __ne__, __gt__ etc, wants a != b to return the negation of a.__eq__(b). It can't be any worse than the current case of having == work as the method __eq__ method describes but != work by object identity. So far, I stand by my suggested change. From superprad at gmail.com Wed Jun 1 19:34:08 2005 From: superprad at gmail.com (PyPK) Date: 1 Jun 2005 16:34:08 -0700 Subject: Performance Issues please help Message-ID: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> I was testing this piece of code and it takes about 24-30 seconds to do a look up on a list(m) of size 1000x1000 m -> list of size 1000x1000 import time print time.ctime() box = {} for r,row in enumerate(m): for c,e in enumerate(row): if box.has_key(e): params = box[e] box[e] = ( min(c, params[0]), min(r, params[1]), max(c, params[2]), max(r, params[3] ) ) else: box[e] = [c, r, c, r] print time.ctime() Can some one tell me what exactly is taking more time here. Is it because I am using dictionaries or what is the problem. Can some one help me improve this .Is there a better way to write this. From simon.dahlbacka at gmail.com Wed Jun 1 06:05:05 2005 From: simon.dahlbacka at gmail.com (simon.dahlbacka at gmail.com) Date: 1 Jun 2005 03:05:05 -0700 Subject: working with pointers In-Reply-To: References: Message-ID: <1117620305.253608.56680@g47g2000cwa.googlegroups.com> this might help.. http://effbot.org/zone/python-objects.htm From idontneednostinkinid at yahoo.com Wed Jun 1 18:24:21 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 15:24:21 -0700 Subject: idiom for constructor? In-Reply-To: References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <1117664661.583868.275460@g49g2000cwa.googlegroups.com> This was the direction I was aiming for initially, and I have used this form before, but was hoping there was a way I could go one step further, and somehow get rid of the repetition of "self."... Heh, ideally: self.{a,b,c,d} = a,b,c,d Alas, not Python syntax... :) I do like Steven's form of a solution, and I think I'll give it a spin for the really ugly spots (refactoring is too expensive right now; prototype-code). From david.bear at asu.edu Mon Jun 13 20:09:29 2005 From: david.bear at asu.edu (David Bear) Date: Mon, 13 Jun 2005 17:09:29 -0700 Subject: just learning eric ide Message-ID: <28706111.YDTNr6pyWa@teancum> Eric is the first IDE I have used since the borland c++ ide for dos many many years ago. Aside from the docs that come in the help system, I'm looking for a quick tutorial that gives me an overview of the test, debug cycle that is considered -- for beginners. any pointers or books. This seems like a terrific environment. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From ml at dynkin.com Sat Jun 4 00:08:32 2005 From: ml at dynkin.com (George Yoshida) Date: Sat, 04 Jun 2005 13:08:32 +0900 Subject: couple of new python articles on onlamp In-Reply-To: References: Message-ID: Kongulo(google crawling tool) seems to be using your App, py2exe. Great work, Thomas! Thomas Heller wrote: > Jeremy Jones writes: > > >>I've got a couple of new articles on ONLamp: >> >>Writing Google Desktop Search Plugins >>http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html >> >>and >> >>Python Standard Logging >>http://www.onlamp.com/pub/a/python/2005/06/02/logging.html >> >> >>Comments, criticisms, flames all welcome. > > > I've read the logging article, and I like it. Good work. > > Thanks, > > Thomas -- george From Sebastien.Boisgerault at gmail.com Fri Jun 17 10:58:46 2005 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 17 Jun 2005 07:58:46 -0700 Subject: Embedding Python Message-ID: <1119020326.409233.89120@g44g2000cwa.googlegroups.com> Hi, Imagine that you have a PyObject pointer 'object' pointing to a Python integer ... let's say 42. How would do you attach the variable "answer" to it so that the code PyRun_SimpleString("print answer"); works as expected ? My current solution is: __main__ = PyImport_ImportModule("__main__"); PyObject_SetAttrString(__main__, "answer", object); Anything better ? SB From vibtrip at yahoo.com Thu Jun 16 12:09:59 2005 From: vibtrip at yahoo.com (Vibha Tripathi) Date: Thu, 16 Jun 2005 09:09:59 -0700 (PDT) Subject: Set of Dictionary In-Reply-To: <4660fe3005061608023c4f96ab@mail.gmail.com> Message-ID: <20050616160959.34219.qmail@web53910.mail.yahoo.com> I need sets as sets in mathematics: sets of any unique type of objects including those of dictionaries, I should then be able to do: a_set.__contains__(a_dictionary) and things like that. Can sets in Python 2.4.1, be reimplemented from scratch to not have it work on top of dict? Peace. Vibha --- Konstantin Veretennicov wrote: > On 6/16/05, Vibha Tripathi > wrote: > > Hi Folks, > > > > I know sets have been implemented using dictionary > but > > I absolutely need to have a set of dictionaries... > > While you can't have a set of mutable objects (even > dictionaries :)), > you can have a set of immutable snapshots of those > objects: > > >>> d1 = {1: 'a', 2: 'b'} > >>> d2 = {3: 'c'} > >>> s = set([tuple(d1.iteritems()), > tuple(d2.iteritems())]) > >>> s > set([((3, 'c'),), ((1, 'a'), (2, 'b'))]) > >>> [dict(pairs) for pairs in s] > [{3: 'c'}, {1: 'a', 2: 'b'}] > > - kv > ======= "Things are only impossible until they are not." __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kristian.zoerhoff at gmail.com Fri Jun 24 09:09:26 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Fri, 24 Jun 2005 08:09:26 -0500 Subject: Two questions on lambda: In-Reply-To: References: Message-ID: <3511dc75050624060963b94568@mail.gmail.com> On 6/24/05, Xavier D?coret wrote: > > For example, the code > > # f = lambda : print "hello" > # f() > does not compile, although: > > # def f(): > # print "hello" > # f() > > does compile. Is there a particular syntax for lambda that I am missing > or is it simply limited and I cannot do what I want with lambda. lambda calls can only include functions; print is a statement, not a function. Try this instead: import sys f = lambda : sys.stdout.writelines("Hello") f() However, if you're going to be binding the function to a name, there is no need to use lambda at all; just def a function and be done with it. > In the same spirit, how can I do to compute intermediary values in the > body of a lambda function. Let's say (dummy example): I leave this to someone more expert than I. -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From grante at visi.com Sun Jun 19 23:57:23 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 20 Jun 2005 03:57:23 -0000 Subject: extreme newbie References: <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> <42B48FDE.4010700@lexicon.net> <0s7bb111j9iimeicputkooj4a8gf4l2dji@4a Message-ID: <11bcfl3icgm5836@corp.supernews.com> On 2005-06-19, Dennis Lee Bieber wrote: > Such lovely things allowed as: embedding non-printable control > characters into file names. Don't most OSes allow that? Unix does, and IIRC VMS did as well. In VMS there was a system call that let you change the name shown by the equivalent of "ps". You could include control characters in that string, and it was sort of fun to change your name to little ASCII-art pictures. Well, it was fun when you were a freshman. > Makes it real fun for someone to figure out just where in a > 10-character file name that console-beep is placed Under Unix it's not all that hard to accidentally create files like that. Sometimes you have to resort to blasting them away by i-node number, or by moving the files you want to keep and then nuking the directory. -- Grant Edwards grante Yow! I will SHAVE and at buy JELL-O and bring my visi.com MARRIAGE MANUAL!! From rupole at hotmail.com Mon Jun 6 22:58:45 2005 From: rupole at hotmail.com (Roger Upole) Date: Mon, 6 Jun 2005 22:58:45 -0400 Subject: what can happen if Python wents commercial ;-) ... References: <3gh5gaFc82m3U1@individual.net> Message-ID: <42a50e72$1_1@spool9-west.superfeed.net> So that's how the PSF is raising funds now ! Roger "Claudio Grondi" wrote in message news:3gh5gaFc82m3U1 at individual.net... > don't click the following link if you are not > at least 18 years old (or don't like sexual > related content): > http://www.python.com/ > > Claudio > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From bretthoerner at gmail.com Mon Jun 27 23:13:41 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 27 Jun 2005 20:13:41 -0700 Subject: Better console for Windows? In-Reply-To: <1119927705.432472.65820@z14g2000cwz.googlegroups.com> References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> Message-ID: <1119928421.011284.183810@o13g2000cwo.googlegroups.com> Rune Strand wrote: > I know that problem... it's extremely annoying! > Here's one way to solve it; > > 1. Start 'Device manager'. > 2. On the menu, click 'View' and check off "Show hidden devices" > 3. Locate 'Beep' 'under Non-Plug and Play Drivers' > 4. Right-click 'Beep', select 'Disable' Christ, thanks. When you install Windows it should pop up first thing and ask if you want to be annoyed, Y/N. Well, that solves my sound problem (thanks again), now if only I could stretch the window horizontally. Thats much less of a problem though, this is at least usable now. Thanks again, Rune From be_veronic at yahoo.com Thu Jun 9 11:43:21 2005 From: be_veronic at yahoo.com (Veronica Tomescu) Date: Thu, 9 Jun 2005 08:43:21 -0700 (PDT) Subject: killing process in windows In-Reply-To: <20050609152958.GA22482@ActiveState.com> Message-ID: <20050609154321.88442.qmail@web32510.mail.mud.yahoo.com> Hi Mick, Thanks for your reply.It works fine until killing the process.Wmplayer is started,I can see the process in the task manager list,I also tried with notepad and it's the same problem. I appreciate if you can help. Vero Trent Mick wrote: [Miki Tebeka wrote] > Hello Veronica, > > > I am using Trent's process.py but I have a problem with killing the > > processes in windows. > > For example : > > > > import process,time > > > > p=process.ProcessOpen('C:\Program Files\Windows Media > > Player\wmplayer') > > time.sleep(3) > > p.kill() > > > > will start Media Player without terminating it. > > Any suggestions? > A brutal way will be to use win32process.TerminateProcess (from win32all > package - http://starship.python.net/crew/mhammond/). Miki, actually my process.py *is* using TerminateProcess under the hood here. Veronica, Sorry, I really don't know what might be causing the problem here. Does your little snippet work properly for other applications like, say, Notepad, iexplore.exe, Word? Note that I'm am going to put the path in a list to be sure that the it gets quoted properly. It *might* be correct as just a string (as you had it) but I'd have to check. If you do this in the interactive shell (don't quit the shell): >>> import process >>> p = process.ProcessOpen(["C:\Program Files\Windows Media Player\wmplayer"]) Does media player start? Is there a "wmplayer.exe" is the process list (press Ctrl+Esc to open Task Manager)? Now try this is the same interactive shell: >>> p.kill() Trent -- Trent Mick TrentM at ActiveState.com __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gsakkis at rutgers.edu Sat Jun 25 14:20:45 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Jun 2005 11:20:45 -0700 Subject: regex question References: <3i59q5Fjm0hsU1@individual.net> Message-ID: <1119723645.540021.266690@g44g2000cwa.googlegroups.com> "Felix Schwarz" wrote: > Hi all, > > I'm experiencing problems with a regular expression and I can't figure > out which words I use when googling. I read the python documentation for > the re module multiple times now but still no idea what I'm doing wrong. > > What I want to do: > - Extract all digits (\d) in a string. > - Digits are separated by space (\w) > > What my program does: > - It extracts only the last digit. > > Here is my program: > import re > line = ' 1 2 3' > regex = '^' + '(?:\s+(\d))*' + '$' > match = re.match(regex, line) > print "lastindex is: ",match.lastindex > print "matches: ",match.group(1) > > > Obviously I do not understand how (?:\s+(\d))* works in conjunction with > ^ and $. > > Does anybody know how to transform this regex to get the result I want > to have? > > fs Here are three ways: - If you your strings consist of only white space and single digits as in your example, the simplest way is split(): >>> ' 1 2 3'.split() ['1', '2', '3'] - Otherwise use re.findall: >>> import re >>> digit = re.compile(r'\d') >>> digit.findall('1 ab 34b 6') ['1', '3', '4', '6'] - Finally, for the special case you are searching for single characters (such as digits), perhaps the fastest way is to use string.translate: >>> import string >>> allchars = string.maketrans('','') # 2 empty strings >>> nondigits = allchars.translate(allchars, string.digits) >>> '1 ab 34 6'.translate(allchars, nondigits) '1346' Note that the result is a string of the matched characters, not a list; you can simply turn it to list by list('1346'). Hope this helps, George From sjmachin at lexicon.net Sat Jun 18 04:31:06 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Jun 2005 18:31:06 +1000 Subject: Python documentation problem In-Reply-To: <1119082311.658973.169610@o13g2000cwo.googlegroups.com> References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> <1119082311.658973.169610@o13g2000cwo.googlegroups.com> Message-ID: <42B3DBCA.4010809@lexicon.net> Xah Lee wrote: > i wanted to find out if Python supports eval. e.g. > > somecode='3+4' > print eval(somecode) # prints 7 > > in the 14 hundred pages of python doc, where am i supposed to find this > info? > Option 1: As they say in the classics, "Suck it and see". If you want to find out if something is supported, just type it in: >>> somecode = '3+4' >>> eval(somecode) 7 >>> Option 2: Use help(): >>> help(eval) Help on built-in function eval in module __builtin__: eval(...) eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mappping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. Option 3: If you have Windows, it's easy to find, just click on the Python documentation icon, then select the index tab, and type in "eval" (or whatever). Option 4: On the Python website, click on the docs link, then choose library reference manual, then either go to the built-in functions, or go to the index and select "eval" -- this latter method will take you to this link: http://www.python.org/doc/2.4.1/lib/built-in-funcs.html#l2h-23 HTH, John From max at alcyone.com Thu Jun 30 22:39:56 2005 From: max at alcyone.com (Erik Max Francis) Date: Thu, 30 Jun 2005 19:39:56 -0700 Subject: Favorite non-python language trick? In-Reply-To: <1120184800.499445.240250@f14g2000cwb.googlegroups.com> References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> Message-ID: ncf wrote: > Eh, just figured it'd be worth noting...map, filter, and reduce should > be possible with the extended list syntaxes. Well, filter I know is, > but hte others /should/ be possible. > > filter(lambda: <>, <>) > [some_var for some_var in <> if <>] reduce isn't. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Who needs a dream / Who needs ambition -- The Russian, _Chess_ From lee at example.com Thu Jun 16 16:50:43 2005 From: lee at example.com (Lee Harr) Date: Thu, 16 Jun 2005 20:50:43 GMT Subject: 1980's Home Computer-style Package. References: <11b3b2kn7l1nlf2@corp.supernews.com> Message-ID: On 2005-06-16, Grant Edwards wrote: > On 2005-06-16, Ralph Corderoy wrote: > >>> Wild-ass guess, but you might try googling for "turtle python". >> >> OK, I've done that but it didn't help; it wasn't tied in with >> Turtle graphics, with which I'm familiar. > > Googling for '"python turtle" graphics programming' leads to > > http://mail.python.org/pipermail/edu-sig/2003-January/002657.html > I did a lot of programming in BASIC when I was a kid. I think pygame (and pygsear) can be used in much the same way. There is also livewires and graphics.py floating around out there. I am actually doing some thinking lately about version 2 of pygsear. So if you have thoughts, please think out loud... From rkern at ucsd.edu Wed Jun 8 20:46:56 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 08 Jun 2005 17:46:56 -0700 Subject: Decimal Places Incorrect In-Reply-To: <0E52D69E86D25840AAE3611CB657F9F8365D9D@millenium.equilar.com> References: <0E52D69E86D25840AAE3611CB657F9F8365D9D@millenium.equilar.com> Message-ID: Tom Haddon wrote: > Hi Folks, > > When I run: > > print "%0.2f" % ((16160698368/1024/1024/1024),) > > I get 15.00 > > I should be getting 15.05. Can anyone tell me why I'm not? Integer division does not yield floats. http://docs.python.org/lib/typesnumeric.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gilles.lenfant at nospam.com Mon Jun 13 11:33:55 2005 From: gilles.lenfant at nospam.com (Gilles Lenfant) Date: Mon, 13 Jun 2005 17:33:55 +0200 Subject: [OT ?] (Pythonic) detection word protected files Message-ID: <42ada90e$0$14696$636a15ce@news.free.fr> Hi, This is certainly off topic, but as my problem must have a pythonic answer. I'm building an utility that makes a catalog of M$ word files in a giant directory tree. The password protected files must be marked, and I didn't find how to guess which files are password protected and which ones are not. I can't use the COM interface for this because the utility must run on a Linux Samba server. I didn't find anything satisfying in M$ related sites (like msdn) or forums or google. Any hint ? Many thanks by advance. -- Gilles From shama.bell at gmail.com Wed Jun 1 11:53:03 2005 From: shama.bell at gmail.com (shama.bell at gmail.com) Date: 1 Jun 2005 08:53:03 -0700 Subject: using builtin array Message-ID: <1117641183.057537.118020@z14g2000cwz.googlegroups.com> Is it possible to join/append 2 arrays defined with different typecodes? What typecode should i use to generate the following output. data1 = array('h', '\0', 6) data2 = array('L', '\0', 25) for i in range( 6): data1[0] = 0xFF data2[1] = 0x00 data1[2] = 0x00 data1[3] = 0x00 data1[4] = 0x00 data1[5] = 0x00 for i in range( 2): data2[0] = 0xF0F0F0F0 data2[1] = 0xFFFFFFFF Output should be... (0xFF 0x00 0x00 0x00 0x00 0x00 0xF0F0F0F0 0xFFFFFFFF) Thank You, -SB From alanmk at hotmail.com Wed Jun 29 13:22:10 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Wed, 29 Jun 2005 18:22:10 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> Message-ID: [Mike Holmans] > Some of those sonorous slow talkers from the South, and majestic bass > African-Americans like James Earl Jones or Morgan Freeman, have far > more gravitas than any English accent can: to us, such people sound > monumental. On a related note, have you ever seen any of the original undubbed Star Wars scenes with Darth Vader, with the original voice of the English actor who played him, Dave Prowse (The Green Cross Man, for those who remember ;-) Problem was, Mr. Prowse has a pronounced West Country accent. Imagine it: Darth Vader (in the voice of Farmer Giles): "You are a Rebel, and a Traitor to the Empire". Hilarious :-D, and impossible to take seriously. Thankfully they overdubbed it with James Earl Jones, "Born in Mississippi, raised in Michigan", who produced one of the finest and most memorable voice performances in modern cinema. get-orff-moy-lahnd-ly y'rs -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From hongqn at gmail.com Tue Jun 14 12:59:35 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Wed, 15 Jun 2005 00:59:35 +0800 Subject: collect data using threads In-Reply-To: References: <42aeeef3$1_1@newspeer2.tds.net> <42AF02BD.9080809@bellsouth.net> Message-ID: <42AF0CF7.9060700@gmail.com> James Tanis wrote: > # > > > A class Collector, it spawns several threads to read from serial port. > # > > > Collector.get_data() will get all the data they have read since last > # > > > call. Who can tell me whether my implementation correct? > # > > > > # Here's the original code: > # > # class Collector(object): > # def __init__(self): > # self.data = [] > # spawn_work_bees(callback=self.on_received) > # > # def on_received(self, a_piece_of_data): > # """This callback is executed in work bee threads!""" > # self.data.append(a_piece_of_data) > # > # def get_data(self): > # x = self.data > # self.data = [] > # return x > # > I may be wrong here, but shouldn't you just use a stack, or in other > words, use the list as a stack and just pop the data off the top. I > believe there is a method pop() already supplied for you. Since > you wouldn't require an self.data = [] this should allow you to safely > remove the data you've already seen without accidentally removing data > that may have been added in the mean time. > I am the original poster. I actually had considered Queue and pop() before I wrote the above code. However, because there is a lot of data to get every time I call get_data(), I want a more CPU friendly way to avoid the while-loop and empty checking, and then the above code comes out. But I am not very sure whether it will cause serious problem or not, so I ask here. If anyone can prove it is correct, I'll use it in my program, else I'll go back to the Queue solution. To Jeremy Jones: I am very sorry to take you too much effort on this weird code. I should make it clear that there is only *one* thread (the main thread in my application) calls the get_data() method, periodically, driven by a timer. And for on_received(), there may be up to 16 threads accessing it simultaneously. -- Qiangning Hong ___________________________________________________________ / BOFH Excuse #208: \ | | | Your mail is being routed through Germany ... and they're | \ censoring us. / ----------------------------------------------------------- \ . _ . \ |\_|/__/| / / \/ \ \ /__|O||O|__ \ |/_ \_/\_/ _\ | | | (____) | || \/\___/\__/ // (_/ || | || | ||\ \ //_/ \______// __ || __|| (____(____) From trentm at ActiveState.com Thu Jun 9 11:37:39 2005 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 9 Jun 2005 08:37:39 -0700 Subject: Windows Installer with Debug Dlls and Libs In-Reply-To: <1118325506.087132.64400@g44g2000cwa.googlegroups.com> References: <1118325506.087132.64400@g44g2000cwa.googlegroups.com> Message-ID: <20050609153739.GC22482@ActiveState.com> [DE wrote] > Hello, > > I have a problem with python builds since some time. > > On windows, it is not a good idea to link your debug build to release > builds of libs and dlls. > > But python installer gives you only release builds. > > So I need to build python myself, no problem, but .... > > I have never managed to setup python like the way installer does. (I > guess it does some registry and env var tricks.) For example, > > - it is not possible to install extensions like wxPython, because the > wxPython installer doesn't like my custom installation > - WinCVS never gets my custom python installation > > and so on. > > Can you give me any hints on this nasty problem ? I haven't tested with a debug build of wxPython, but if you use the ActivePython distro you can get a package with the debug DLLs. The main installer: http://ftp.activestate.com/ActivePython/windows/2.4/ActivePython-2.4.1-245-win32-ix86.msi The package of debug bits: http://ftp.activestate.com/ActivePython/etc/ActivePython-2.4.1-245-win32-ix86-debug.zip Cheers, Trent -- Trent Mick TrentM at ActiveState.com From lycka at carmen.se Tue Jun 21 09:02:36 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 21 Jun 2005 15:02:36 +0200 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Benji York wrote: > If by "economy" you mean "optimization", then I would suggest that the > difference would be unnoticeable. If there is a measurable performance gain in skipping the runtime test in "while True", then this is a compiler issue, not a language issue. I don't know anything about the Python compiler internals, but it doesn't seem very hard to identify simple literals following while and if, and to skip the runtime test. (Perhaps it's done already?) I hope the time is over when language designers build ugly quirks into programming language syntaxes to make life a little easier for the compilers. From mandus at gmail.com Thu Jun 30 08:41:30 2005 From: mandus at gmail.com (Mandus) Date: Thu, 30 Jun 2005 12:41:30 +0000 (UTC) Subject: map vs. list-comprehension References: <42c27238$0$26269$626a14ce@news.free.fr> <42c2b7cd$1@nntp0.pdx.net> Message-ID: Wed, 29 Jun 2005 08:33:58 -0700 skrev Scott David Daniels: > Mandus wrote: >> 29 Jun 2005 10:04:40 GMT skrev F. Petitjean: >> >>>Le Wed, 29 Jun 2005 09:46:15 +0000 (UTC), Mandus a ?crit : >>> >>>res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] >> >> seem to be a tad slower than the map, but nothing serious. Guess it's >> the extra zip. > You could try timing it using itertools.izip rather than zip. jepp - faster, but still slower than the map. 1000000 iterations: zip+list-comprehension: 8.1s izip+list-comprehension: 7.5s map: 7.0s -- Mandus - the only mandus around. From silvia.rovati at spaziozerouno.it Thu Jun 16 08:50:15 2005 From: silvia.rovati at spaziozerouno.it (Silvia Rovati) Date: Thu, 16 Jun 2005 14:50:15 +0200 Subject: access properties of parent widget in Tkinter In-Reply-To: <42b17114$1_2@newspeer2.tds.net> Message-ID: Hi. I think that using "backgrounding" doesn't solve your problem. I suppose that you must fork the processes to let them run independently and separately. Best regards Silvia -----Original Message----- From: python-list-bounces+silvia.rovati=spaziozerouno.it at python.org [mailto:python-list-bounces+silvia.rovati=spaziozerouno.it at python.org]On Behalf Of Kent Johnson Sent: giovedi 16 giugno 2005 14:33 To: python-list at python.org Subject: Re: access properties of parent widget in Tkinter William Gill wrote: > I am trying to get & set the properties of a widget's parent widget. > What I have works, but seems like a long way around the block. First I > get the widget name using w.winfo_parent(), then i convert the name to a > reference using nametowidget(). > > self.nametowidget(event.widget.winfo_parent()).hasChanged= True Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? Kent -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Fri Jun 24 07:24:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 07:24:04 -0400 Subject: howto load and unload a module In-Reply-To: References: Message-ID: Guy Robinson wrote: > I have a directory of python scripts that all (should) contain a number > of attributes and methods of the same name. > > I need to import each module, test for these items and unload the > module. I have 2 questions. > > 1.. How do unload an imported module? Why would you want to? Doing what you describe doesn't require that you "unload" a module, unless that means something more to you than, say, merely releasing the memory used by it (which is likely insignificant to you). > 2.. how do I test for the existance of a method in a module without > running it? The object bound to the name used in the import statement is, well, an object, so you can use the usual tests: import mymodule try: mymodule.myfunction except AttributeError: print 'myfunction does not exist' or use getattr(), or some of the introspection features available in the "inspect" module. -Peter From littlejohn.75 at news.free.fr Wed Jun 22 15:08:25 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 22 Jun 2005 19:08:25 GMT Subject: how to use more than 1 __init__ constructor in a class ? References: <42b99d7b$0$21804$626a14ce@news.free.fr> <1119465849.547458.219210@f14g2000cwb.googlegroups.com> Message-ID: <42b9b729$0$32429$626a14ce@news.free.fr> Le 22 Jun 2005 11:44:09 -0700, wittempj at hotmail.com a ?crit : > You also could use a list to represent your data, then you get more > dimensions supported, e.g: > import math > class Point: > def __init__(self, *args): > self.points = list(args) > > def dist(x, y): > if len(x.points) != len(y.points): > raise RuntimeError('dimensions not the same') > d = 0 > for i in range(len(x.points)): > d += (x.points[i] - y.points[i])**2 > return math.sqrt(d) > My rewrite (same idea) :-) class Point(object): def __init__(self, *args): self.coords = list(args) # or even args ? def dist(self, other): d2 = sum([ (c1-c2)*(c1-c2) for c1, c2 in zip(self.coords, other.coords)]) return math.sqrt(d2) From here at there.net Mon Jun 20 13:20:15 2005 From: here at there.net (Drazen Gemic) Date: Mon, 20 Jun 2005 19:20:15 +0200 Subject: login website that using PHP References: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> Message-ID: On Sun, 19 Jun 2005 19:11:38 -0700, frost wrote: > Hi, > > I am trying to login a website that using PHP and javascript. This is > what happend if you browse that website using IE, after you login, you Browser remembers so called HTTP authorization header field. It sends authorization information whenever server requiress authorization by sending corresponding status code and, so called, realm specification. It is beyond the scope of this group and it is well described in HTTP standard and corresponding RFC. DG From metawilm at gmail.com Tue Jun 14 09:16:19 2005 From: metawilm at gmail.com (metawilm at gmail.com) Date: 14 Jun 2005 06:16:19 -0700 Subject: Resume after exception In-Reply-To: References: Message-ID: <1118754979.345360.172090@g43g2000cwa.googlegroups.com> Richard Lewis schreef: > Is it possible to have an 'except' case which passes control back to the > point after the exception occurred? No, not in Python. The concept has however been discussed, under the name "resumable exceptions". http://www.google.com/search?num=100&q=%22resumable+exceptions%22+site%3Apython.org An excellent article about the concept was written by Kent Pitman: "Condition Handling in the Lisp Language Family" http://www.nhplace.com/kent/Papers/Condition-Handling-2001.html Common Lisp is a language that does have the feature. Your code would be written in Lisp like below. When the function notices the file is locked, it will raise an exception. Now imagine there are two ways to solve the problem: 1) read the file anyway, despite the lock; 2) clear the lock and read the file. Or reading the file could be cancelled. These three possible ways to continue the execution are set up by "restart-case". (So this is actually a generalization of your request, in that instead of "just continueing", you can direct the way of continuing) (defun read-unlocked-file (file-name) (with-open-file (f file-name) (when (string= (read-line f) "FILE LOCKED") (let ((user "lock-user") (timestamp 123)) (restart-case (error 'file-locked :name file-name :user user :timestamp timestamp) (continue () :report "Continue reading the locked file.") (clear-lock () :report "Clear the lock and continue reading" (warn "clearing lock...")) (abort () :report "Abort reading the file." (return-from read-unlocked-file))))) (warn "reading remainder of file...") t)) When reading a locked file, you end up with this message: CL-USER(31): (read-unlocked-file "file.txt") Error: File file.txt was locked by lock-user at time 123. [condition type: FILE-LOCKED] Restart actions (select using :continue): 0: Continue reading the locked file. 1: Clear the lock and continue reading 2: Abort reading the file. 3: Return to Top Level (an "abort" restart). 4: Abort entirely from this process. Note the three first "restart actions" are the ones we just defined inside "read-unlocked-file". Let's continue execution by clearing the lock (restart number 1): [1] CL-USER(32): :continue 1 Warning: clearing lock... Warning: reading remainder of file... T If Python had restarts, in your example you would set up code that, depending on whether the user clicked "abort" or "continue" in the dialog, automatically invokes the corresponding restart to either continue or abort the calculation. Restarts are pretty cool. Maybe Stackless Python could support it fairly easily, restarts basically being named continuations? - Willem From tdwdotnet at gmail.com Tue Jun 28 10:59:11 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Tue, 28 Jun 2005 15:59:11 +0100 Subject: Dictionary to tuple In-Reply-To: References: Message-ID: <9afea2ac05062807593ac655f2@mail.gmail.com> On 28 Jun 2005 14:45:19 GMT, Odd-R. wrote: > I have a dictionary, and I want to convert it to a tuple, > that is, I want each key - value pair in the dictionary > to be a tuple in a tuple. > > If this is the dictionary {1:'one',2:'two',3:'three'}, > then I want this to be the resulting tuple: > ((1,'one'),(2,'two'),(3,'three')). > >>> d = {1:'one',2:'two',3:'three'} >>> t = tuple([(k,v) for k,v in d.iteritems()]) >>> t ((1, 'one'), (2, 'two'), (3, 'three')) >>> From CKOSTYN at Indygov.org Wed Jun 15 16:26:48 2005 From: CKOSTYN at Indygov.org (Catherine Kostyn) Date: Wed, 15 Jun 2005 15:26:48 -0500 Subject: Python-list Digest, Vol 21, Issue 234 (Out of the Office June 16) Message-ID: I will be out of the office on June 16, to return on June 17. I will reply to your message at that time. Catherine Kostyn Transportation Planner Indianapolis MPO 200 E. Washington St., Ste. 1821 Indianapolis, IN 46204 (317)327-5142 From No_4 at dsl.pipex.com Tue Jun 28 16:57:21 2005 From: No_4 at dsl.pipex.com (Big and Blue) Date: Tue, 28 Jun 2005 21:57:21 +0100 Subject: turn text lines into a list In-Reply-To: <3ia3mfFk3168U1@individual.net> References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> <3ia3mfFk3168U1@individual.net> Message-ID: Gunnar Hjalmarsson wrote: > >> @corenames=qw( >> rb_basic_islamic >> sq1_pentagonTile >> sq_arc501Tile >> sq_arc503Tile >> ); > > > Impractical to mix code and data, isn't it? Obviously not impractical, given he did it quite easily and succinctly. > chomp( my @corenames = ); > > __DATA__ > rb_basic_islamic > sq1_pentagonTile > sq_arc501Tile > sq_arc503Tile Not so easy when you have multiple variables to set. And the original version was transparent in what it was doing - your version is not. -- Just because I've written it doesn't mean that either you or I have to believe it. From cpunerd4 at gmail.com Fri Jun 17 20:41:36 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 17 Jun 2005 17:41:36 -0700 Subject: extreme newbie Message-ID: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> Hello programmers, I stumbled onto the python language by chance and it looks like a great language. Although from what I've read so far (which isn't much) I've guessed that python is purely an interpreted language unless its compiled into another language (ie. it needs python installed in order to run programs). Is this correct? If it is, I guess my plan of action would be to use python embeded in java applets. Another question I have: Does any one know any really good, really easy to understand python books? I would prefer one that is avalible online for free, but I would also like to know my choices in print. Thanks in advance for any advice, cpunerd4 P.S. I'm 14 and I know HTML, PHP, and I know about many others! From anno4000 at lublin.zrz.tu-berlin.de Wed Jun 1 07:03:48 2005 From: anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) Date: 1 Jun 2005 11:03:48 GMT Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> Message-ID: Tassilo v. Parseval wrote in comp.lang.perl.misc: > Also sprach Dale King: > > > David Formosa (aka ? the Platypus) wrote: > >> On Tue, 24 May 2005 09:16:02 +0200, Tassilo v. Parseval > >> wrote: > >> > >>> [...] I haven't yet come across a language that is both statically and > >>>strongly typed, in the strictest sense of the words. I wonder whether > >>>such a language would be usable at all. > >> > >> > >> Modula2 claims to be both statically typed and strongly typed. And > >> your wonder at its usablity is justified. > > > > I used a variant of Modula-2 and it was one of the best languages I have > > ever used. That strong, static type checking was a very good thing. It > > often took a lot of work to get the code to compile without error. > > Usually those errors were the programmers fault for trying to play fast > > and loose with data. But once you got it to compile it nearly always worked. > > I am only familiar with its successor Modula-3 which, as far as I > understand, is Modula-2 with uppercased keywords and some OO-notion > bolted onto it (I still recall 'BRANDED' references). > > I have to say that doing anything with this language was not exactly a > delight. I've been through Pascal, Modula2 and Oberon, and I agree. These languages had an axe to grind. They were designed (by Niklas Wirth) at a time of a raging discussion whether structured programming (goto-less programming, mostly) is practical. Their goal was to prove that it is, and in doing so the restrictive aspects of the language were probably a bit overdone. In the short run they succeeded. For a number of years, languages of that family were widely used, primarily in educational programming but also in implementing large real-life systems. In the long run, the languages have mostly disappeared from the scene. It has been discovered that "structured programming" is possible in about any language. It turns out that programmers prefer the self-discipline it takes to do that in a liberal language over the enforced discipline exerted by Papa Pascal and his successors. Anno From programmer.py at gmail.com Tue Jun 28 13:57:52 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 28 Jun 2005 12:57:52 -0500 Subject: regulars expressions ? In-Reply-To: <42c18cc9$0$6342$636a15ce@news.free.fr> References: <42c18cc9$0$6342$636a15ce@news.free.fr> Message-ID: Maybe, you need the csv module: import csv mystring = "\"test1, test2\", test, 42" # The one argument to csv.reader is an iterable object # You could use a file here... csv_reader = csv.reader([mystring]) for line in csv_reader: print line ['test1, test2', ' test', ' 42'] hth, jw On 6/28/05, scott wrote: > hi people ! > > > i got some trouble with regular expressions > i need to split a string like this on the ',' character : > > mystring = ""\test1, test2\", test, 42" > > i wanna get something (a list) like this (3 elements) : > "test1, test2" > test > 42 > > but the only thing i get is a list like this (4 elements) : > "test1" > "test2" > test > 42 > > each element is separated by ',' but 1st element which is delimited by > '"' may contain ',' character inside. > > so the regular expression i need is something like : > split each element using ',' delimiter but if ',' delimiter is included > between '"' please do not split > > > 1st question is : does someone has understood the question ? > 2nd question is : does someone has an answer ? > > thanks people > > scott > -- > http://mail.python.org/mailman/listinfo/python-list > From darkpaladin79 at hotmail.com Thu Jun 30 22:42:25 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 30 Jun 2005 22:42:25 -0400 Subject: How to run commands in command line from a script Message-ID: I know there is an easy way to do this, and I just can not remember. I have already searched where I thought the module would be. . . I just want to run some name specific commands. Is this easily possible? Thanks, -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From me at privacy.net Tue Jun 14 08:12:17 2005 From: me at privacy.net (Dan Sommers) Date: 14 Jun 2005 08:12:17 -0400 Subject: sudo open() ? (python newbee question) References: <42aea8cd$0$9912$636a15ce@news.free.fr> Message-ID: On Tue, 14 Jun 2005 11:52:13 +0200, Denis WERNERT wrote: > The script could be SUID Root, and you could use os.setuid immediately > after having performed the task to switch to a non-priviledged > user. May be a big security risk, if someone can alter the script, he > gains root access to the system... I am *not* advocating suid scripts, and *ESPECIALLY NOT* suid Python programs, but if a user can modify an unwriteable suid script owned by root in a an unwriteable directory, then they already have root access to the system (unless there's' a kernel or filesystem bug, in which case all bets are off anyway). Regards, Dan -- Dan Sommers From kasimov at i.com.ua Wed Jun 8 04:33:40 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Wed, 08 Jun 2005 11:33:40 +0300 Subject: different time tuple format In-Reply-To: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> References: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> Message-ID: seems like it is not a platform specific, i think to solve the problem i need put settings in order (in php it is php.ini file) thus i'll have a portable code. i've check the following code on my various servers, and it gives me different results: import time time.tzname time.daylight time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") time.strptime("2005-06-07 15:07:12 EEST", "%Y-%m-%d %H:%M:%S %Z") Python 2.3.3 (#1, Feb 28 2004, 20:35:22) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('EET', 'EEST') >>> time.daylight 1 >>> time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") (2005, 6, 7, 15, 7, 12, 1, 158, -1) >>> time.strptime("2005-06-07 15:07:12 EEST", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 1, 158, 1) Python 2.2.3 (#1, Oct 22 2004, 03:10:44) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.tzname ('EET', 'EEST') >>> time.daylight 1 >>> time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S") (2005, 6, 7, 15, 7, 12, 6, 1, 0) >>> time.strptime("2005-06-07 15:07:12 EEST", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 6, 1, 1) wittempj at hotmail.com wrote: > In your case it is the EEST, as this is the DST timezone (see again: > http://docs.python.org/lib/module-time.html) > > ** martin at ubuntu:~ $ python > ** Python 2.4.1 (#2, Mar 30 2005, 21:51:10) > ** [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 > ** Type "help", "copyright", "credits" or "license" for more > information. > ** >>> import time > ** >>> print time.tzname > ** ('CET', 'CEST') > ** >>> time.strptime("2005-06-07 15:07:12 CET", "%Y-%m-%d %H:%M:%S %Z") > ** (2005, 6, 7, 15, 7, 12, 1, 158, 0) > ** >>> time.strptime("2005-06-07 15:07:12 CEST", "%Y-%m-%d %H:%M:%S > %Z") > ** (2005, 6, 7, 15, 7, 12, 1, 158, 1) > ** >>> > -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From steve at REMOVETHIScyber.com.au Sun Jun 26 00:30:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 14:30:15 +1000 Subject: Favorite non-python language trick? References: <42bdcd82.194023771@news.oz.net> Message-ID: On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote: > On Sun, 26 Jun 2005 04:08:31 +1000, Steven D'Aprano wrote: > >>On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote: >> >>> On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote: >>>> with colour do begin >>>> red := 0; blue := 255; green := 0; >>>> end; >>>> >>>> instead of: >>>> >>>> colour.red := 0; colour.blue := 255; colour.green := 0; >>>> >>>> Okay, so maybe it is more of a feature than a trick, but I miss it and it >>>> would be nice to have in Python. > > How do you like the following? > >>> color = type('',(),{})() # an instance that will accept attributes > >>> vars(color) > {} > > The single line replacing > """ > with colour do begin > red := 0; blue := 255; green := 0; > end; > """ > follows: > >>> vars(color).update(red=0, blue=255, green=0) The point is that a hypothetical "with" block would have to allow arbitrary access to dotted names: getting, setting, deletion, and method calling, not just one very limited form of keyword assignment. I understand how to manipulate __dict__ as an more complicated (dare I say obfuscated?) way of assigning to object attributes. [snip] > We can clear those attributes from the instance dict: >>>> vars(colour).clear() >>>> vars(colour) > {} Which has the unfortunate side effect of also destroying any other instance attributes. >>you might do this: >> >>with myobject: >> # read a class attribute >> print .__class__.myattribute >> # set an instance attribute >> .widget.datapoints[.collector] = .dispatcher(.widget.current_value) >> > > def mywith(o=myobject): > # read a class attribute > print o.__class__.myattribute > # set an instance attribute > o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value) > mywith() [snip] > Is a one-character prefix to the dot objectionable? That's a good workaround, subject to namespace pollution issues, and one that I'm aware of. Although do you really want to be creating a unique function definition every time you want to use the with idiom? I'm not about to stop using Python because of the lack of Pascal-like "with" blocks. It is a nice feature to have, but I'm aware that Guido prefers explicit to implicit and "with" is extremely implicit. -- Steven. From agriff at tin.it Tue Jun 7 18:02:48 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 07 Jun 2005 22:02:48 GMT Subject: programmnig advise needed References: <1118171685.749946.240100@g47g2000cwa.googlegroups.com> Message-ID: <5l5ca1treamnrsee551fajg2uc9ajel57f@4ax.com> On 7 Jun 2005 12:14:45 -0700, mitsura at skynet.be wrote: >I am writing a Python program that needs to read XML files and contruct >a tree object from the XML file (using wxTree). Supposing your XML file has a single top level node (so that it's a legal XML file) then the following code should be able to read it... ######### from elementtree import ElementTree as ET class Node: def __init__(self, xmlnode): self.xmlnode = xmlnode self.children = [] def loadtree(f): root = ET.parse(f).getroot() nodes = {} for x in root: if x.tag.startswith("element"): nodes[x.tag] = Node(x) for x in root.findall("association"): name = x.find("Name").text parent = x.find("Parent").text nodes[parent].children.append(nodes.pop(name)) assert len(nodes) == 1 return nodes.popitem()[1] ########## The idea is to create a node with an empty list of logical children and then for every association removing the child node from the global pool (a dict indexed by node name) to place it in its parent. I assumed that the nodes are in random order, but that the associations are sorted bottom-up in the tree. If this is not the case then you should keep TWO dicts, removing from only one of them the children when you process an association, and looking up the parent in the *other* dict that is not changed during processing of associations. The dict from who you are removing the children will allow you to detect logical errors in the file (i.e. a node having two parents - you won't find that node in the dict the second time - and absence of a single root - you won't end up with a single element in the dict after processing all associations -). HTH Andrea From steve.horsley at gmail.com Sun Jun 5 13:00:08 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Sun, 05 Jun 2005 18:00:08 +0100 Subject: maybe a bug in python In-Reply-To: References: Message-ID: flyaflya wrote: > > >>> a = {1: ("a")} > >>> a[1] > 'a' > why not ('a')? when > >>> a = {1: ((("a")))} > >>> a[1] > 'a' > the result is 'a' too,not ((("a"))).but when use["a"] or ("a","b"),the > tuple is longer than 1, it's no problem. > > > To define a tuple literal with one member, you must place a comma after the first element like this: a = {1: ("a",)} I read this somewhere in the python docs, so I know its there somewhere. The comma eliminates ambiguity as to the meaning of the brackets, which without the comma are simply enclosing and precedence controlling brackets. Steve From negroup at gmail.com Thu Jun 30 06:01:18 2005 From: negroup at gmail.com (Negroup) Date: 30 Jun 2005 03:01:18 -0700 Subject: Add methods to string objects. Message-ID: <2fdabf19.0506300201.5fb56b59@posting.google.com> Hi all. I'm writing a simple Python module containing functions to process strings in various ways. Actually it works importing the module that contains the function I'm interested in, and calling my_module.my_function('mystring'). I was just asking if it is possible to "extend" string objects' behaviour so that it becomes possible to invoke something like 'anystring'.my_method(). 1) does the latter approach bring some advantages? 2) how is it possible to achieve this goal? Any pointer will be appreciated, thanks. From gsakkis at rutgers.edu Sun Jun 26 17:17:35 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 26 Jun 2005 14:17:35 -0700 Subject: unittest: collecting tests from many modules? References: <1118588778.234523.112910@g14g2000cwa.googlegroups.com> <42bf093c.274849712@news.oz.net> Message-ID: <1119820655.773022.98760@g14g2000cwa.googlegroups.com> "Bengt Richter" wrote: > On 12 Jun 2005 08:06:18 -0700, "George Sakkis" wrote: > > >I had written a script to do something close to this; currently it > >doesn't do any kind of aggregation, but it should be easy to extend it > >as you like. What I don't like is the way it currently works: it > >replaces sys.modules['__main__'] for each unit test and then it > >execfile()s it, which seems like a hack. I didn't look into unittest's > >internals in case there is a more elegant way around this; if there > >isn't, a future version of unittest should address the automatic > >aggregation of tests, as py.test does already. > > > I think if you execfile a script and supply the global dict initialized > to {'__name__':'__main__'} then I think that will satisfy the if __name__ ... condition > and the whole thing will run as if executed interactively from the command line. Yes, execfile is called with {'__name__':'__main__'} for globals but that's not enough because __main__ is already bound to the test.py script, not the tested module. Even worse, after each test, sys.modules['__main__'] seems to have to be reset to the original __main__; otherwise os (and I guess other globals) is bound to None ! I'm not sure if this is normal or I missed something basic. Regards, George PS: I reposted the script at http://rafb.net/paste/results/3f1PIZ70.html. From peter at engcorp.com Tue Jun 28 14:45:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Jun 2005 14:45:14 -0400 Subject: whois like functionality on Windows? In-Reply-To: References: Message-ID: <342dnX3zuo5XB1zfRVn-pg@powergate.ca> Gerrit Muller wrote: > I am migrating a website from a UNIX based machine to an Windows > machine. In the logfiles I got from the old machine I mostly got domain > names and sometimes only IP addresses. The Windows machine seems to > produce only IP addresses. > > Somehow I cannot find a windows solution to translate an IP address back > into a domain-name. Searching with Google shows that more people have > been wrestling with this problem. > > I did find working whois scripts, but unfortunately: [snip] Part of your problem is looking for the wrong thing. You are looking for the capability provided by "domain name servers" (DNSes), not "whois" servers. But Thomas has just given you the solution... -Peter From peter at engcorp.com Mon Jun 13 12:48:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Jun 2005 12:48:50 -0400 Subject: string formatting using the % operator In-Reply-To: References: Message-ID: Dan Sommers wrote: > Let the DB-API do more work for you: > > cursor = connection.cursor( ) > sql = """SELECT column2, columns3 FROM table WHERE name LIKE %s""" > values = ('%%%s%%' % searchterm,) # note that this is a tuple It looks like this might be a rare case where not using the % operator might make it easier to see what's going on: values = ('%' + searchterm + '%',) -Peter From peter at engcorp.com Mon Jun 20 11:27:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Jun 2005 11:27:30 -0400 Subject: Couple functions I need, assuming they exist? In-Reply-To: References: Message-ID: Charles Krug wrote: > First, I'm reading that aString.split() is depreciated. What's the > current best practice for this? > > Or am I mistaking that: > > myWords = split(aString, aChar) > is depreciated but If you mean "import string; string.split(aString, aChar)" then yes, it's deprecated (not "depreciated", by the way). > myWords = aString.split(aChgar) > is not? Correct, this is perfectly acceptable. > Second question, I've written a script that generates a LaTeX source > containing randomly generated arithmetic problems of various types. > > The target of the problems (my daughter) would prefer that the thousands > be delimited. Is there a string function that does this? You refer to something like putting a comma between groups of three digits, as in 1,000? This is locale-specific, and there's a "locale" module that should have what you need. -Peter From cam.ac.uk at mh391.invalid Wed Jun 29 04:15:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 29 Jun 2005 09:15:45 +0100 Subject: strange __call__ In-Reply-To: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> Message-ID: Rahul wrote: > Consider the following: > def a(x): > return x+1 > > def b(f): > def g(*args,**kwargs): > for arg in args: > print arg > return f(*args,**kwargs) > return g > > a.__call__ = b(a.__call__) > > now calling a(1) and a.__call__(1) yield 2 different results!! > i.e. for functions a(1) doesnt seem to be translated to a.__call__ if > you assign a new value to a.__call__? I don't know why this happens, but setting the __call__ attribute of a is a pretty strange thing to do. Why not just set a instead? The original function a(x) will still be stored as a closure in what is returned from b(). If this is of purely academic interest then the answer is I don't know. :) -- Michael Hoffman From adam1800uk at yahoo.co.uk Mon Jun 6 11:11:07 2005 From: adam1800uk at yahoo.co.uk (Adam Munoz Lopez) Date: Mon, 6 Jun 2005 16:11:07 +0100 (BST) Subject: Lost in the inheritance tree... Message-ID: <20050606151107.70037.qmail@web25010.mail.ukl.yahoo.com> Can anyone help with this code... I have infinite recursion but since I'm pretty new to Python (and programming in general) I can't find where I did the mistake. Thanks a lot in advance. Adam ************************************************* import Tkinter class RootFrame(Tkinter.Frame): def __init__(self,parent=None,myHeight=600,myWidth=800,myBd=3,\ myRelief=Tkinter.RIDGE): Tkinter.Frame.__init__\ (self,parent,height=myHeight,width=myWidth,bd=myBd,\ relief=myRelief) self.grid() self.grid_propagate(0) self.createFrames() self.showMsg() def showMsg(self): msg=Tkinter.Label(textFrame,text="Are you thinking of an animal?") msg.grid() def createFrames(self): textFrame=TextFrame(self,300,600) textFrame.grid() textFrame.grid_propagate(0) def createButtons(self): yesButton=Tkinter.Button(self,text="Yes") yesButton.grid(row=1,sticky=Tkinter.E) noButton=Tkinter.Button(self,text="No") noButton.grid(row=1,sticky=Tkinter.W) class TextFrame(RootFrame): def __init__(self,parent,myHeight,myWidth): RootFrame.__init__(self,parent,myHeight,myWidth) rootFrame=RootFrame() rootFrame.mainloop() ___________________________________________________________ Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail http://uk.messenger.yahoo.com From Florian.Lindner at xgm.de Thu Jun 23 15:40:55 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Thu, 23 Jun 2005 21:40:55 +0200 Subject: key - key pairs Message-ID: Hello, is there in python a kind of dictionary that supports key - key pairs? I need a dictionary in which I can access a certain element using two different keys, both unique. For example: I've a dictionary with strings and times. Sometimes I have the string and I want to have the time, other time I've the time and I want the string. It is important that one of the keys supports the min/max builtin function. Thanks, Florian From devlai at gmail.com Tue Jun 28 15:30:53 2005 From: devlai at gmail.com (Devan L) Date: 28 Jun 2005 12:30:53 -0700 Subject: Newbie: Help Figger Out My Problem In-Reply-To: <42c174ab$1@nntp0.pdx.net> References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> <42c174ab$1@nntp0.pdx.net> Message-ID: <1119987053.884256.211190@g49g2000cwa.googlegroups.com> import random flips = 100 results = [random.randint(0,1) for i in range(flips)] heads = results.count(0) tails = results.count(1) print "Heads:%s" % heads print "Tails:%s" % tails I think this is more compact. From ksenia.marasanova at gmail.com Sun Jun 12 10:52:02 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Sun, 12 Jun 2005 16:52:02 +0200 Subject: Code documentation tool similar to what Ruby (on Rails?) uses Message-ID: <130df193050612075277318970@mail.gmail.com> Hi, I wonder if there is a tool for generation Python API documentation that can include source code into HTML output. Example: http://api.rubyonrails.com/ I really like the possibility to click on "show source" link and read the source of the method! AFAIK it is not possible with Epydoc and Pydoc.. but maybe other tools? Thanks! -- Ksenia From b at b.b Tue Jun 7 02:06:58 2005 From: b at b.b (Roose) Date: Tue, 07 Jun 2005 06:06:58 GMT Subject: random module question References: <1118079065.795771.248640@g49g2000cwa.googlegroups.com> Message-ID: <6Qape.881$Z44.439@newssvr13.news.prodigy.com> Raymond Hettinger wrote: > The answer is a qualified Yes. While the core generator (currently Thanks! That is the answer I'm looking for. And to Paul Rubin, it is a good point that Jython might not support it, but at this point it doesn't interest me. The program is only for myself anyway. R From steve at REMOVETHIScyber.com.au Wed Jun 29 10:33:33 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 30 Jun 2005 00:33:33 +1000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: On Tue, 28 Jun 2005 11:27:40 -0700, muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. Many companies hire salespersons from Britain to > represent their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? Which American accent? Texan? Georgian cracker or Maine fisherman? New York taxi driver? Bill Clinton or Jesse Jackson or George W Bush? California Valley girl, Arkansas redneck or boyz from th' hood? Paris Hilton or Queen Latifah? > Be blunt. We Americans need to know. Should we try to change the way we > speak? Are there certain words that sound particularly goofy? Please > help us with your advice on this awkward matter. Speaking as an Australia, the typical "film voice" (eg Harrison Ford, Tom Cruise, etc) doesn't sound unsophisticated. In fact, when we hear it, it doesn't sound like an accent at all, such is the influence of Hollywood. (Which is linguistically impossible, of course, since *every* way of speaking is by definition an accent.) The Hollywood voice is a mixture of West Coast and very light mid-Western. But as for the rest of you, yes, you sound -- strange. It depends on the specific regional accent. At best, just different. At worst, dumber than a box of hammers. Which is of course unfair: there is no connection between accent and intelligence. But by gum, some accents just sound dumber than others. My fiancee, from Ireland, has worked and lived in the USA for half her life, and to her you all sound like Kermit the Frog and Miss Piggy. Lest anyone gets offended, I should point out that every English-speaking country have accents which are considered by others to mark the speaker as a thick yokel. In Ireland, they look down on Kerrymen. In England, even Yorkshiremen look down on Summerset, Devon and Dorset accents. And there is nothing as thick-sounding as a broad Ocker Aussie accent. But don't worry, there is one thing we all agree on throughout the English-speaking world: you Americans don't speak English. There are a few things that you can do to help: Herb starts with H, not E. It isn't "ouse" or "ospital" or "istory". It isn't "erb" either. You just sound like tossers when you try to pronounce herb in the original French. And the same with homage. Taking of herbs, there is no BAY in basil. And oregano sounds like Ray Romano, not oh-reg-ano. And please, fillet of fish only has a silent T if you are speaking French. Aluminium is al-u-min-ium, not alum-i-num. Scientists work in a la-bor-atory, not a lab-rat-ory, even if they have lab rats in the laboratory. Fans of the X-Men movies and comics will remember Professor Charles Xavier. Unless you are Spanish (Kh-avier), the X sounds like a Z: Zaviour. But never never never Xecks-Aviour or Eggs-Savior. Nuclear. Say no more. -- Steven. From grante at visi.com Fri Jun 10 10:07:46 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 10 Jun 2005 14:07:46 -0000 Subject: without shell References: Message-ID: <11aj7lia90g33b5@corp.supernews.com> On 2005-06-12, km wrote: > can any linux command be invoked/executed without using shell (bash)? Yes -- for some values of "linux command". You can execute anything that's not a bash internal or a bash script without using bash. > what abt security concerns? What about them? -- Grant Edwards grante Yow! I'm young... I'm at HEALTHY... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From rschroev_nospam_ml at fastmail.fm Fri Jun 24 05:44:45 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 24 Jun 2005 09:44:45 GMT Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: Joseph Garvin wrote: > As someone who learned C first, when I came to Python everytime I read > about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > getattr/setattr, the % operator, all of this was very different from C. > > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > > Here's my current candidate: > > So the other day I was looking at the language Lua. In Lua, you make a > line a comment with two dashes: > > -- hey, this is a comment. > > And you can do block comments with --[[ and ---]]. > > This syntax lets you do a nifty trick, where you can add or subtract a > third dash to change whether or not code runs: > > So you can change whether or not code is commented out just by adding a > dash. This is much nicer than in C or Python having to get rid of """ or > /* and */. Of course, the IDE can compensate. But it's still neat :) Off topic, but in C or C++ it's easier to do it using #ifdef 1 ... #endif Then you just have to change the 1 into 0 or vice versa. It also prevents problems with nested comments. Back on topic, the lack of such a construct in Python is actually one of the very few things that bother me in the language. There are work-arounds, of course; idle, for example, has a feature that prepends a # to every line in the selection, or removes the # again. But not all editors have such a feature, and even if they have it I still need to select the block of code every time. Not that big a deal though. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rkern at ucsd.edu Thu Jun 30 21:32:15 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 18:32:15 -0700 Subject: map vs. list-comprehension In-Reply-To: References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: Roy Smith wrote: > Terry Hancock wrote: > >>One of the strengths of Python has been that the language itself is >>small (which it shares with C and (if I understand correctly, not being >>a lisp programmer?) Lisp), but with all the syntax enhancements going >>on, Python is getting pretty complicated. I have to wonder if new users >>won't begin to find it just as intimidating as Perl or other big >>languages. > > +1 > > Even some of the relatively recent library enhancements have been kind of > complicated. The logging module, for example, seems way over the top. > > Look at what happened to C when it mutated into C++. In isolation, most of > the features of C++ seem like good ideas. Taken together, it's a huge > hairy mess that most people only understand increasingly larger subsets of. > Fred Brooks called it the second system sy Looks like the PSU got to yoNO CARRIER From newsgroups at jhrothjr.com Wed Jun 15 17:12:29 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 15 Jun 2005 15:12:29 -0600 Subject: __str__ vs __repr__ References: <42b021ba$1@griseus.its.uu.se> Message-ID: <11b16e3mld1s9b7@news.supernews.com> "Jan Danielsson" wrote in message news:42b021ba$1 at griseus.its.uu.se... > Sorry, but I Just Don't Get It. I did search the 'net, I did read the > FAQ, but I'm too dumb to understand. > > As far as I can gather, __str__ is just a representation of the > object. For instance: > > class ServerConnection: > def __str__(self): > buf = "Server: " + self.name + "\n" > buf += "Sent bytes: " + str(self.sentBytes) + "\n" > buf += "Recv bytes: " + str(self.recvBytes) + "\n" > return buf > > However, I don't understand what __repr__ should be. There's a phrase > in the documentation which makes it highly confusing for a beginner like > me: "If at all possible, this should look like a valid Python expression > that could be used to recreate an object with the same value (given an > appropriate environment).". What does that mean? Does it mean that I > should return: > > def __str__(self): > buf = "self.name=" + self.name + "\n" > buf += "self.sentBytes=" + str(self.sentBytes) + "\n" > buf += "self.recvBytes=" + str(self.recvBytes) + "\n" > return buf > > ..or is there some other "valid Python expression" format which I > have yet to encounter? str() should be something that's meaningful to a human being when it's printed or otherwise rendered. repr() should be something that can round trip: that is, if you feed it into eval() it should reproduce the object. You can't always achieve either one, especially with very complex objects, but that's the goal. John Roth From twic at urchin.earth.li Thu Jun 30 13:23:29 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 30 Jun 2005 18:23:29 +0100 Subject: map vs. list-comprehension In-Reply-To: <42c4068c$0$21964$afc38c87@news.optusnet.com.au> References: <42c27238$0$26269$626a14ce@news.free.fr> <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: On Fri, 1 Jul 2005, Mike P. wrote: > "Bj?rn Lindstr?m" wrote in message > news:87irzxtqsp.fsf at lucien.dreaming... >> "F. Petitjean" writes: >> >>> res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] >>> >>> Hoping that zip will not be deprecated. >> >> Nobody has suggested that. The ones that are planned to be removed are >> lambda, reduce, filter and map. Here's GvR's blog posting that explains >> the reasons: >> >> http://www.artima.com/weblogs/viewpost.jsp?thread=98196 > > That really sucks, I wasn't aware of these plans. Ok, I don't use reduce > much, but I use lambda, map and filter all the time. These are some of > the features of Python that I love the best. I can get some pretty > compact and easy to read code with them. Same here. > And no, I'm not a Lisp programmer (never programmed in Lisp). My > background being largely C++, I discovered lambda, apply, map and filter > in Python, although I had seen similar stuff in other functional > languages like Miranda and Haskell. Same here too! > Also, I don't necessarily think list comprehensions are necessarily > easier to read. I don't use them all that much to be honest. And here! However, i also felt that way about generator functions - until the other day, when i realised one was the best solution to a problem i had. That made me realise that the same was probably true of list comprehensions. That said, i do still think that map etc are better than list comps, because they involve less language. Once you have the idea of a function and a list, you can understand map as a function that operates on lists; list comprehensions provide a whole new splodge of arbitrary syntax to learn. I guess you could say the same about lambda, which is really an essential part of the whole map way of life, but i don't think that's fair - list comprehensions are a structure for doing just one thing, whereas lambda is a construct of enormous general power. I'd be happy for the lambda syntax to be tidied up, though - perhaps it could be merged with def? Like: def name(args): # traditional form some_statements return some_expression def name(args): return some_expression # one-line form def name(args): some_statements; return some_expression def name(args) = some_expression # shorthand one-line form Then an anonymous form, which is an expression rather than a statement: def (args): some_statements return some_expression def (args): return some_expression def (args) = some_expression The latter form is like a lambda; i'm not sure how the former forms would work inside enclosing expressions; i think it would look pretty sick: surfaceAreaToVolumeRatios = map(def (radius): area = 4.0 * math.pi * (radius ** 2) volume = 4.0 / 3.0 * math.pi * (radius ** 2) return area / volume , radii) It works, but i admit it's not hugely pretty. But then, i would't advise anyone to actually do this; it's just there for completeness. You might also want to allow: def name(args) = some_statements; some_expression And the anonymous counterpart. But i'm not sure about that one. Multiple expressions inside lambdas would sometimes be useful, but you can get those with the shorthand form. > I think at this stage the Python community and Python programmers would > be better served by building a better, more standardised, cross > platform, more robust, better documented, and more extensive standard > library. I would be happy to contribute in this regard, rather than > having debates about the addition and removal of language features which > don't improve my productivity. Same here. > Sorry, I've probably gone way off topic, and probably stirred up > political issues which I'm not aware of, but, man when I hear stuff like > the proposed removal of reduce, lambda, filter and map, all I see ahead > of me is a waste of time as a programmer. Same here. > Sorry for the OT long rant. Yeah, that was really off-topic for a python newsgroup. You didn't even mention regional accents once! tom -- How did i get here? From sjmachin at lexicon.net Tue Jun 7 16:29:59 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 08 Jun 2005 06:29:59 +1000 Subject: Reading a CSV file into a list of dictionaries In-Reply-To: <42a5fc08$0$302$7a628cd7@news.club-internet.fr> References: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> <42a5fc08$0$302$7a628cd7@news.club-internet.fr> Message-ID: <42A603C7.8000702@lexicon.net> Laurent RAHUEL wrote: > RFQ wrote: > > >>Hi, I'm struggling here to do the following with any success: >> >>I have a comma delimited file where each line in the file is something >>like: >> >>PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... > > > This is NOT a CSV file. A CSV file would be : > > PNumber,Contractor,Architect,... > 2056,XYZ Contracting,ABC Architects,... > CSV is an acronym for "Comma-Separated Values". It does not imply anything about the contents of the fields. The OP's file *is* a CSV file. Yes, the contents do represent an unusual application of the CSV format -- however a bus full of parcels instead of people is still a bus. > Then, you could use the built-in CSV module of recent python versions. Python is a case-sensitive language. The name of the module is "csv". The OP could use the csv module with his data. From jan.danielsson at gmail.com Wed Jun 29 14:34:28 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 29 Jun 2005 20:34:28 +0200 Subject: Graphs/statistics using wxPython In-Reply-To: References: <42c2df8b$1@griseus.its.uu.se> Message-ID: <42c2e859$1@griseus.its.uu.se> Robert Kern wrote: >> I wanted to plot some statistics, so I wrote a simple wxPython class >> to do it. Then I realized that I would like to draw bar graphs, so I >> added that too. >> >> Since I'm a complete Python newbie, I haven't done much of it the >> "Python way", I suspect. So, I'm wondering if someone would like to show >> me some of the tricks I should have used. > > > Trick #1: > > import matplotlib Oh. :-) That's a pretty neat trick -- now can you make my embarrassment go away? I did do a quick search to see if anyone had done anything similar; but I guess I wasn't using the right keywords. > ;-) You may point and laugh. Damn, that's a neat toolkit! Thanks for pointing me to it! From skip at pobox.com Wed Jun 1 09:48:58 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Jun 2005 08:48:58 -0500 Subject: Another source of time for the logging package? In-Reply-To: References: Message-ID: <17053.48330.465119.3058@montanaro.dyndns.org> >> Before I get out my scalpel, has anyone found a non-invasive way to >> do this (or already done the surgery and would be willing to share >> it)? Ames> While I'm not sure you would call the following 'non-invasive' Ames> I've used it in a similar situation: Ames> class MyLogRecord(logging.LogRecord): Ames> def __init__(*args, **kwargs): Ames> logging.LogRecord.__init__(self, *args, **kwargs) Ames> self.created = time_warp() # get the time you need ... Excellent! Works like a charm. Thanks, Skip From ny_r_marquez at yahoo.com Mon Jun 13 13:51:48 2005 From: ny_r_marquez at yahoo.com (RM) Date: 13 Jun 2005 10:51:48 -0700 Subject: searching for IDE In-Reply-To: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: <1118685108.920805.25370@g43g2000cwa.googlegroups.com> oops. I didn't see the part about you having tried eric3 already. For your part, you may have missed the very good auto-completion tools available for eric3. Look here: http://www.die-offenbachs.de/detlev/eric3-contrib.html -RM From sjmsoft at hotmail.com Tue Jun 21 08:58:20 2005 From: sjmsoft at hotmail.com (sjmsoft at hotmail.com) Date: 21 Jun 2005 05:58:20 -0700 Subject: Want to learn a language - is Python right? In-Reply-To: <1119278824.847517.294700@g47g2000cwa.googlegroups.com> References: <1119264546.393296.245650@f14g2000cwb.googlegroups.com> <7x3brdjnyt.fsf@ruckus.brouhaha.com> <1119278824.847517.294700@g47g2000cwa.googlegroups.com> Message-ID: <1119358700.737855.20410@z14g2000cwz.googlegroups.com> Aziz McTang wrote: > What I'm looking for is more to learn one good, comprehensive > programming language well than several approximately on an ad hoc > basis. What I also failed to mention is the desire to develop my > presently limited computer skills a lot further. I've programmed in perhaps 20 languages ranging from the famous to the obscure, from 1950s to 1990s design. Python is my favorite. It's a great language for beginners but advanced programmers do not outgrow it. It has powerful features but simple, sensible syntax, so you spend little time fighting the language itself and more time fighting the problem you're trying to solve. It's open source so cost of entry is zero, it runs on many platforms, and it has a active, helpful user community. And coding in Python is fun! Python is a great first lanuguage but keep an open mind to _someday_ learning more languages. As someone else mentioned in this thread, no language is right for all jobs. And knowing languages built on different paradigms (e.g., Prolog, Lisp, assembly languages) provides new insights into the art of programming. Cheers, Steve From volker_grabsch at v.notjusthosting.com Sat Jun 4 14:19:30 2005 From: volker_grabsch at v.notjusthosting.com (Volker Grabsch) Date: Sat, 4 Jun 2005 20:19:30 +0200 Subject: idiom for constructor? References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> <87acm6e9ei.fsf@hector.domek> <8764wue8t0.fsf@hector.domek> <87wtpaayel.fsf@hector.domek> Message-ID: Peter Dembinski wrote: >> This is not a good use case for exec. Use setattr: > > OK, true. > From the other side: what are the usual uses of 'exec'? An interactive Python interpreter. :-) No, seriously: Introspection is always better than exec. It is far less error phrone, especially because you don't need to deal with quoting issues, and because you have an initial syntax check of your Python code which is bypassed when using exec. Similarly, try to avoid system() whenever possible. Greets, -- Volker Grabsch ---<<(())>>--- \frac{\left|\vartheta_0\times\{\ell,\kappa\in\Re\}\right|}{\sqrt [G]{-\Gamma(\alpha)\cdot\mathcal{B}^{\left[\oint\!c_\hbar\right]}}} From http Thu Jun 2 20:50:06 2005 From: http (Paul Rubin) Date: 02 Jun 2005 17:50:06 -0700 Subject: thread vs GC Message-ID: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> Another of those "how can I kill a thread" questions. Let's say I have an app that needs a random prime number for something every now and then, based on user interaction. I have a function makeprime() which creates such a prime, but it's pretty slow, so I don't want to wait for it when the user clicks for a new prime. I want to generate some primes in the background and cache a few of them. Let's say I want to make an iterator object to wrap all this: class primegen: def __init__(self): self.q = Queue.Queue(5) # cache up to 5 primes def background_generator(): while True: self.q.put(makeprime()) # sleeps if 5 primes are already cached threading.Thread(target=background_generator).start() def next(self): return self.q.read() def __iter__(self): return self Now I can make a caching prime stream with g = primegen() and it's all rather elegant. But maybe g will sit in some other object or for some other reason I end up making a bunch of these generators. The generators get cleaned up by GC when they go out of scope, but the threads they spawn are left hanging around. Adding a __del__ method that sets a flag (actually threading.Event) which the background_generator function checks doesn't seem to do the job. Any suggestions for the cleanest way to get rid of the thread? I can think of some awful kludges that I'd rather not resort to. Extra points if it works in both Python and Jython, i.e. it isn't GIL dependent. Thanks for any ideas. From jesper.olsen at gmail.com Tue Jun 7 23:46:54 2005 From: jesper.olsen at gmail.com (Jesper Olsen) Date: 7 Jun 2005 20:46:54 -0700 Subject: import error using BOOST in linux In-Reply-To: <1118176441.221162.298660@o13g2000cwo.googlegroups.com> References: <1118176441.221162.298660@o13g2000cwo.googlegroups.com> Message-ID: <1118202414.577705.241700@g49g2000cwa.googlegroups.com> Have you set LD_LIBRARY_PATH ? -Jesper From donn at u.washington.edu Thu Jun 2 12:04:58 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 02 Jun 2005 09:04:58 -0700 Subject: calling ksh script from python References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: In article <1117722690.144752.82250 at g14g2000cwa.googlegroups.com>, ronan_boisard at yahoo.com wrote: ... > I call it from python like that: > -- begin --- > import commands > commands.getstatusoutput('. toto.env') > -- end --- > > but it always return an error saying: > sh: TOTO_ENV=/home/home: is not an identifier > > doesn anyone know why ? ... > and what about this sh primpt in the error message, can't I use ksh > script ? Yes and no. You can expect system(), popen() et al. to invoke the standard UNIX shell, "sh", so you must supply an expression that will be correctly executed by that shell. That expression can execute a program written in another language - for example, 'ksh toto.env' or just './toto.env' if you have made it executable and it starts with #!/bin/ksh. That's really the best way to invoke a script. Meanwhile, it might be worthwhile to reconsider the use of ksh here, if you have any choice in the matter. Ksh is fine for interactive use, but has some unfortunate flaws as a programming shell, and due to proprietary issues one commonly encounters an alternative implementation that's even worse. On most modern platforms, sh will have a pretty good programming feature set, and will be more reliable (especially if it isn't just ksh by another name.) Donn Cave, donn at u.washington.edu From robin at reportlab.com Wed Jun 15 14:52:39 2005 From: robin at reportlab.com (Robin Becker) Date: Wed, 15 Jun 2005 19:52:39 +0100 Subject: non OO behaviour of file In-Reply-To: <20050615160435.5047.559850221.divmod.quotient.3338@ohm> References: <42B04B78.8000601@chamonix.reportlab.co.uk> <20050615160435.5047.559850221.divmod.quotient.3338@ohm> Message-ID: <42B078F7.6000707@chamonix.reportlab.co.uk> Jp Calderone wrote: > On Wed, 15 Jun 2005 16:38:32 +0100, Robin Becker wrote: > >>Michael Hoffman wrote: >>..... >> >>>Well, you could use python -u: >>> >> >>unfortunately this is in a detached process and I am just reopening stdout >>as an ordinary file so another process can do tail -F on it. I imagine ther >>ought to be an os dependant way to set the file as unbuffered, but can't >>remember/find out what it ought to be. >> > > > open(name, 'w', 0) > > For even more excitment, there's os.open() with the O_DIRECT and O_SYNC flags. You shouldn't need to go to this extreme, though. > > FWIW, I think the behavior of Python wrt file subclasses that override write() is silly, too. > > Jp that's the one I was fumbling towards :) -- Robin Becker From dowskimania at gmail.com Fri Jun 10 10:05:34 2005 From: dowskimania at gmail.com (dowskimania at gmail.com) Date: 10 Jun 2005 07:05:34 -0700 Subject: SMTP Test Rig ( SMTPRIG.PY v1.0 ) References: Message-ID: <1118412334.020699.11310@g49g2000cwa.googlegroups.com> Tim Williams wrote: > After a few posts recently, I have put together an SMTP test rig that will > receive emails and either store them to a file, write them to a console, or > both. Sounds interesting. > Does anyone have any suggestions on where I can get it hosted as a utility > for general public use? You could upload it to the Vaults of Parnassus. http://www.vex.net/parnassus/ > TIA > > Tim Christian http://www.dowski.com From dan at nospam.com Thu Jun 23 11:47:34 2005 From: dan at nospam.com (Dan) Date: Thu, 23 Jun 2005 10:47:34 -0500 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> <3tiue.27$jv6.1568@news.uswest.net> Message-ID: On 6/22/2005 3:08 PM, Cameron Laird wrote: > In article <3tiue.27$jv6.1568 at news.uswest.net>, Dan wrote: > >>On 6/22/2005 1:14 PM, Dave Cook wrote: >> >>>On 2005-06-22, Cameron Laird wrote: >>> >>> >>> >>>>Are you saying that Python-based applications are particularly >>>>vulnerable in this all-too-common scenario? If so, I'm not >>>>getting it; why is the architecture described more fragile than >>>>more traditional Windows-oriented development patterns? If not, >>>>then, ... well then I truly don't get your point. >>> >>> >>>Maybe the point is the downside of depending on installed DLLs rather than >>>shipping your own. >>> >>>Dave Cook >> >>Yes, DLL hell. > > > ? > > OK, I'm with you part of the way. Typical "Access" developers > are *always* involved with DLL hell, right? You're surely not > saying that Python worsens that frustration, are you? No. From mwm at mired.org Sat Jun 11 16:44:26 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 11 Jun 2005 15:44:26 -0500 Subject: Controlling a generator the pythonic way References: Message-ID: <863bro4o9h.fsf@guru.mired.org> Thomas Lotze writes: > A related problem is skipping whitespace. Sometimes you don't care about > whitespace tokens, sometimes you do. Using generators, you can either set > a state variable, say on the object the generator is an attribute of, > before each call that requires a deviation from the default, or you can > have a second generator for filtering the output of the first. Again, both > solutions are ugly (the second more so than the first). One uses > side-effects instead of passing parameters, which is what one really > wants, while the other is dumb and slow (filtering can be done without > taking a second look at things). I wouldn't call the first method ugly; I'd say it's *very* OO. Think of an object instance as a machine. It has various knobs, switches and dials you can use to control it's behavior, and displays you can use to read data from it, or parts of its state . A switch labelled "ignore whitespace" is a perfectly reasonable thing for a tokenizing machine to have. Yes, such a switch gets the desired behavior as a side effect. Then again, a generator that returns tokens has a desired behavior (advancing to the next token) as a side effect(*). If you think about these things as the state of the object, rather than "side effects", it won't seem nearly as ugly. In fact, part of the point of using a class is to encapsulate the state required for some activity in one place. Wanting to do everything via parameters to methods is a very top-down way of looking at the problem. It's not necessarily correct in an OO environment. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mwm at mired.org Mon Jun 13 22:58:04 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 13 Jun 2005 21:58:04 -0500 Subject: recursive import list References: <1118693853.601057.92730@g44g2000cwa.googlegroups.com> Message-ID: <86u0k1y79f.fsf@guru.mired.org> "wittempj at hotmail.com" writes: >> I have a fairly large project going on and would like to figure out >> automatically from the source which files are being imported. > If you use your own import function, like below, you could create a > list of all imported modules. Why not use sys.modules? To answer the question actually asked, check for a __file__ attributes on each module in sys.modules, and print that if it exists. That won't list builtin modules that are imported - but they don't have files to be imported, so I assume that the OP doesn't want them listed. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From calin.hanchevici at gmail.com Mon Jun 13 07:23:03 2005 From: calin.hanchevici at gmail.com (calin.hanchevici at gmail.com) Date: 13 Jun 2005 04:23:03 -0700 Subject: translating C++ exceptions to python Message-ID: <1118661783.702138.128880@g49g2000cwa.googlegroups.com> Hi all, I have a C++ library I call from python. The problem is I have c++ exceptions that i want to be translated to python. I want to be able to do stuff like: try: my_cpp_function() except cpp_exception_1: do_stuff except cpp_exception_2: do_other_stuff any ideas how can i do the translation? Thanks, calin From jstroud at mbi.ucla.edu Mon Jun 20 21:46:37 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 20 Jun 2005 18:46:37 -0700 Subject: Tuple Unpacking in raise In-Reply-To: References: Message-ID: <200506201846.37984.jstroud@mbi.ucla.edu> Thank you Steven and Konstantin, that clears things up. Sometimes I forget how incomplete my Python Essential Reference is. James On Monday 20 June 2005 05:40 pm, Steven Bethard wrote: > Well, it's not a bug, because that's what the documentation says it'll do: > > "The second object is used to determine the exception value: If it is an > instance of the class, the instance becomes the exception value. If the > second object is a tuple, it is used as the argument list for the class > constructor; if it is None, an empty argument list is used, and any > other object is treated as a single argument to the constructor."[1] > > In the example above (as well as almost all code), there's no need to > use the two argument version of raise. You can simply write: > > raise MyErr(sometup) > > If you need the three argument version of raise, I believe you can still > write it as: > > raise MyErr(sometup), None, tb > > Note that Guido has mentioned a few times that in Python 3.0, he wants > tracebacks to be attributes of the Exception objects so that all raise > statements are like the one argument version. > > STeVe > > P.S. If you insist on using the two argument version of raise, you can > do it like this: > > py> class E(Exception): > ... def __init__(self, atup): > ... Exception.__init__(self, "Error with %s-%s" % atup) > ... > py> raise E, ((1, 2),) > Traceback (most recent call last): > File "", line 1, in ? > E: Error with 1-2 > > But that seems a lot less elegant than simply using the one argument > version. > > [1] http://docs.python.org/ref/raise.html -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rochoa at cimex.com.cu Thu Jun 2 19:30:41 2005 From: rochoa at cimex.com.cu (rochoa at cimex.com.cu) Date: Thu, 2 Jun 2005 18:30:41 -0500 Subject: Formatting Time Message-ID: May be >>> sec = 2472 >>> "%d:%02d:%02d" % (int(sec/360), int(sec % 360 /60), int(sec % 60)) '6:05:12' Regards -----Mensaje original----- De: Ognjen Bezanov [mailto:ognjen at mailshack.com] Enviado el: Jueves, 02 de Junio de 2005 03:29 p.m. Para: python-list at python.org Asunto: Formatting Time I never thought id need help with such a thing as time formatting (admittadly i never did it before) but ok, i guess there is a first for everything. I have a float variable representing seconds, and i want to format it like this: 0:00:00 (h:mm:ss) Now search as I might i am finding this quite elusive, i had a look at the time module but that seems overly complicated for this. Anyone got any simple solutions to doing this? cheers! From Florian.Lindner at xgm.de Wed Jun 22 13:47:49 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Wed, 22 Jun 2005 19:47:49 +0200 Subject: timedelta comparision with gmtime() Message-ID: Hello, I want to know if a certain duration is over. I try it like this with timedelta objects: d = datetime.timedelta(minutes = 2) t = time.gmtime() print (t + d < time.gmtime()) gives: TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and 'time.struct_time' How to do that right? Thanks, Florian From amit at digitalpeers.com Thu Jun 30 12:56:20 2005 From: amit at digitalpeers.com (amit) Date: Thu, 30 Jun 2005 18:56:20 +0200 Subject: Multi Threading embedded python Message-ID: <42C42434.1080302@digitalpeers.com> Hello, I am embedding a python script in a C++ application. The script can be called simultaneously from multiple threads. What is the correct way to implement this situation: 1) Have unique python interpreter instantiations ( Py_Initialize() ) for each thread. 2) Have one python interpreter, and implement a lock on it so it can't be called simultaneously by multiple threads? Thanks Amit From jmeile at hotmail.com Fri Jun 10 05:18:25 2005 From: jmeile at hotmail.com (Josef Meile) Date: Fri, 10 Jun 2005 11:18:25 +0200 Subject: how to export data from ZODB to text files In-Reply-To: References: Message-ID: <42A95AE1.2030405@hotmail.com> Hi again, > I thought also about Python script like > > > //connect to database > >>> from ZODB import FileStorage, DB > >>> storage = FileStorage.FileStorage('Data.fs') > >>> db = DB(storage) > >>> conn = db.open() > >>> dbroot = conn.root() I just found an information that may be useful for you: * ZODB for Python Programmers By Michael Pelletier: http://www.informit.com/articles/article.asp?p=23413&rl=1 * A Simple ZODB viewer in wxPython: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409012 The first link contains some useful examples and explanations. The second one could help you to see how your zodb is organized. In the links that Peter post, there is also an useful powerpoint presentation. According to the first link, the ZODB is a persistent dictionary that you can access like: >>> db = DB(storage) >>> connection = db.open() >>> root = connection.root() If I'm not wrong, you could see what objects are in root of your zodb by doing: >>> print root.keys() After that you could get your plone site by doing: >>> ploneSite = root['ploneFolder'] Where if I'm not wrong, "ploneFolder" may be a key in the root dictionary. Then if plone is like CMF, it must have a "portal_catalog" instance in it, so, you can get it by: >>> catalog = getattr(ploneSite,'portal_catalog',None) If at this point catalog = None, then you have to print the objects in the plone site by doing: >>> print ploneSite.objectIds() Once you find the catalog object, you could try the script I post before from the command line. I haven't tested this, but I hope it helps. Regards, Josef Meile From mast_nospam at complement.xxx.at Fri Jun 10 06:09:51 2005 From: mast_nospam at complement.xxx.at (Martin Stettner) Date: Fri, 10 Jun 2005 12:09:51 +0200 Subject: Problem in generated files with makepy and Microsoft ADO References: Message-ID: "Martin Stettner" schrieb im Newsbeitrag news:d8bne1$908$1 at newsreader1.utanet.at... > Hi, > > when trying to generate the wrapper classes for Microsofts ADO Library > [bigsnip...] > Martin Ok, I found some references to similar bugs at http://www.python.org/sf/1163244, http://www.python.org/sf/1089395 and http://www.python.org/sf/1101726. It seems that Python 2.4.1 has problems with mbcs encodint. I'll try to install the actual version of the pywin32 package (build 204) which seems to implement a workaround.cuMartin From rossnixon at gmail.com Sun Jun 12 00:37:01 2005 From: rossnixon at gmail.com (ross) Date: 11 Jun 2005 21:37:01 -0700 Subject: What language to manipulate text files Message-ID: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> I want to do some tricky text file manipulation on many files, but have only a little programming knowledge. What are the ideal languages for the following examples? 1. Starting from a certain folder, look in the subfolders for all filenames matching *FOOD*.txt Any files matching in each folder should be copied to a new subfolder within the current folder called EATING with a new name of *FOOD*COPY.txt 2. Process each file as follows: Here is a simplified example of what I want as input and output. ------------------------------------- input ......................... 'several unknown lines of text file Get apples from apples shop Get oranges from oranges shop Get plums from plums shop Get pears from pears shop Eat from apples, oranges, plums, pears 'whitespace at start of line is unimportant ......................... 'more unknown lines of text file Chapter 1 Several lines of text about apples in here Chapter 2 Several lines of text about oranges in here Chapter 3 Several lines of text about plums in here Chapter 4 Several lines of text about pears in here ------------------------------------- output ......................... 'several unknown lines of text file Get apples from apples shop Get oranges from oranges shop Get plums from plums shop Get pears from pears shop Get bagels from bagels shop 'the Get lines... Get donuts from donuts shop 'can be in any order Eat from apples, bagels, oranges, plums, donuts, pears 'whitespace at start of line is unimportant ......................... 'more unknown lines of text file Chapter 1 Several lines of text about apples in here Chapter 2 Several lines of text about bagels in here Chapter 3 Several lines of text about oranges in here Chapter 4 Several lines of text about plums in here Chapter 5 Several lines of text about donuts in here Chapter 6 Several lines of text about pears in here Summary: I have added two new items to Get; I have put them into the comma-delimited list after searching for a particular fruit to put each one after; The Chapters are renumbered to match their position in the comma-delimited list. The "several lines of text" about each new item can be pulled from a new_foods.txt file (or a bagels.txt and a donuts.txt file). My first objective is to process the files as described. My second objective is to learn the best language for this sort of text manipulation. The language should run on Windows 98, XP and Linux. Would Python be best, or would a macro-scripting thing like AutoHotKey work? I thought about Perl, but think I would learn bad habits and have hard to read code. Thanks, Ross From jelleferinga at gmail.com Thu Jun 23 13:53:18 2005 From: jelleferinga at gmail.com (jelle) Date: 23 Jun 2005 10:53:18 -0700 Subject: connecting to an exsisting COM server Message-ID: <1119549198.624156.171130@f14g2000cwb.googlegroups.com> Hi, I'm using win32com.client.GetObject(Class='Rhino3.Application') to connect to an existing COM server. However when doing so: Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\site-packages\win32com\client\__init__.py", line 80, in GetActiveObject dispatch = pythoncom.GetActiveObject(resultCLSID) com_error: (-2147221021, 'Operation unavailable', None, None) A com_error is raised. This problem has come up a few times on this list, however that didn't help me to find a way of connecting to it. What else could I try? Cheers, Jelle From s_david_rose at hotmail.com Wed Jun 8 19:26:20 2005 From: s_david_rose at hotmail.com (Dave Rose) Date: Wed, 8 Jun 2005 23:26:20 +0000 (UTC) Subject: refactoring, unit testing, ant, etc. Message-ID: Hello all I've been learning Python for the past few months, reading tutorials and postings here. I've bought the personal Komodo then downloaded Eclipse with Pydev. IDLE also is a staple of everyday use. ~10 years ago, I had CS as a minor in college. I learned some C and modula-2 to name the relevent languages. Back then I was compiling on a VAX. Much different than today. I was hoping someone could guide me a bit with current-day practices. I've been pythoning along, but I hear about things I don't know about (re-factoring, unit-testing, debugging, ant build tools) and I don't know how they're applicable to make my life easier. Tutorials didn't shed too much light -- they make it seem to be more work than I need now. To be clear, I've used debuggers in the past, but it seems when I set break- points, the Eclipse just skips merrily past them, or steps at every line, and for wxPython, that's annoying given all the support libraries. I also use wxPython and wxGlade, so those seem to ignore debug mode completely for some reason. Can someone please shed some light onto how I should really use my IDE to make my life more enjoyable? I feel I just don't know how to use the tools that are available, and that's frustrating. Thanks so much! Dave From superprad at gmail.com Tue Jun 14 08:25:46 2005 From: superprad at gmail.com (PyPK) Date: 14 Jun 2005 05:25:46 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> Message-ID: <1118751946.686069.295910@g44g2000cwa.googlegroups.com> I get a decoder error when i do a get pixel on the Image >>> im.getpixel((12,34)) Traceback (most recent call last): File "", line 1, in ? File "Image.py", line 858, in getpixel self.load() File "/usr/local/lib/python2.4/site-packages/PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "Image.py", line 328, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder group4 not available From bokr at oz.net Sat Jun 25 19:08:10 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 25 Jun 2005 23:08:10 GMT Subject: Favorite non-python language trick? References: Message-ID: <42bdcd82.194023771@news.oz.net> On Sun, 26 Jun 2005 04:08:31 +1000, Steven D'Aprano wrote: >On Fri, 24 Jun 2005 15:47:45 -0700, James Stroud wrote: > >> On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote: >>> with colour do begin >>> red := 0; blue := 255; green := 0; >>> end; >>> >>> instead of: >>> >>> colour.red := 0; colour.blue := 255; colour.green := 0; >>> >>> Okay, so maybe it is more of a feature than a trick, but I miss it and it >>> would be nice to have in Python. How do you like the following? >>> color = type('',(),{})() # an instance that will accept attributes >>> vars(color) {} The single line replacing """ with colour do begin red := 0; blue := 255; green := 0; end; """ follows: >>> vars(color).update(red=0, blue=255, green=0) which sets all the attributes: >>> vars(color) {'blue': 255, 'green': 0, 'red': 0} >>> color.blue 255 >>> color.red 0 >>> color.green 0 Of course, I defined a class on the fly above, so I could have given it defaults as class variables (using English spelling ;-) : >>> colour = type('Colour',(),dict(red=0,blue=255,green=0))() # an instance with defaults >>> vars(colour) {} Which don't show up in the instance dict, but do show up as attributes: >>> colour.red 0 >>> colour.green 0 >>> colour.blue 255 Then we can update the instance dict that holds its attributes: >>> vars(colour).update(red=111,green=222,blue=333) And they show up, shadowing the class vars >>> vars(colour) {'blue': 333, 'green': 222, 'red': 111} You can do one attribute this way: >>> vars(colour).update(red='RED') >>> vars(colour) {'blue': 333, 'green': 222, 'red': 'RED'} though this is obviously more concise: >>> colour.green = 'GREEN' >>> vars(colour) {'blue': 333, 'green': 'GREEN', 'red': 'RED'} >>> The class vars are still there, even though we don't have a local name binding for the class: >>> map(vars(type(colour)).__getitem__, 'red green blue'.split()) [0, 0, 255] The instance is separate: >>> vars(colour) {'blue': 333, 'green': 'GREEN', 'red': 'RED'} We can clear those attributes from the instance dict: >>> vars(colour).clear() >>> vars(colour) {} And then they don't shadow the class vars, so getting attributes make the class vars show again: >>> [getattr(colour, c) for c in 'red green blue'.split()] [0, 0, 255] Or: >>> map(colour.__getattribute__, 'red green blue'.split()) [0, 0, 255] Actually, you could make that a few characters shorter using a temporary short name to make a kind of with inside a list comprehension: >>> [[c.red, c.green, c.blue] for c in [colour]][0] [0, 0, 255] Though list comprehensions leak bindings: >>> c <__main__.Colour object at 0x02F8FFCC> Which generator expressions don't: >>> del c >>> list(([c.red, c.green, c.blue] for c in [colour]))[0] [0, 0, 255] >>> c Traceback (most recent call last): File "", line 1, in ? NameError: name 'c' is not defined Or we can get the pairs and build a dict: >>> [(c,getattr(colour, c)) for c in 'red green blue'.split()] [('red', 0), ('green', 0), ('blue', 255)] >>> dict([(c,getattr(colour, c)) for c in 'red green blue'.split()]) {'blue': 255, 'green': 0, 'red': 0} Of course, rgb is usually ordered, so why not >>> colour = type('Colour',(),dict(rgb=(0,255,0)))() # an instance with default rgb >>> vars(colour) {} >>> colour.rgb (0, 255, 0) >>> colour.rgb = 111,222,333 >>> vars(colour) {'rgb': (111, 222, 333)} >>> colour.rgb (111, 222, 333) >>> type(colour).rgb (0, 255, 0) >> >> class color: # americanized >> red = 0 >> blue = 255 >> green = 0 > >The problem is, you have made colour (returning to English spelling >instead of foreign) into a class. If you need two colour variables, you >have to duplicate the code for the class (perhaps only changing the >numeric constants. You can't even make instances from the class, because >they all share the same RGB values, which is pretty useless if they are >meant to represent different colours. > > >> Less typing than pascal. > >You have missed the point. I'm not comparing Python vs Pascal for >creating records representing RBG values. I'm talking about a Pascal >feature that reduced typing by allowing you to use an implicit record. >Here is one possible way you might use such a feature as a Python idiom, >letting "with" specify an implicit object. Instead of doing this: > ># read a class attribute >print myobject.__class__.myattribute ># set an instance attribute >myobject.widget.datapoints[myobject.collector] \ >= myobject.dispatcher(myobject.widget.current_value) > >you might do this: > >with myobject: > # read a class attribute > print .__class__.myattribute > # set an instance attribute > .widget.datapoints[.collector] = .dispatcher(.widget.current_value) > def mywith(o=myobject): # read a class attribute print o.__class__.myattribute # set an instance attribute o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value) mywith() Or if we had a lambda-replacing anonymous def permitting full suites: (def(o=myobject): # read a class attribute print o.__class__.myattribute # set an instance attribute o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value) )() Is a one-character prefix to the dot objectionable? >> Also avoids those stupid little colons. > >Using := and = for assignment and equality is precisely as stupid as using >= and == for assignment and equality. Perhaps less stupid: why do we use >== for equals, but not ++ for plus and -- for minus? > I agree, but I think := would be nice in python for RE-binding an existing binding, wherever it is seen from the local context. Thus you could write def foo(): x:=123 and x = 456 def bar(): x = 789 foo() # finds and rebinds local x print x bar() # -> 123 print x # -> 456 foo() # finds and rebinds the global x print x # -> 123 but del x foo() #-> NameError exception, can't find any x to rebind hm, wandered a bit OT there, ;-/ Regards, Bengt Richter From harold.fellermann at upf.edu Tue Jun 14 14:04:03 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 14 Jun 2005 20:04:03 +0200 Subject: extending Python base class in C In-Reply-To: References: Message-ID: > "harold fellermann" wrote in message > news:mailman.378.1118678951.10512.python-list at python.org... > Hi all, > > I once read that it is possible to use a python base class for a C > extension class. On 14.06.2005, at 09:29, Grigoris Tsolakidis wrote: > There was good article of how to do this on DDJ home page www.ddj.com unfortunately, I could not find it yet. I managed to do the following: I the initmodule function of my extension, I import the module and look for the class I want to use as a base class: PyObject *base_module = PyImport_ImportModule("module_name"); if (!base_module) return; PyObject *base_class = PyMapping_GetItemString( PyModule_GetDict(base_module,"BaseClass") ); if (!base_class) return; This gives me a pointer to the class I want to use as base class. Does anyone know how to assign this to the extension class? I tried to build a tuple (BaseClass,) and assign it (after the respective PyType_Ready call) to CClass.__bases__ like this: PyObject_SetAttrString( &cclassType, "__bases__", Py_BuildValue("(O,)",base_class) ); but this raises a TypeError when executed during import: TypeError: can't set attributes of built-in/extension type 'ext_module.CClass' Any ideas how to proceed? - harold - -- You can imagine the opposite -- Maurizio Nannucci From jepler at unpythonic.net Wed Jun 15 12:37:00 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 15 Jun 2005 11:37:00 -0500 Subject: Programmatic links in a TKinter TextBox In-Reply-To: <1118851935.958133.152710@g43g2000cwa.googlegroups.com> References: <1118851935.958133.152710@g43g2000cwa.googlegroups.com> Message-ID: <20050615163656.GA25149@unpythonic.net> Based on the location where the user clicked, you can find the associated tags. Then you must loop through them to find the one that gives the "href" value. Jeff :r /tmp/link.py import Tkinter app = Tkinter.Tk() text = Tkinter.Text(app) text.pack() def click(event): #this doesn't work print event w = event.widget x, y = event.x, event.y tags = w.tag_names("@%d,%d" % (x, y)) for t in tags: if t.startswith("href:"): print "clicked href %s" % t[5:] break else: print "clicked without href" return "break" def show_hand_cursor(event): event.widget.configure(cursor="hand1") def show_arrow_cursor(event): event.widget.configure(cursor="") # configure text tag text.tag_config("a", foreground="blue", underline=1) text.tag_bind("a", "", show_hand_cursor) text.tag_bind("a", "", show_arrow_cursor) text.tag_bind("a", "", click) text.config(cursor="arrow") #add text text.insert(Tkinter.INSERT, "click here!", "a") text.insert(Tkinter.INSERT, "\n") #add a link with data href = "http://www.example.com" text.insert(Tkinter.END, "this is a ") text.insert(Tkinter.END, "link", ("a", "href:"+href)) app.mainloop() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ggg at zzz.it Wed Jun 1 04:10:32 2005 From: ggg at zzz.it (deelan) Date: Wed, 01 Jun 2005 10:10:32 +0200 Subject: something like CPAN, PPMs? In-Reply-To: References: Message-ID: <1d70n2-g5a.ln1@news.interplanet.it> Maurice LING wrote: > Hi Alex, > > I am actually working on something like that as an academic project. At > this stage, at least for the purpose of my scope, it will not be as > extensive as CPAN but a set of mechanisms for the same effect for Python. don't foget to keep an eye on python's eggs: and related blog posts: HTH. -- @prefix foaf: . <#me> a foaf:Person ; foaf:nick "deelan" ; foaf:weblog . From lkirsh at cs.ubc.ca Fri Jun 24 03:38:48 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Fri, 24 Jun 2005 00:38:48 -0700 Subject: printing indented html code Message-ID: Is there a module or library anyone knows of that will print html code indented? What I'd like would be for a function or class which works like this: htmlIndent(sys.stdout, 'foobar...') and will print somethinkg like this to stdout: foobar ... My current way of doing this kind of stuff is less than ideal and will write such a function if it doesn't exist. Thanks, Lowell From riccardo_cut1 at cut2_sideralis.net Wed Jun 15 07:13:49 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Wed, 15 Jun 2005 13:13:49 +0200 Subject: dynamic References: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> Message-ID: On Wed, 15 Jun 2005 03:12:07 -0700, Michele Simionato wrote: > Having a class that returns instances of some other class is horrible, but > since you asked for it: > > class A(object): pass > class B(object): pass > > class Foo(object): > def __new__(cls, arg): > if arg=="a": > return A() > else: > return B() > > print Foo("a") > print Foo("b") > > Michele Simionato > > P.S. don't do it! Ciao Michele. I have n classes wich share the same interface. I then have a single class which add functionality to all the n classes, using their interface. The only way I see to make this single class inherith from the choosed nx class is this one. If there is a better approach, I can implement it. Thank you for the answer, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From correiajREMOVECAPS at hotmail.com Fri Jun 3 17:54:14 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Fri, 03 Jun 2005 21:54:14 GMT Subject: Pressing A Webpage Button References: <6onne.27139$9A2.4091@edtnps89> <42a0a23b$0$18648$14726298@news.sunsite.dk> Message-ID: "Esben Pedersen" wrote in message news:42a0a23b$0$18648$14726298 at news.sunsite.dk... > How do i know which methods the ie object has? dir(ie) doesn't show > Navigate. For ie object: http://msdn.microsoft.com/workshop/browser/webbrowser/reference/ifaces/IWebBrowser2/IWebBrowser2.asp For document object: http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/obj_document.asp From prabapython at yahoo.co.in Sat Jun 18 02:23:42 2005 From: prabapython at yahoo.co.in (praba kar) Date: Sat, 18 Jun 2005 07:23:42 +0100 (BST) Subject: regarding popen function In-Reply-To: <1119007542.096220.182420@g49g2000cwa.googlegroups.com> Message-ID: <20050618062342.42094.qmail@web8408.mail.in.yahoo.com> Dear All, The following way of popen function usage is wrong or not kindly give me answer regarding this time = os.popen("echo %s | tai64nlocal" % line[2]).read() Actually here I didn't use any file handler and I didn't close file handler. regards Prabahar __________________________________________________________ Free antispam, antivirus and 1GB to save all your messages Only in Yahoo! Mail: http://in.mail.yahoo.com From paschott at no.yahoo.spamm.com Thu Jun 16 16:16:39 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Thu, 16 Jun 2005 20:16:39 GMT Subject: Alternative Ways to install Python 2.4? References: <41F43373.4020003@v.loewis.de> Message-ID: Not sure if this was ever resolved or not, but I've also had issues trying to install from a mapped drive. Once I copied the file locally and installed, it ran smoothly. -Pete Michael Goettsche wrote: > On Monday 24 January 2005 00:29, "Martin v. L?wis" wrote: > > Michael Goettsche wrote: > > > I convinced my CS teacher to use Python in school. We currently have 2.2 > > > installed on a Windows 2000 Terminal server. I asked the system > > > administrator to upgrade to Python 2.4, but he didn't succeed in doing > > > it. He used the microsoft installer package, which according to him > > > crashed when starting. So my question is if there's an alternative way to > > > install it(must be easy). Would it be an option to remove 2.2 first and > > > then try to install 2.4 again? > > > > That would be an option, but I doubt it helps. Please have a look at > > > > http://www.python.org/2.4/bugs.html > > > > Most likely, you need to upgrade Visual Basic on that machine. > > > > Of course, without a precise error description, it is hard to tell. > > > > Regards, > > Martin > > Hi Martin, > > thanks for your answer, I'll let him know! > > Michael From ods at strana.ru Mon Jun 20 03:53:23 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Mon, 20 Jun 2005 11:53:23 +0400 Subject: Embedding Python - How to create a class instance In-Reply-To: <20050619072953.GJ908@zoran.com> References: <20050619072953.GJ908@zoran.com> Message-ID: <20050620115323.6d2e256c@ods.pravda.rfn.ru> On Sun, 19 Jun 2005 10:29:53 +0300 Miki Tebeka wrote: > I'm trying to embed Python in a C application. > What I didn't find is how to create an instance once I have a class object. Class is a callable object. Just call it to create instance. > I'd like to do the equivalent of: > > from a import A > obj = A() > obj.foo(10) > > The following code omits error checking for clarity. > --- a.py --- > class A: > def foo(self, x): > print "A got %d" % x > --- a.py --- > > --- a.c --- > int > main() > { > PyObject *module, *A, *dict, *a, *args; > PyObject *obj; > > Py_Initialize(); > > PyRun_SimpleString("import sys; sys.path.append('.')"); > > module = PyImport_ImportModule("a"); > dict = PyModule_GetDict(module); > A = PyDict_GetItemString(dict, "A"); > /* FIXME: Create obj as instance of A (a = A()) */ > obj = ??? obj = PyObject_CallObject(A, NULL); > > foo = PyObject_GetAttrString(obj, "foo"); > args = Py_BuildValue("(O, i)", obj, 49); > PyObject_CallObject(foo, args); PyObject_CallMethod(obj, "foo", "i", 49); > Py_Finalize(); > > return 0; > } > --- a.c --- -- Denis S. Otkidach http://www.python.ru/ [ru] From passion_to_be_free at hotmail.com Mon Jun 20 09:26:21 2005 From: passion_to_be_free at hotmail.com (passion_to_be_free at hotmail.com) Date: 20 Jun 2005 06:26:21 -0700 Subject: log in to a website In-Reply-To: References: <1118942713.133261.258480@o13g2000cwo.googlegroups.com> Message-ID: <1119273981.843978.220250@o13g2000cwo.googlegroups.com> Works like a gem! Thanks a ton. ClientForm and ClientCookie are great! From scrimp212 at yahoo.com Tue Jun 14 16:39:04 2005 From: scrimp212 at yahoo.com (scrimp) Date: 14 Jun 2005 13:39:04 -0700 Subject: Using PAMIE to upload and download files...is it possible? In-Reply-To: <1118767425.720972.242180@g44g2000cwa.googlegroups.com> References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> <1118256512.379934.292780@z14g2000cwz.googlegroups.com> <1118427453.108199.135860@g14g2000cwa.googlegroups.com> <1118435301.748143.288780@g14g2000cwa.googlegroups.com> <1118759561.268065.320510@g43g2000cwa.googlegroups.com> <1118767425.720972.242180@g44g2000cwa.googlegroups.com> Message-ID: <1118781544.330786.169160@g49g2000cwa.googlegroups.com> Theres one problem with the code that I saw off the bat. My PAMIE script takes IE all the way up the window thats called "File Download". It has 4 buttons Open, Save, Cancel, More Info. The code u gave to me is for the next window I reach AFTER I click manually on Save. It brings up the Save As window. Anyways, I did the PAMIE part manually and the Save As window was open waiting for the SaveAsDocDialog to click Save. It never did, in fact all it did was freeze up python and crash it. So, im still at a stand still here. I know for sure my PAMIE part of the code works. It gets me to where I need to use winGuiAuto. winGuiAuto just sits there and does nothing for me. The window name "File Download" does NOT work for me. I have no idea where or how to find the className of the window. Again, thanx for all the help. Ill keep on trying it though From jesper.olsen at gmail.com Wed Jun 8 10:40:13 2005 From: jesper.olsen at gmail.com (Jesper Olsen) Date: 8 Jun 2005 07:40:13 -0700 Subject: running distutils installer without admin on windows In-Reply-To: <1118241029.833151.252720@g47g2000cwa.googlegroups.com> References: <1118241029.833151.252720@g47g2000cwa.googlegroups.com> Message-ID: <1118241612.999333.224880@f14g2000cwb.googlegroups.com> timothy.williams at nvl.army.mil wrote: > Hello all. > > We don't have admin privs on our Windows boxes, but I'd like to be able > to install a package built using distutils. I was able to install > Python without admin, but when I tried to run the installer for this > package I'm trying to install, I get a message saying that I need admin > privs. > > Is there a way around this? Why can't it just put things in > C:\Python23\Lib\site-packages like a good little installer? > > Do I need to put a service call in to our admins to do this? > > Thanks. You can use the --home switch to specify a local directory to install in, e.g.: % python setup.py install --home=. -Jesper From onurb at xiludom.gro Tue Jun 28 11:01:00 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 28 Jun 2005 17:01:00 +0200 Subject: Modules for inclusion in standard library? In-Reply-To: <1119901432.218536.289030@g47g2000cwa.googlegroups.com> References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> Message-ID: <42c1662d$0$26260$626a14ce@news.free.fr> George Sakkis wrote: > I'd love to see IPython replace the standard interpreter. I dont. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rkern at ucsd.edu Mon Jun 13 17:37:20 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 13 Jun 2005 14:37:20 -0700 Subject: Tiff Image Reader/writer In-Reply-To: <1118697529.173406.134460@g44g2000cwa.googlegroups.com> References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118697529.173406.134460@g44g2000cwa.googlegroups.com> Message-ID: PyPK wrote: > One reason why I don't want to use PIL is it seems very slow for tiff > images of very large sizes(2400x4800). So I am looking for a better > tool than does the right job faster. This isn't fast enough? In [8]: %time img2 = Image.open('foo.tiff') CPU times: user 0.00 s, sys: 0.01 s, total: 0.01 s Wall time: 0.03 In [9]: img2.size Out[9]: (2400, 4800) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mrmaple at gmail.com Sat Jun 11 10:23:51 2005 From: mrmaple at gmail.com (James Carroll) Date: Sat, 11 Jun 2005 10:23:51 -0400 Subject: cgi script runs under Opera, but not firefox In-Reply-To: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> Message-ID: Try View Source under Firefox, you should see everything that you're printing from your CGI on the server. The server side CGI will do the same thing no matter what browser is requesting the page. Next, take that source and paste into into some app that will look for problems like tags that aren't balanced (Dreamweaver is what I'd use.) -Jim On 11 Jun 2005 07:00:39 -0700, nephish at xit.net wrote: > Hey there, > i have a python cgi script that prints out html just fine in the Opera > browser > but doesnt print at all under FireFox. > weird, eh? > i am getting nothing in the apache logs about any error. > perhaps its a firefox issue, but i doubt it. > > any suggestions. simple script here.. > > -- > http://mail.python.org/mailman/listinfo/python-list > > From aetodd at gmail.com Fri Jun 17 15:07:26 2005 From: aetodd at gmail.com (Andrew) Date: 17 Jun 2005 12:07:26 -0700 Subject: Shortcut to initialize variables In-Reply-To: <42b31929$1_2@newspeer2.tds.net> References: <1119032651.912256.319140@o13g2000cwo.googlegroups.com> <42b31929$1_2@newspeer2.tds.net> Message-ID: <1119035246.014322.132790@g47g2000cwa.googlegroups.com> Oops, I probably should have tried searching the list first. My background is strictly academic. I was switching languages so often I never got really familiar with any of them. Maybe C for a while, but I've forgotten alot. I'm hoping python will be the last language I ever need. :) I don't know why I didn't turn to dictionaries first. It does seem to be the obvious solution. I'm writing a program that will take substitution and transposition cipher texts and spit out plain text with no human input. So I suppose I'll have dictionaries of digraphs and trigraphs too; for frequency analysis. Do you think this is to heavy of a project to learn the language? Thanks for the quick feedback From nidoizo at yahoo.com Sun Jun 5 01:32:44 2005 From: nidoizo at yahoo.com (Nicolas Fleury) Date: Sun, 05 Jun 2005 01:32:44 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Andrew Dalke wrote: > Consider the following > > server = open_server_connection() > with abc(server) > with server.lock() > do_something(server) > > server.close() > > it would be translated to > > server = open_server_connection() > with abc(server): > with server.lock() > do_something(server) > server.close() > > when I meant for the first code example to be implemented > like this > > server = open_server_connection() > with abc(server): > with server.lock() > do_something(server) > > server.close() That's an interesting point. But I'm not sure if it is a realistic error. It would be like using a with-statement without knowing what it does. Also, and it seems we agree, these cases are very rare. > > (It should probably use the with-block to handle the server open > and close, but that's due to my lack of imagination in coming up > with a decent example.) > > Because of the implicit indentation it isn't easy to see that > the "server.close()" is in an inner block and not at the outer > one that it appears to be in. To understand the true scoping > a reader would need to scan the code for 'with' lines, rather > than just looking at the layout. But with both syntaxes you only look at the indentation layout, no? If you want to know the "scope" of something as you said, it means you have already scan its "with" statement. You only need after that to look at the indentation layout, as with indentation syntax. It's however less obvious at first look that with-statements implies some scope, but I feel that Python newcomers usually do the opposite error instead, thinking their variables have a defined scope as in some other languages. > A test for how often this is needed would be to look in existing > code for the number of try/finally blocks. I have seen and > written some gnarly deeply stacked blocks but not often - once > a year? > > That's not to say it's a good indicator. A lot of existing code > looks like this I agree. It's hard to find a good indicator. In my case I use both my Python code (with try/finally typically ending a function) and my C++ code (with typically no {} block created for RAII object scope). So, my conclusion, most of the time the indentation will be useless. > What I mean by all of this is that the new PEP may encourage > more people to use indented blocks, in a way that can't be > inferred by simply looking at existing code. In that case > your proposal, or the one written Totally agree. The with-statement will open the door to new programming patterns in Python and it's hard to tell from status quo how much it will be used. Regards, Nicolas From tzot at sil-tec.gr Wed Jun 22 04:30:48 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 22 Jun 2005 11:30:48 +0300 Subject: Dynamic Lists, or...? References: <1118511053.455332.231570@g44g2000cwa.googlegroups.com> <1118649893.551622.289740@g49g2000cwa.googlegroups.com> Message-ID: On 13 Jun 2005 01:04:53 -0700, rumours say that "Raymond Hettinger" might have written: ># Professional driver on a closed course. ># Don't try this at home. > >data = """ >rose, 1, 500 >lilac, 1, 300 >lilly, 1, 400 >rose, 0, 100 >""" > >data = data.replace(', 1, ', ' += ') >data = data.replace(', 0, ', ' -= ') > >class DefaultDict(dict): > def __getitem__(self, key): > return self.get(key, 0) > >d = DefaultDict() >exec data in {}, d >print d.items() For kids trying this at home, note that it only works if the descriptor is a valid Python identifier. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From spiralx at gmail.com Wed Jun 15 05:27:19 2005 From: spiralx at gmail.com (James) Date: Wed, 15 Jun 2005 10:27:19 +0100 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118734620.851366.291360@f14g2000cwb.googlegroups.com> Message-ID: <7ee3dcd805061502273f2c84de@mail.gmail.com> If you're thinking of things like superstrings, loop quantum gravity and other "theories of everything" then your friend has gotten confused somewhere. There is certainly no current experiments which we can do in practise, which is widely acknowledged as a flaw. Lots of physicists are trying to work out low-energy consequences of these theories so that they can be tested, but the maths is extremely hard and the theories aren't even well understood in many cases; but that doesn't mean that they've decided that they'll accept them fully and not bother testing them! On 6/14/05, Andrea Griffini wrote: > On 14 Jun 2005 00:37:00 -0700, "Michele Simionato" > Wow... I always get surprises from physics. For example I > thought that no one could drop confutability requirement > for a theory in an experimental science... I mean that I > always agreed with the logic principle that unless you > tell me an experiment whose result could be a confutation > of your theory or otherwise you're not saying anything > really interesting. > In other words if there is no means by which the theory > could be proved wrong by an experiment then that theory > is just babbling without any added content. > A friend of mine however told me that this principle that > I thought was fundamental for talking about science has > indeed been sacrified to get unification. I was told that > in physics there are current theories for which there > is no hypotetical experiment that could prove them wrong... > (superstrings may be ? it was a name like that but I > don't really remember). From nyamatongwe+thunder at gmail.com Wed Jun 22 21:05:50 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 23 Jun 2005 01:05:50 GMT Subject: Avoiding deadlocks in concurrent programming In-Reply-To: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> Message-ID: Eloff: > So I think you would need multiple locks so clients only acquire what > they need. This would let multiple threads access the data at once. But > now I have to deal with deadlocks since clients will usually acquire a > resource and then block acquiring another. It is very likely that one > client locks A, another locks B, then the guy with B waits for A and > the guy with A waits for B. Worse yet the backup thread will go around > trying to lock everything and will no doubt deadlock everybody. The classic way to avoid lock cycles is to establish an order and require that locks only be acquired in that order. There is an OK introduction to deadlock on the wikipedia: http://en.wikipedia.org/wiki/Deadlock Neil From desertgarden at netscape.com Sun Jun 12 11:44:35 2005 From: desertgarden at netscape.com (Brian) Date: Sun, 12 Jun 2005 15:44:35 GMT Subject: checking for when a file or folder exists, typing problems? In-Reply-To: References: Message-ID: Hi Bryan, Here's a potential idea. Try converting the variable to a string by using the following syntax: thePath = str(thePathArg) This will convert the current variable type to a string, which follows the data type syntax that you have specified at the beginning of your message. Hope this helps, Brian :-) --- Bryan Rasmussen wrote: > Hi > I have a little program that is importing from os.path import exists, join, > isdir, normpath, isfile > at one point in my program I check if a file exists using > if exists("c:\projects"): > > and that works fine. > > If I change it to be > if exists(thepath): > where thepath is a commandline argument it does not work fine. > > Note that the commandline is c:\projects and when I print thepath to check what > is going on it prints > c:\projects > > The only thing I can assume is that there is some sort of typing problem going > on here, but then it should go ahead and give an error then if it's getting > something unexpected obviously. > > Any help on what this error is? > > Thanks > > From listserver at tdw.net Fri Jun 10 08:46:08 2005 From: listserver at tdw.net (Tim Williams) Date: Fri, 10 Jun 2005 13:46:08 +0100 Subject: SMTP Test Rig ( SMTPRIG.PY v1.0 ) Message-ID: <002f01c56dba$601ff960$ccbefea9@twilliams> After a few posts recently, I have put together an SMTP test rig that will receive emails and either store them to a file, write them to a console, or both. Does anyone have any suggestions on where I can get it hosted as a utility for general public use? TIA Tim From ccurvey at gmail.com Tue Jun 7 13:34:28 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 7 Jun 2005 10:34:28 -0700 Subject: separate IE instances? In-Reply-To: References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> Message-ID: <1118165668.863841.291290@z14g2000cwz.googlegroups.com> I would have given up on this a long time ago, but I can create two IEXPLORE processes simultaneously (and get the behavior I want) by just manually launching them from the Start menu. (Of course, that doesn't mean that I can launch them programmatically, but I'm hoping that someone can give me a definitive answer.) From SFarkov at osler.com Mon Jun 27 11:42:33 2005 From: SFarkov at osler.com (Farkov, Serge) Date: Mon, 27 Jun 2005 11:42:33 -0400 Subject: ['ext.IsDOMString', 'ext.SplitQName'] Message-ID: <2A679641220D9244B3ED28E908C07B9EF88752@TSV-EXCHANGE1.ohhllp.com> I am using python 2.4, py2exe 0.5.3, PyXML 0.8.4., and have the same warning. My research shows that this is due to wrong references in PyXML code. For example, I found such definition (and couple more similar): c:\python24\lib\site-packages\_xmlplus\dom\Element.py(27) from ext import SplitQName, IsDOMString Should be changed to "from xml.dom.ext import SplitQName, IsDOMString" to be properly resolved by py2exe To get Adhoc solution for this problem, scan the code and replace all occurrences of "from ext" to "from xml.dom.ext" Regards, Serge Farkov *********************************************************************** This e-mail message is privileged, confidential and subject to copyright. Any unauthorized use or disclosure is prohibited. Le contenu du pr'esent courriel est privil'egi'e, confidentiel et soumis `a des droits d'auteur. Il est interdit de l'utiliser ou de le divulguer sans autorisation. *********************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Mon Jun 20 20:23:27 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 20 Jun 2005 17:23:27 -0700 Subject: Want to learn a language - is Python right? In-Reply-To: <1119278824.847517.294700@g47g2000cwa.googlegroups.com> References: <1119264546.393296.245650@f14g2000cwb.googlegroups.com> <7x3brdjnyt.fsf@ruckus.brouhaha.com> <1119278824.847517.294700@g47g2000cwa.googlegroups.com> Message-ID: <200506201723.27501.jstroud@mbi.ucla.edu> Python will help you as a novice for these reasons: 1. Help you to learn programming concepts and develop good habits. 2. Powerful Standard Library to help you do more advanced things. 3. Smooth, shallow learning curve, e.g. hello world is: print "Hello World" So you can do simple things in python with minimal learning. 4. Excellent, friendly, patient, helpful user base. 5. Code is inherently more maintainable than other languages. 6. comp.lang.python In short, you have come to the right place. I have used many programming languages (C, Java, Fortran, Python, Perl, just to name the more famous ones) and python takes the cake as a general purpose programming language. By the way, ignore any posts talking about speed of execution. This is generally a non-issue for new programmers. If you want your code to run faster, buy a faster computer. James On Monday 20 June 2005 07:47 am, Aziz McTang wrote: > What I'm looking for is more to learn one good, comprehensive > programming language well than several approximately on an ad hoc > basis. What I also failed to mention is the desire to develop my > presently limited computer skills a lot further. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mkb at incubus.de Sun Jun 5 10:30:18 2005 From: mkb at incubus.de (Matthias Buelow) Date: Sun, 05 Jun 2005 16:30:18 +0200 Subject: What are OOP's Jargons and Complexities? In-Reply-To: References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> <3g5tlqFaq4meU1@news.dfncis.de> <927s915p5t5l302u8vcbpmvrokdm64hb39@4ax.com> <3g6n98Faps91U1@news.dfncis.de> Message-ID: <3gggfbFcaca8U1@news.dfncis.de> Andrea Griffini wrote: >>Of course it is a language, just not a standardized one (if you include >>Borland's extensions that make it practical). > > The history of "runtime error 200" and its handling from > borland is a clear example of what I mean with a product. Hmm, I had to google this up... Quite embarrassing, but it's a runtime bug and got nothing to do with the language per se. And it certainly manifests itself after the hey-days of Turbo Pascal (when Borland seems to have lost interest in maintaining it.) mkb. From hongyuan1306 at gmail.com Wed Jun 29 04:08:54 2005 From: hongyuan1306 at gmail.com (Yuan HOng) Date: Wed, 29 Jun 2005 16:08:54 +0800 Subject: Reading output from a child process non-blockingly Message-ID: <91320d22050629010851fb92ea@mail.gmail.com> In my program I have to call an external program and parse its output. For that I use the os.popen2 function, and then read the output stream. But the complexity is that the external program gives back its output in a piecemeal manner, with long delays between the outputs. In the main program I want to therefore read the output in a non-blocking manner, to read as many bytes as the child process is spitting out. The question is, how can I achieve that? I tried use select.select on the output stream returned by os.popen2, but it returns a readable file descriptor only after the whole child process ends. Here is a script simulating the external program: test.py: import sys, time print 'hello\n'*500 sys.stdout.flush() time.sleep(100) print 'world\n'*500 And here is what I am tring to do in the main program to read its output: import os, select cmd = 'python test.py' pin, pout = os.popen2(cmd) while not select.select([pout], [], [], some_timeout)[0]: pass pout.readline() I hope to get the first return very soon, before the external program sleeps, but instead only after the whole program exits do I get any output. Can anyone give me a hint? -- Hong Yuan ????????? www.homemaster.cn From renato.ramonda at gmail.com Sat Jun 18 10:36:13 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Sat, 18 Jun 2005 16:36:13 +0200 Subject: extreme newbie In-Reply-To: <1119102644.048879.258100@g47g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <11b88ier7jled7@corp.supernews.com> <1119102644.048879.258100@g47g2000cwa.googlegroups.com> Message-ID: cpunerd4 ha scritto: > > Another reason I was thinging java was because you can > run it in the browser. Bad idea in 99% of the cases: applets are evil. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From correiajREMOVECAPS at hotmail.com Mon Jun 13 20:58:30 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Tue, 14 Jun 2005 00:58:30 GMT Subject: win32evtlog References: <1118705839.260490.13140@z14g2000cwz.googlegroups.com> <7PydnRpfyLjuuzPfRVn-qA@powergate.ca> <1118710023.098700.252130@g43g2000cwa.googlegroups.com> Message-ID: wrote in message news:1118710023.098700.252130 at g43g2000cwa.googlegroups.com... > Doh! I didn't think to look in the demo directory. Silly me. > http://www.win32com.de/index.php?option=com_content&task=view&id=163&Itemid=189 From rkern at ucsd.edu Mon Jun 6 15:28:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 06 Jun 2005 12:28:51 -0700 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: max wrote: > Perhaps 'attempts' is too strong a word. Maybe 'ends up giving' would > help my argument more. The best example I can come up with at the > moment is programmer A releases a project under the gpl. Programmer B > makes a substantial contribution to the project, which pA reads > through and accepts. Later, pA decides that he would like to release > the project under a more liberal license. To me, whether he legally > can under the gpl is a very murky subject, as pB might not agree, and > pA, having looked through/thought about pB's contribution might have > some trouble proving that he implemented any matching functionality > without referencing pB's earlier contribution, which if he did > reference it(even by memory), would presumably require him to continue > using the gpl. > > I guess my argument is that with multiple contributors, the gpl, in > comparison to say, a BSD style license, grants power to the code. If 3 > people work on a gpl project, they must agree to any changes. If 3 > people work on a BSD style project, they each can do whatever the hell > they like with the code. So, in my opinion, the gpl ends up giving > perhaps not rights, but certainly power, to the actual code base. There's no power being granted to code. All of the power is in the hands of pA and pB. If pA wants a more liberal license to pB's code, then he needs to ask for one. pB can grant that permission (assuming the code is his and not actually pC's). There's nothing special about the GPL in this respect. The same situation works with the BSD license, too, although the BSD license is pretty much rock-bottom in terms of restrictions such that there's almost never a *desire* to ask for more permissions. The code has never been granted any legal powers. It's still just contributors. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From renato.ramonda at gmail.com Thu Jun 9 17:45:19 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Thu, 09 Jun 2005 23:45:19 +0200 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: Thomas Bartkus ha scritto: >>Then download gtk2.6 and glade for windows and then install pygtk and >>code away to your satisfaction! :-D >> > > > I *will* try that. On linux you probably have everything installed or a command away, on windows use this: http://gladewin32.sourceforge.net/ choosing the development package (that includes gtk _and_ glade), plus http://www.pcpm.ucl.ac.be/~gustin/win32_ports/pygtk.html for pygtk. Just choose the right python version, obviously. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From mahongquan at sina.com Fri Jun 10 02:44:13 2005 From: mahongquan at sina.com (mahongquan) Date: Fri, 10 Jun 2005 14:44:13 +0800 Subject: python2.41 distutil setup.py Message-ID: when i install pysqlite in python2.41,it show error below,and i install other package error also ocur, ,but when i copy the cmdline ,it can run without error,who can help me: ''''' running install running build running build_py running build_ext building '_sqlite' extension C:\PROGRA~1\MICROS~2\VC98\BIN\cl.exe /c /nologo /Ox /MD /W3 /GX /DNDEBUG -I..\sq lite -If:\python24\include -If:\python24\PC /Tc_sqlite.c /Fobuild\temp.win32-2.4 \Release\_sqlite.obj _sqlite.c f:\python24\include\pyconfig.h(30) : fatal error C1083: Cannot open include file : 'io.h': No such file or directory error: command 'C:\PROGRA~1\MICROS~2\VC98\BIN\cl.exe' failed with exit status 2 From rune.strand at gmail.com Sat Jun 11 21:26:05 2005 From: rune.strand at gmail.com (Rune Strand) Date: 11 Jun 2005 18:26:05 -0700 Subject: how to operate the excel by python? In-Reply-To: <42AB8CEA.50606@lexicon.net> References: <1118375729.127295.90870@g43g2000cwa.googlegroups.com> <42AB8CEA.50606@lexicon.net> Message-ID: <1118539565.468717.117400@g44g2000cwa.googlegroups.com> John, I wrote a script that autmates the conversion from XLS to CSV. It's easy. But your points are still good. Thanks for making me aware the xlrd module! From http Tue Jun 28 01:36:32 2005 From: http (Paul Rubin) Date: 27 Jun 2005 22:36:32 -0700 Subject: windows/distutils question Message-ID: <7xd5q7xctb.fsf@ruckus.brouhaha.com> I'm trying to package a windows app with distutils (you've heard about it before). The app needs to store some data on disk and apparently the right place to put it is in the "Application Data" directory. The only way I see to find out the name of this directory is the get_special_folder_path function in the postinstallation script (CSIDL_APPDATA). So I call that function and get the directory name, which work ok. There's just one problem: how do I store the name so the application can use it? My obvious idea is to just make an "appdir.py" file containing something like # automatically generated by postinstallation script application_directory = "C:\windows\documents and settings\username\application data" but the point is that I need appdir.py to be stored in the directory where the application code itself lives, i.e. the installation target directory. And I don't see a way to find THAT from the postinstallation script. The postinstallation script seems to run with working directory equal to wherever you launched it from. Note: using os.path.expanduser('~/Application Data') doesn't work because the person may be using a non-English version of Windows and that directory would have a different name. Thanks for any ideas. From tim.golden at viacom-outdoor.co.uk Tue Jun 21 11:22:51 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 21 Jun 2005 16:22:51 +0100 Subject: Running WMI within a Windows service Message-ID: <9A28C052FF32734DACB0A288A3533991EBB918@vogbs009.gb.vo.local> [cameron.mccloud at gmail.com] | Hi, | | When trying to import the WMI module in a Python Windows | Service, I get | the following: | | dynamic module does not define init function (initwmi) | | The WMI version is 0.6. Python 2.4 on Win32, Python Win32 extensions | version 203 This is almost certainly caused by a problem which I consistently fail to mention on my site every time it comes up. In essence, the service you've defined will run in c:\winnt\system32, where there is an file called wmi.dll (which presumably implements the core WMI functionality). Python, looking for a "wmi" to import, finds this -- which could be a Python module -- and tries to import it. And fails. Possible solutions: 1) Within the service code, switch directories to some other directory before importing wmi. 2) Rename wmi.py to something else (pywmi.py?) and import that. 3) Run the service as a named user, which will run within that user's home directory. (Not at all sure about this one; haven't tried it). HTH TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From twic at urchin.earth.li Thu Jun 30 13:29:56 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 30 Jun 2005 18:29:56 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1120141667.753928.40750@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 30 Jun 2005, Benji York wrote: > python-needs-more-duct-tape'ly yours, You're in luck: Python 3000 will replace duck typing with duct taping. tom -- I know you wanna try and get away, but it's the hardest thing you'll ever know From pdemb at gazeta.pl Sun Jun 12 15:38:45 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 12 Jun 2005 21:38:45 +0200 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42ABAB62.4040205@lexicon.net> Message-ID: <87d5qrgybe.fsf@hector.domek> Steven D'Aprano writes: [snap] > new_text = "" > for word in text: > new_text = new_text + process(word) new_text = "".join(map(process, text)) (I couldn't resist) From vibtrip at yahoo.com Thu Jun 16 10:41:43 2005 From: vibtrip at yahoo.com (Vibha Tripathi) Date: Thu, 16 Jun 2005 07:41:43 -0700 (PDT) Subject: Set of Dictionary Message-ID: <20050616144143.26956.qmail@web53905.mail.yahoo.com> Hi Folks, I know sets have been implemented using dictionary but I absolutely need to have a set of dictionaries...any ideas how to do that? Peace. Vibha "Things are only impossible until they are not." __________________________________ Discover Yahoo! Find restaurants, movies, travel and more fun for the weekend. Check it out! http://discover.yahoo.com/weekend.html From jedit at 126.com Wed Jun 1 23:17:26 2005 From: jedit at 126.com (Owen) Date: 1 Jun 2005 20:17:26 -0700 Subject: Rss lib in python? References: <119qdk1cmtmi70@corp.supernews.com> Message-ID: lihui wrote in message news:... > Please use feedparser: > > http://feedparser.org/ > > 2005/6/1, Grant Edwards : > > On 2005-06-01, Owen wrote: > >=20 > > > i want to know some rss library in python.For example, some > > > for rss readers, and some for generator. > >=20 > > http://www.learnwebskills.com/search/main.html > > http://www.learnwebskills.com/search/google.html > >=20 > > Googling for "python rss library" generate a whole page > > full of useful looking stuff: > >=20 > > http://www.google.com/search?q=3Dpython+rss+library > >=20 > > Here's an RSS aggregator written in Python: > >=20 > > http://offog.org/code/rawdog.html > >=20 > > -- > > Grant Edwards grante Yow! HOW could a GLAS= > S > > at be YELLING?? > > visi.com > > -- > > http://mail.python.org/mailman/listinfo/python-list > >=20 > > > --=20 > my gmail:lihuimail(at)gmail.com Thank you for your interest in my question. now i am finding some RSS readers in python(GUI in wxPython). From cjbottaro at alumni.cs.utexas.edu Fri Jun 3 18:40:34 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Fri, 03 Jun 2005 17:40:34 -0500 Subject: how to get name of function from within function? References: Message-ID: Steven Bethard wrote: > Christopher J. Bottaro wrote: >> I want to get the name of the function from within the function. >> Something like: >> >> def myFunc(): >> print __myname__ >> >>>>> myFunc() >> 'myFunc' > > There's not a really good way to do this. Can you give some more detail > on what exactly you're trying to do here? I want to make wrappers around functions but I can't use __getattr__ because the functions are being published as a SOAP service and the SOAP lib I'm using requires a callable object as the argument to the publishing function. Basically I want to wrap every function in try/except automatically. Typically, I suppose people would do that with __getattr__. The way my code is now is that every function (err, method) is enclosed in the exact same try/except error handling code. Everytime I make a new function, I copy/paste that try/catch block. Its ugly, it clutters the code, its prone to error, and if i decide to change the error handling code later, I have to change tons of functions. Actually, I just realized that function call arguments are not passed to __getattr__, so my idea of wrapping function calls that way won't work. Is there something like PHP's __call() method in Python? >> Also, is there a way to turn normal positional args into a tuple without >> using *? Like this: >> >> def f(a, b, c): >> print get_args_as_tuple() >> >>>>>f(1, 2, 3) >> >> (1, 2, 3) > > Um... > > py> def f(a, b, c): > ... print (a, b, c) > ... > py> f(1, 2, 3) > (1, 2, 3) > > ? In your method, if the name and/or number of positional arguments changes, the body of the function must change. I want to avoid that. Thanks. From http Thu Jun 9 18:41:05 2005 From: http (Paul Rubin) Date: 09 Jun 2005 15:41:05 -0700 Subject: Fast text display? References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> <863brr6xiw.fsf@guru.mired.org> Message-ID: <7xzmtzm9vi.fsf@ruckus.brouhaha.com> Mike Meyer writes: > > I mean included with the source distro from python.org. > > Well, it includes Tkinter, but it doesn't include tcl/tk. So you get a > non-functional version of Tkinter if you install from those > sources. Not very useful. OK. But I found on RH9 and FC3, as well as on Windows, that tcl/tk was preinstalled (or included with Python). I didn't find wxwidgets preinstalled on any of those systems. > On FreeBSD, it takes about 5 seconds of my time to install > wxPython from source: > > # cd /usr/ports/x11-toolkits/py-wxPython > # make install What about wxwidgets, which wxpython requires? > Then I can go do something useful while the package system downloads, > compiles and installs all the required software. The installer is going to download more stuff? Yuccch, I'd rather not need a network connection to do an install. Anyway, wxpython built ok on FC3. The problem was wxwidgets, which needed an obsolete version of GTK. I spent at least an hour or two messing around with it before deciding it wasn't worth the hassle. From anna-s at internet.is Mon Jun 20 06:10:39 2005 From: anna-s at internet.is (Anna M.) Date: Mon, 20 Jun 2005 10:10:39 -0000 Subject: global name not defined :$ Message-ID: <20050620101043.174B77AD7E@mail.internet.is> Hi I am trying to write a red-black tree implementation in python. I am very new to python and appologize if my question is terribly stubid. But I ran into some trouble. I have a class and in it there are functions but when I try to run the code I have I just get an error on one of the functions "global name 'balancedFourNode' is not defined" Now of course I realize that I am doing something wrong when defining the function but I just can't seem to find it. Any insight would be greatly appreciated. Another thing, I'll just put in a code snip but I am not sure if it is enough for you guys to see the problem, how ever the class is almost 200 lines so I just didn't want to put it all in the post. Many thanks, Anna M. class node: def __init__(self,g=None): self.data=g self.parent=None self.child=[None,None] # color 0 = black, 1 = red self.color = 0 # NB. changed june 7th # Kids were two and named right and left, respectively # Now a node can have many children # used in 2-3-4 trees and other fun trees. def left(self,x): self.child[0]=x x.parent=self return self def right(self,x): self.child[1]=x x.f=self return self def b(self,l): self.child=l[:] for child in l: child.f=self return self def noOfKids(self): kids = 0 if self.child[0] != None: kids += 1 if self.child[1] != None: kids += 1 return kids def balancedFourNode(self): children = 0 children = noOfKids(self) if children == 2: if child[0].color == 1: red += 1 if child[1].color == 1: red += 1 if red == 2: return 1 else: return 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.hamm at gmail.com Thu Jun 2 09:50:02 2005 From: brian.hamm at gmail.com (brian.hamm at gmail.com) Date: Thu, 02 Jun 2005 08:50:02 -0500 Subject: Python Win32 and Condor Message-ID: <_rKdnRBkh8UXkwLfRVnyvA@giganews.com> Hi. I have a created a python script that opens a program then uses the com package to run a few things and then close. the program. It works perfectly fine when run normally. ie from command prompt or shell. Now I am using the University of Wisconsins queueing program "Condor" to execute this on a number of machines. So far it works perfectly on everyting I have tried. Until today. I tried It on another machine on the network, (same OS, WINXP as the rest) same everything actually but now I get this error. Traceback (most recent call last): File "C:\Condor\execute\dir_3760\test.py", line 39, in ? AB = win32com.client.Dispatch("Broker.Application") File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 79, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147024891, 'Access is denied.', None, None) The funny thing is it works without Condor, just executing regularly with cmd prompt. So I thought it was a condor problem but It runs on all other machines just fine, also a jscript run in the problem machine works with condor. Any help is apreciated. Brian Hamm From harold.fellermann at upf.edu Thu Jun 16 15:19:06 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 16 Jun 2005 21:19:06 +0200 Subject: dir() with string as argument In-Reply-To: <47d5f088340cd.42b193c4@Princeton.EDU> References: <47d5f088340cd.42b193c4@Princeton.EDU> Message-ID: <1d1bb26a6f8fea4d04682e0d89daf9e6@upf.edu> On 16.06.2005, at 20:59, Shankar Iyer (siyer at Princeton.EDU) wrote: > Hi, > > Suppose I have a string, sModuleName, that contains the name of a > module. I now want to see what functions are in that module, but if I > call dir(sModuleName), I instead get the list of operations that can > be done on a string. Is there any way to convert the string into a > format that I could feed to dir to cause the desired effect? I think > I could modify the string a bit and then use the exec command, but I > was advised against that on this board last week. you have to import the module: name = "sys" mod = __import__(name) dir(mod) - harold - -- Bitte verlassen Sie diese Welt so, wie Sie sie vorfinden m?chten. -- From peter at engcorp.com Wed Jun 22 09:23:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Jun 2005 09:23:38 -0400 Subject: A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... In-Reply-To: References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> Message-ID: <7uednX3FwvgU-yTfRVn-pA@powergate.ca> Jack Diederich wrote: > The '.info' domain also defeats > the linux 'whois' command to dig for registrar info. Maybe so, but it's always pretty easy to Google for "whois" plus the domain to find a way of doing it via the web, in this case with http://www.afilias.info/cgi-bin/whois.cgi . (It's registered to something called the Institute of Pamela, which seems to stand for "Peaceful Alliances facilitated by Multilingual, multiracial Education, handicapable outreach and native Language Accessibility". I think this thing really exists, making this spam and not just a farce.) -Peter From cjbottaro at alumni.cs.utexas.edu Sat Jun 4 02:01:15 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Sat, 04 Jun 2005 01:01:15 -0500 Subject: how to get name of function from within function? References: Message-ID: Steven Bethard wrote: [...snip...] > Yes, has's suggestion is probably the right way to go here. I'm still > uncertain as to your exact setup here. Are the functions you need to > wrap in a list you have? Are they imported from another module? A > short clip of your current code and what you want it to do would help. But I want to avoid having to write each wrapper myself. As it is now, when I want to add a public method to my class named myFunc, I first write myFunc which is a wrapper to the implementation: def myFunc(self): try: self.myFuncIMPL() except: # error handling code def myFuncIMPL(self): # do the real stuff here, no need to worry about error handling stuff # cuz its done in the wrapper I guess I'm just lazy, but I don't want to write the wrapper func for each new func I want to add. I want it done automatically. > I don't know. What does PHP's __call() do? I don't know PHP, and it > wasn't in the online manual http://www.php.net/docs.php. http://www.php.net/manual/en/language.oop5.overloading.php I haven't tried it yet, but this is what I would do with __call(): function __call($name, $args) { $name .= 'IMPL'; try { $this->$name($args); } except { # error handling; } } function funcA() { # do something } function funcBIMPL($a, $b) { # do something } So I imagine it would work like this: $obj = new MyClass(); $obj->funcA(); # actually calls funcA because the function # exists in the class $obj->funcB($a, $b); # funcB doesn't exist, so __call() gets called with # args 'funcB', array($a, $b) # so inside __call(), we append 'IMPL' to $name, then invoke # $this->funcBIMPL($a, $b) Using this setup, when I want to add a new function called mySuperFunc(), I merely have to define mySuperFuncIMPL() and magically the wrapper is "made for me"...=) Thanks for the help and ideas! From chad.hughes at pnl.gov Wed Jun 22 13:24:16 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Wed, 22 Jun 2005 10:24:16 -0700 Subject: Database recommendations for Windows app Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B61B4@pnlmse27.pnl.gov> Firebird is cross platform (you would need the classic server version) look at the following post: http://mail.python.org/pipermail/python-list/2005-June/286366.html Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of Will McGugan Sent: Wednesday, June 22, 2005 7:14 AM To: python-list at python.org Subject: Database recommendations for Windows app Hi, I'd like to write a windows app that accesses a locally stored database. There are a number of tables, the largest of which has 455,905 records. Can anyone recommend a database that runs on Windows, is fast / efficient and can be shipped without restrictions or extra downloads? I have googled and found plenty of information on databases, its just that I dont have enough experience with databases to know which one is best for my task! Thanks in advance, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -- http://mail.python.org/mailman/listinfo/python-list From d at e.f Fri Jun 17 16:31:32 2005 From: d at e.f (D H) Date: Fri, 17 Jun 2005 15:31:32 -0500 Subject: Back to the future - python to C++ advice wanted In-Reply-To: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> References: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > During the last 18 months or so I have indulged in the joy of learning > and using python for almost everything, but I may have to go back to > C/C++ at work. Suddenly I found myself transliterating (or translating > at least) common python idioms and patterns, looking for libraries to > replace python's "included batteries" or writing my own from scratch, > (over)using templates in an attempt to mimic duck typing, and so on. > Still, I am not sure if this is a good idea in general since every > language has its own idiosyncrasies, and this is obvious when one sees > python code looking like C or Java. OTOH, bringing python's higher > level of expressiveness to C/C++ might actually be a good thing, > leading to cleaner, safer code. > > So, I wonder what have others who have gone the same path done and > learned in similar situations. How one can avoid the frustration of > having to work with a low level language once he has seen the Light ? That's why so many people have switched to Java or C# (or Python and other langugages of course). You might talk to them about using Python, since Python and C/C++ fit together very nicely (with tools like BOOST, SWIG, Pyrex,...). But me personally I like to avoid C++ altogether when possible, and use Java or C# instead, both of which also can be combined with python or python-like languages such as jython, groovy, or boo. From ladasky at my-deja.com Sat Jun 18 03:26:23 2005 From: ladasky at my-deja.com (ladasky at my-deja.com) Date: 18 Jun 2005 00:26:23 -0700 Subject: Migrating from Windows to OS X Message-ID: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> Hello, fellow programmers! I am sitting in front of a nice new PowerBook portable which has OS 10.4 installed. The Python.org web site says that Apple has shipped OS 10.4 with Python 2.3.5 installed. How exactly do I access this? I have searched through the Applications and Libraries folders. I found the site-packages directory, but nothing other than that. Thanks for your help, John Ladasky From mistobaan at gmail.com Fri Jun 10 08:32:21 2005 From: mistobaan at gmail.com (M1st0) Date: 10 Jun 2005 05:32:21 -0700 Subject: python bytecode grammar Message-ID: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> where I can find the grammar of python bytecode ? ( better if is in BCF ). From eserc at vestel.com.tr Fri Jun 24 07:49:01 2005 From: eserc at vestel.com.tr (=?WINDOWS-1254?Q?Eser_=C7etinkaya?=) Date: Fri, 24 Jun 2005 14:49:01 +0300 Subject: help! Message-ID: <03FB1C8A0749414494FE4726AADD7D4302A8C5B4@vkomexch1.zh.corp> In your documentation, it is written : " os.path.getatime(path) Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. " what do you mean by "access" ? this function gives same outputs with the " os.path.getmtime(path) " What can change an acess time of a path different from modification? Is there any mistakes in the implementation or am i missing some points? M.Eser Cetinkaya -------------- next part -------------- An HTML attachment was scrubbed... URL: From idontneednostinkinid at yahoo.com Sat Jun 18 08:28:02 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 18 Jun 2005 05:28:02 -0700 Subject: MixIn method to call the method it overrides: how? Message-ID: <1119097682.444797.159470@g44g2000cwa.googlegroups.com> I have a MixIn class which defines a method foo(), and is then mixed in with another class by being prepended to that class's __bases__ member, thus overriding that class's definition of foo(). In my application though it is necessary for the MixIn's foo() to call the overridden foo(). How can I do this? My current hack is to do this: def foo(): # MixIn's method orig_bases = self.__class__.__bases__ bases = list(orig_bases) bases.remove(OptEdgeCache) self.__class__.__bases__ = tuple(bases) foo_orig = self.foo self.__class__.__bases__ = orig_bases # other stuff here... Is there a better way? Does the above even work as I think it does? From gsakkis at rutgers.edu Wed Jun 29 09:14:51 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 29 Jun 2005 06:14:51 -0700 Subject: map vs. list-comprehension References: <42c27238$0$26269$626a14ce@news.free.fr> <1120047847.948179.105550@o13g2000cwo.googlegroups.com> Message-ID: <1120050891.463135.18130@g43g2000cwa.googlegroups.com> "Carl Banks" wrote in message > Fear not, people: just as the BDFL does not indiscriminately add > features, also he does not indiscriminately remove them. zip, though > it feels a little exotic, is very useful and serves a purpose that no > language feature serves(*), so rest assured it's not going to > disappear. > > (*) Excepting izip, of course, which is more useful than zip and > probably should also be a builtin. One of the envisioned changes in Python 3000 (http://www.python.org/peps/pep-3000.html) is to return iterators instead of lists in several contexts (e.g. dict.keys(), dict.items()), so perhaps zip will stand for what itertools.izip is today. George From peter at engcorp.com Thu Jun 2 12:55:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 12:55:11 -0400 Subject: PYTHONSTARTUP and the -i command line option In-Reply-To: References: Message-ID: Christopher Wood wrote: > But these two things won't play together, as (by design, it seems) > $PYTHONSTARTUP isn't read when the -i option is used, leaving me with an > unenhanced Python interpreter environment after after script execution. > > Is the any way round this, other than editing all my scripts or manually > loading the .pythonrc.py script in the interpreter? Modifying the contents of your .pythonrc script and therein setting the PYTHONINSPECT environment variable via os.environ comes to mind. -Peter From accenture_travel at syniverse.co.uk Fri Jun 17 08:35:02 2005 From: accenture_travel at syniverse.co.uk (accenture_travel at syniverse.co.uk) Date: Fri, 17 Jun 2005 13:35:02 +0100 Subject: Python & firewall control (Win32) References: Message-ID: <011101c57338$fcb5e8b0$ccbefea9@twilliams> ----- Original Message ----- From: "Tom Anderson" > On Fri, 17 Jun 2005, Tim Williams wrote: > > > On Thu, 16 Jun 2005, Tom Anderson wrote: > > > > > On Thu, 16 Jun 2005, Tim Williams wrote: > > > > > > > Does anyone know of (personal/desktop) firewall that can be > > > > controlled via Python > > > > > > http://wipfw.sourceforge.net/ > > > > Tom, many thanks for that. I'm actually looking for a firewall (packet > > filter) I can control in realtime from a Python application, > > I think you should be able to do that with wipfw ... > > > or even a Win32 equivalent of http://woozle.org/~neale/src/ipqueue/ . > > .... but i'm not sure about that! However, i'm not any sort of firewall or > network expert, so it's possible that ipfw has some way to call out to > external code to get decisions made (a sort of packet version of > procmail's filter system) and that i don't know about it. > > > Though if I can stop & restart ipfw in a fraction of a second from > > within a Python app then the result would be the same I guess. I will > > have a play with it. > > AIUI, you won't be stopping and restarting ipfw - the ipfw command just > modifies the ruleset being used by a continuously-running instance of the > ipfw kernel module or daemon or whatever. How long it takes from starting > the os.system call to the changes taking effect in the firewall, though, i > have no idea - it might not be fast enough for you. I'd be surprised if it > was more than a few hundred milliseconds, though, and really ought to be > much, much faster than that. Thanks Tom Again, I will give it a go and post back with my findings From ndsg_mmii at yahoo.co.uk Wed Jun 22 10:05:37 2005 From: ndsg_mmii at yahoo.co.uk (Nigel Greenwood) Date: 22 Jun 2005 07:05:37 -0700 Subject: sudoku dictionary attack References: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> <1119287197.993599.160240@g47g2000cwa.googlegroups.com> Message-ID: <1119449137.246537.325550@g44g2000cwa.googlegroups.com> Nick Atty wrote: > On-line canal route planner: http://www.canalplan.org.uk So the Travelling Salesman goes by narrow boat these days, does he? Nigel -- ScriptMaster language resources (Chinese/Modern & Classical Greek/IPA/Persian/Russian/Turkish): http://www.elgin.free-online.co.uk From fuzzyman at gmail.com Sun Jun 19 08:54:39 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 19 Jun 2005 05:54:39 -0700 Subject: What platforms have Python Virtual Machines and what version(s) ofPython do they support? In-Reply-To: <1119170474.644310.102840@g49g2000cwa.googlegroups.com> References: <361ab1trhpgra9hig255r7arv68gfpe7lj@4ax.com> <1119170474.644310.102840@g49g2000cwa.googlegroups.com> Message-ID: <1119185679.773426.110520@z14g2000cwz.googlegroups.com> Hmmm... the page is a *bit* out of date (which is to be expected I suppose). There is a port of Python 2.3 for Pocket PC. I think pippy is pretty dead and wasn't that useable. On this newsgroup not long ago someone announced they were working on a new PalmOS port. To the best of my knowledge jython is languishing at Python 2.1. The PSF has funded a push to implement new style classes which will allow it to be brought up to date. I don't know the answer to the other jython questions thougj. Best Regards, Fuzzy http://www.voidspace.org.uk/python From renato.ramonda at gmail.com Sat Jun 11 19:14:06 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Sun, 12 Jun 2005 01:14:06 +0200 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: <2fKqe.16297$TR5.15925@news.edisontel.com> Tim Roberts ha scritto: > Hardly. Sizers have been the primary method of placing multiple controls > in wx for as long as I've been using it, which goes back to 2.3. In fact, > it's hard to create a non-trivial wx app WITHOUT using sizers. All of the > wx GUIs place controls in nested sets of sizers. Dunno... I'll take your word on this. In my experience though wx apps have awfully ugly laid out interfaces, often non resizable ones. Maybe is't only bad luck :-) -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From exarkun at divmod.com Tue Jun 28 10:10:37 2005 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 28 Jun 2005 10:10:37 -0400 Subject: [Twisted-Python] Limiting number of concurrent client connections In-Reply-To: <200506281047.04810.tdickenson@devmail.geminidataloggers.co.uk> Message-ID: <20050628141038.26278.87450687.divmod.quotient.2052@ohm> On Tue, 28 Jun 2005 10:47:04 +0100, Toby Dickenson wrote: >Im finding that Win32Reactor raises an exception on every iteration of the >main loop if I exceed the limit of 64 WaitForMultipleObjects. > >I would prefer to avoid this fairly obvious denial-of-service problem by >limiting the number of concurrent client connections. Is there a standard >solution for this? > Count the number of connections you have accepted. When you get up to 62 or 63 or so, stop accepting new ones. If ServerFactory.buildProtocol() returns None, Twisted immediately closes the accepted connection. If you do this (perhaps in conjunction with calling stopListening() on the port returned by listenXYZ()), you'll never overrun the 64 object limit. Jp From axel at white-eagle.invalid.uk Sat Jun 18 11:26:34 2005 From: axel at white-eagle.invalid.uk (axel at white-eagle.invalid.uk) Date: Sat, 18 Jun 2005 15:26:34 GMT Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> <1119082311.658973.169610@o13g2000cwo.googlegroups.com> Message-ID: In comp.lang.perl.misc Xah Lee wrote: > i wanted to find out if Python supports eval. e.g. > somecode='3+4' > print eval(somecode) # prints 7 > in the 14 hundred pages of python doc, where am i supposed to find this > info? By using the index - it's an alphabetical list of names and topics. Follow-ups set. Axel From deets at web.de Tue Jun 7 17:38:29 2005 From: deets at web.de (Diez B. Roggisch) Date: Tue, 07 Jun 2005 23:38:29 +0200 Subject: time consuming loops over lists In-Reply-To: <292ca1h01uhj0jfsehvs50i0t6vcaaun01@4ax.com> References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> <292ca1h01uhj0jfsehvs50i0t6vcaaun01@4ax.com> Message-ID: > I don't see a "break" so why the "/2" ? also IIUC the That was the assumption of an equal distribution of the data. In O-notationn this would be O(n) of course. Diez From meren at uludag.org.tr Mon Jun 27 08:40:50 2005 From: meren at uludag.org.tr (A. Murat Eren) Date: Mon, 27 Jun 2005 15:40:50 +0300 Subject: Downloading files using URLLib In-Reply-To: <9D1BA87B48D4F440A0D9E371471F45A53263AE@cernxchg21.cern.ch> References: <9D1BA87B48D4F440A0D9E371471F45A53263AE@cernxchg21.cern.ch> Message-ID: <200506271540.56973.meren@uludag.org.tr> Hi, On Monday 27 June 2005 12:10, Oyvind Ostlund wrote: > I have to download a lot of files. And at the moment i am trying with > URLLib. But sometimes it doesn't download the whole file. It looks like it > stops half way through or something. Is it possible to ask for the file > size before you download, and then test afterwards if the whole file was > read? If so please guid me a bit here. You need something like that: import urllib2 URI='http://cekirdek.uludag.org.tr/index.html' file = urllib2.urlopen(URI) headers = file.info() fsize = int(headers['Content-Length']) HTH.. Ciao, -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - A. Murat Eren meren at uludag.org.tr http://cekirdek.uludag.org.tr/~meren/ 0x527D7293, 7BCD A5A1 8101 0F6D 84A4 BD11 FE46 2B92 527D 7293 - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- Alan Cox sounds as if he hasn't followed the development of programming languages and compilers for the last 10 years (exa). - -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From roy at panix.com Thu Jun 16 07:36:18 2005 From: roy at panix.com (Roy Smith) Date: Thu, 16 Jun 2005 07:36:18 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: Andrea Griffini wrote: > That strings in python are immutable it's surely > just a detail, and it's implementation specific, > but this doesn't means it's not something you can > ignore for a while. I disagree. It is indeed something you can ignore for a while. The first program you teach somebody to write is going to be: print "Hello, world" To get that to work, you need to figure out how to run the python interpreter, and how to edit a program source file. You also learn some basic python syntax like how to form strings, that the print statement gives you a carriage return for free, and you don't need a ";" at the end. It would be a mistake to mention now that "Hello, world" is an immutable object. That's just not important at this point in the learning process. Eventually, you're going to have to introduce the concept of immutability. That point may not be much beyond lesson 2 or so, but it doesn't have to be lesson 1. From mwm at mired.org Sat Jun 11 16:20:01 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 11 Jun 2005 15:20:01 -0500 Subject: cgi script runs under Opera, but not firefox References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> <1118501642.065924.83560@z14g2000cwz.googlegroups.com> <1118505371.230328.231880@o13g2000cwo.googlegroups.com> <6d8ma1lvfer5itr6ukomg095uprnp30ujd@4ax.com> <1118516629.651991.134730@g47g2000cwa.googlegroups.com> Message-ID: <867jh04pe6.fsf@guru.mired.org> nephish at xit.net writes: > fixed, thanks for all of your help. > i am pouring over python texts and the problem is > html... duh.... Right. To get HTML that will work in any browser, , you really need to validate your HTML. w3.org provides a public validator at (as well as validators for CSS, RDF, XML Schema and link checking). If you're going to be doing a lot of work with such formats, you probably want to install a validator locally. Lots of options for that, depending on what kind of system you're using. BTW, practical experience is that you write your application to follow the standards, then go back and work around the bugs in various versions of IE. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jeoffwilks at gmail.com Fri Jun 24 12:15:37 2005 From: jeoffwilks at gmail.com (jeoffwilks at gmail.com) Date: 24 Jun 2005 09:15:37 -0700 Subject: Python as client-side browser script language References: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> <7xk6leylhi.fsf@ruckus.brouhaha.com> <3g79esFb0jkrU1@individual.net> Message-ID: <1119629737.630333.15360@g47g2000cwa.googlegroups.com> Sorry to resurrect a slightly older topic, but I want to clarify some points about how the browser DOM and the script language interact. Paul Rubin wrote: > Huh? The language itself has to provide the sandbox. > Remember that scripts have to be able to see > certain DOM elements but not others, and some of them have to be > read-only, etc. Greg Ewing wrote: > If the DOM objects are implemented as built-in Python > types, there shouldn't be any difficulty with that. > Python objects have complete control over which attributes > can be read or written by Python code. In web browsers, Javascript does not provide the sandbox. The browser provides scripts with certain objects like "document" or "window" but these are not native script objects at all. They're wrappers for browser-native objects, usually written in C/C++ and exposed via an ActiveX or XPCOM interface. (IE uses ActiveX, Mozilla uses XPCOM). The interfaces to these browser-native objects enforce the security model by restricting what the scripting language is allowed to do within the browser context. If you attempt any foul play with a browser-native object, it can simply feed an exception back to the script wrapper, and your script code fails. That's the sandbox. Following are some relevant links for those interested in further details: DOM Intro (especially the section, DOM vs Javascript:) "That is to say, [the script is] *written* in JavaScript, but it *uses* the DOM to access the web page and its elements." http://www.mozilla.org/docs/dom/domref/dom_intro.html "Mozilla's DOM is coded almost entirely in C++. ... When, in JavaScript, a client tries to access a DOM object or a DOM method on a DOM object, the JS engine asks XPConnect to search for the relevant C++ method to call." http://www.mozilla.org/docs/dom/mozilla/hacking.html "The DOM makes extensive use of XPCOM. In fact, to do anything with the DOM implementation you need XPCOM." http://www.mozilla.org/docs/dom/mozilla/xpcomintro.html Talking to XPCOM in Python "The techniques for using XPCOM in Python have been borrowed from JavaScript - thus, the model described here should be quite familiar to existing JavaScript XPCOM programmers." http://public.activestate.com/pyxpcom/tutorial.html So in theory you should be able to create a python script interpreter, at least for Mozilla. In practice you'd either need to be an expert with the Mozilla source code, XPCOM, and Python... or you'd find yourself becoming an expert by necessity. --- Incidentally when people don't understand the difference between DOM objects and Javascript objects, they end up with lots of memory leaks: http://jgwebber.blogspot.com/2005_01_01_jgwebber_archive.html From surrender_it at remove-yahoo.it Wed Jun 29 05:31:51 2005 From: surrender_it at remove-yahoo.it (gabriele renzi) Date: Wed, 29 Jun 2005 09:31:51 GMT Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1120023753.231890.182890@g43g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1120023753.231890.182890@g43g2000cwa.googlegroups.com> Message-ID: BORT ha scritto: > All, > > The Forth-Python pull was heading to a conclusion just like "Tastes > Great" vs. "Less Filling" or Ford-Chevy. However, friendly folks at > comp.lang.forth pointed me to Amazon.com and _Mindstorms: Children, > Computers, and Powerful Ideas_ > by Seymour Papert. The book is by Logo's inventor and, according to > the reviews, addresses the larger goal I most want to achieve. I thought you were limiting the choice to python/forth. Logo is a nice dialect of lisp, so I think you're making a good choice ;) But I'd consider Squeak. It is the best educational-but-not-only environment I've seen (which does not mean there are not better, but I've seen quite a bit of them) Squeak not only has programming at the hand but it also provide you with a complete educational system, with music, painting, animations etc. And there is nothing that could get a kid involved like making a rabbit explode. > I now want to read the book. Period. However, my kids both love Legos > which uses a Logo implementation for their robotics toys. I could > probably capture both the 10 yr old AND the 7 yr old if we can spring > for the $200 Lego Mindstorm set. Sort of blows away my specification > of "free," but... > > In my earlier browsing, I eliminated Logo early on, thinking we would > hit its capability ceiling too quickly and then backtrack in order to > make a transition to a "REAL" language. > > uh... I've been browsing on Logo tonight and, even without the Lego > robots, I may go that route. Shoot, I thought Logo was just moving > hokey sprites in increasingly complex patterns until I saw the book > list at: > > http://el.media.mit.edu/logo-foundation/products/books.html > > Hmm... When all is said and done, maybe the choice is kind of like > physical exercise. I can spend weeks choosing the most effective work > out and diet combination. But, until I cut back on biggie size grease > brugers with double shakes and get off of the couch every now and then, > the choice of workout is moot. In fact, one I use is better than the > "best" that I don't use. > > Gentle folk of comp.lang.python, I heartily thank you all for your > input. I think I'm taking the boys through the door marked "Logo." We > may be back this way, though. We will likely need MORE in the nebulous > future. I am impressed with the outpouring of support here! > > Thanks to all! > From mblume at socha.net Tue Jun 21 11:09:36 2005 From: mblume at socha.net (Martin Blume) Date: Tue, 21 Jun 2005 17:09:36 +0200 Subject: eval() in python References: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> Message-ID: <42b82db0$0$1151$5402220f@news.sunrise.ch> "Xah Lee" schrieb > > perhaps i'm tired, but why can't i run: > > t='m=3' > print eval(t) > Perhaps you didn't read the documentation? :-) Perhaps you didn't try hard enough? C:\WINNT>c:\programme\python\python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> t='m=3' >>> m Traceback (most recent call last): File "", line 1, in ? NameError: name 'm' is not defined >>> exec(t) >>> m 3 >>> HTH Martin From phillip.watts at anvilcom.com Fri Jun 10 14:24:03 2005 From: phillip.watts at anvilcom.com (phil) Date: Fri, 10 Jun 2005 13:24:03 -0500 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> Message-ID: <42A9DAC3.2010306@anvilcom.com> Not taking a position for or against the original post: Everytime this comes up, on any group, one little annoying post results in and endless discussion and sometimes hurtful flame war. Perhaps the rest of us should let the moderator handle it and get back to something interesting, like Python. :-} From philippe at philippecmartin.com Mon Jun 13 16:12:16 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 13 Jun 2005 20:12:16 GMT Subject: searching for IDE References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: pydev for eclipse ? alexrait1 wrote: > I need an IDE for python that has the ability to show the filds of a > class when I write "." > Just the way it works in eclipse/JBuilder with java or visual studio > with c++ > For now I treid eric3 and IDLE they don't do this... From irmen.NOSPAM at xs4all.nl Tue Jun 14 19:35:09 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 15 Jun 2005 01:35:09 +0200 Subject: Python in Games (was RE: [Stackless] Python in Games) In-Reply-To: <1118787883.193470.125620@f14g2000cwb.googlegroups.com> References: <1118787883.193470.125620@f14g2000cwb.googlegroups.com> Message-ID: <42af69ad$0$96347$e4fe514c@news.xs4all.nl> Patrick Down wrote: > My understanding is that the upcoming Civilization IV will have python > scripting. > Also, alledgedly the new BattleField II uses Python in a way... because I heard that you had to comment out a certain line in a certain .py file to remove the time limit of the demo :-) --Irmen From gcholakidis at hotmail.com.spam-remove Thu Jun 16 06:43:57 2005 From: gcholakidis at hotmail.com.spam-remove (Grigoris Tsolakidis) Date: Thu, 16 Jun 2005 13:43:57 +0300 Subject: UML to Python/Java code generation References: Message-ID: There is tool to generate UML from Python Code... "Maurice LING" wrote in message news:d8qlvb$pog$1 at domitilla.aioe.org... > Hi, > > Is there any UML tools that is able to take UML and generate Python codes? > > Cheers > Maurice From noreply at gcgroup.net Wed Jun 22 11:06:23 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 22 Jun 2005 15:06:23 GMT Subject: a comprehensive Tkinter document? Message-ID: I know a major problem I am having is that I am finding lots of Tkinter information in 'fragments' of various , sometimes conflicting vintages. For example the python reference I was using didn't show the '%%' as an escape sequence, I posted asking how to escape the '%' and after several helpful responses voila I found a more complete table of escape sequences. Is there a comprehensive document or book that I can get that is relatively current? I realize that updates and changes are dynamic, but I'm realizing that I am trying to use documents that look similar, only to find that one is several years old, or that another applies to an offshoot of Tkinter. I'm not even sure Tkinter is the 'preferred' gui anymore. Any suggestions? Bill From steve at REMOVETHIScyber.com.au Sat Jun 18 05:20:00 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Jun 2005 19:20:00 +1000 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? References: <9s77b1h8195sgmvb8p4e9qp8qts1tokprl@4ax.com> Message-ID: On Sat, 18 Jun 2005 04:26:13 +0000, Dennis Lee Bieber wrote: > On Sat, 18 Jun 2005 03:02:13 +1000, Steven D'Aprano > declaimed the following in > comp.lang.python: > >> >> The language is *always* spelt without the "a", and usually all in >> lower-case: perl. >> > Given that, at least one well known, book relates the name to > Practical Extraction (&) Report Language, whether that was a retrofit or > not -- I'd be tempted to user PERL for the name... According to Larry Wall, PERL is *officially* wrong and should *never* be used. > All lowercase most > likely reflects the standard habits of Linux/Unix command naming. And since Larry came from that tradition, you are most likely correct. And that is why originally the official name of the language was all lowercase. Things change, and now Perl is officially the name of the language, and perl officially the name of the implementation of the language. Reading the Perl FAQs at www.perl.org is a good place to start. -- Steven. From eurleif at ecritters.biz Fri Jun 3 22:13:49 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 04 Jun 2005 02:13:49 GMT Subject: Scope In-Reply-To: References: Message-ID: Elliot Temple wrote: > I want to write a function, foo, so the following works: > > def main(): > n = 4 > foo(n) > print n > > #it prints 7 What's wrong with: def foo(n): return 7 def main(): n = 4 n = foo(n) print n Anything else (including the tricks involving mutable objects that will no doubt be posted) will result in ugly, hard to maintain code. From sean_mcilroy at yahoo.com Fri Jun 24 13:19:53 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 24 Jun 2005 10:19:53 -0700 Subject: Two questions on lambda: In-Reply-To: References: Message-ID: <1119633593.266445.199830@g44g2000cwa.googlegroups.com> def PRINT(x): print x f = lambda: PRINT("hello") ################################### def let(x,y): globals()[x] = y return True f = lambda x: let('y',x*x) and y+y From fuzzyman at gmail.com Sun Jun 19 06:39:03 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 19 Jun 2005 03:39:03 -0700 Subject: Help implementing an idea In-Reply-To: References: Message-ID: <1119177543.671321.118700@g43g2000cwa.googlegroups.com> Nicholas.Vaidyanathan at asu.edu wrote: [snip..] > results. Now, I was thinking today, I'd really like to create a program that > can go to a specific directory and upload all the files in the directory to a > specific url for backup purposes, and I have the feeling that the python > implementation would be ruthlessly small and efficient, like the > above....anyone who could point me in the right direction as to how to actually > do it? Upload to a URL *sounds* like you want to do the upload by http rather than ftp. In this case you can do it with a Python CGI on the server and a script on the client that communicates with the CGI. When voidspace is back up you can find a pair of scripts that do just that : http://www.voidspace.org.uk/python/cgi.shtml#upload Hint - filelist = [os.path.join(directory, entry) for entry in os.listdir(directory)] Regards, Fuzzy http://www.voidspace.org.uk/python From fabio.pliger at siavr.it Sat Jun 11 13:43:59 2005 From: fabio.pliger at siavr.it (Fabio Pliger) Date: Sat, 11 Jun 2005 17:43:59 GMT Subject: wx ListCtrl with combobox... Message-ID: Hi all, i'm working on a very large project using wx 2.5... On one frame i have a wx.lib.mixins.listctrl widget, wich is a listctrl extended with the possibility to edit the columns text entrys.... Anyone know if it's possible (or if there's a widget...) to have also the possbility to have a comboBox in the list (with the text edit entry)? The final result i need is a list with 2 columns, one with the text entry editable, and the other with a comboBox in it... Anyone know to do it? TNX a lot... F.P. From chad.hughes at pnl.gov Thu Jun 9 17:13:01 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Thu, 09 Jun 2005 14:13:01 -0700 Subject: smtpd module Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6156@pnlmse27.pnl.gov> No, I know how to use the smtplib module and I can send email through that. However what I want is a the ability to set up a very simple mail server with python, for some tests that I need to run that just prints out the message to the standard out and disregards the message. The smtpd module seems to provide this ability via the DebuggingServer. According to the documentation that is provided with python the: class DebuggingServer( localaddr, remoteaddr) Create a new debugging server. Arguments are as per SMTPServer. Messages will be discarded, and printed on stdout. Unfortunately, this does not tell me how to use it. I cannot find any examples on the web. For that matter, I cannot find any other documentation anywhere. Has anyone ever used ether the SMTPServer object or the DebuggingServer object? If so, I would appreciate very much an example use case. Thanks, Chad -----Original Message----- From: Ivan Shevanski [mailto:darkpaladin79 at hotmail.com] Sent: Thursday, June 09, 2005 2:03 PM To: python-list at python.org Cc: Hughes, Chad O Subject: RE: smtpd module So youre wondering how to send mail in python? I have a lot of examples if you want the smtp module. I don't have anything for anything other than the smtp module. -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From mauriceling at acm.org Thu Jun 16 19:31:33 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 17 Jun 2005 09:31:33 +1000 Subject: which ports to use for SOAP? Message-ID: Hi, I'm writing something that specifies the use of SOAP. One requirement that fumbles me is the port number(s) to use. Is there any way to find out which ports are not used by the system? I've looked in the library reference and doesn't seems to get anything. Is there a problem with say 2 programs using the same ports? Thanks in advance. Maurice From emami at knmi.nl Wed Jun 8 07:48:30 2005 From: emami at knmi.nl (Nader Emami) Date: Wed, 08 Jun 2005 13:48:30 +0200 Subject: test Message-ID: L.S., I would like to learn how does work the "unit test" concept in Python. I have try the 'romantest.py' of the "Dive in Python" book and I get the next problem: Traceback (most recent call last): File "romantest.py", line 153, in ? unittest.main() File "/usr/lib/python2.3/unittest.py", line 721, in __init__ self.runTests() File "/usr/lib/python2.3/unittest.py", line 758, in runTests result = self.testRunner.run(self.test) File "/usr/lib/python2.3/unittest.py", line 657, in run startTime = time.time() AttributeError: 'module' object has no attribute 'time' I can't understand it! Would somebody tell me how I can solve this problem. Thanks, Nader From mahs at telcopartners.com Thu Jun 2 14:15:36 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 02 Jun 2005 11:15:36 -0700 Subject: Performance Issues please help In-Reply-To: References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> <1117723908.636248.302410@g14g2000cwa.googlegroups.com> Message-ID: Michael Spencer wrote: > def search1(m): > box = {} > for r,row in enumerate(m): > for c,e in enumerate(row): > try: > minc, minr, maxc, maxr = box[e] > box[e] = ( c < minc and c or minc, > r < minr and r or minr, > c > maxc and c or maxc, > r > maxr and r or maxr) > except KeyError: > box[e] = (c, r, c, r) > return box > > Michael > Sorry, my earlier solution was incorrect since: c < minc and c or minc # evaluates to minc if c == 0 Two of the tests are unnecessary, as pointed out by Peter The remaining test: c > maxc and c or maxc does not suffer from the same problem, since c cannot both be 0 and greater than maxc The following version, still untested ;-) has the correction: def search2(m): box = {} for r,row in enumerate(m): for c,e in enumerate(row): try: # use this form if e will be found 90%+ of the time # otherwise, use: if e in box: minc, minr, maxc, maxr = box[e] # note correction for c == 0 # also Peter's simplification box[e] = ( c and (c < minc and c or minc), minr, c > maxc and c or maxc, r) except KeyError: box[e] = (c, r, c, r) return box Michael From darkpaladin79 at hotmail.com Tue Jun 7 17:34:34 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Tue, 07 Jun 2005 17:34:34 -0400 Subject: SMTP help please In-Reply-To: <42A59565.6080209@syscononline.com> Message-ID: >From: Larry Bates >To: Ivan Shevanski >Subject: Re: SMTP help please >Date: Tue, 07 Jun 2005 07:39:01 -0500 > >I have found that the SmtpWriter class "hides" all the >complexity in creating emails like you want to send. > >Check it out here: > >http://motion.sourceforge.net/related/send_jpg.py This is good, but I don't want to send pictures and I don't know what to take out so it doesnt send pictures. I fooled around with it a little bit and kept getting this error: Traceback (most recent call last): File "mail.py", line 119, in ? writer.sendMessage() File "mail.py", line 94, in sendMessage aList = self.getImages() File "mail.py", line 90, in getImages attachList = os.listdir(self.__imageDir) AttributeError: SmtpWriter instance has no attribute '_SmtpWriter__imageDir' So. . .it was good but i still can't get it to work. . .Can you help? -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From claudio.grondi at freenet.de Thu Jun 23 18:05:29 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 23 Jun 2005 22:05:29 -0000 Subject: key - key pairs References: Message-ID: <3i0j0vFj36mfU1@individual.net> > is there in python a kind of dictionary that supports key - key pairs? > I need a dictionary in which I can access a certain element using two > different keys, both unique. > A Python dictionary needs a unique key, so a pair of keys is still one unique key, but probably it is some kind of misunderstanding here, because a dictionary is not a database which needs a key to quickly find an entry, so it can have as many keys as required. What about two dictionaries where each has as a value a key to the target dictionary with the actual values? > For example: > > I've a dictionary with strings and times. Sometimes I have the string and I > want to have the time, other time I've the time and I want the string. It > is important that one of the keys supports the min/max builtin function. >From this example it seems, that what is needed is a two-way dictionary. I don't know about a special kind of dictionary for this, so maybe someone else knows about such. I can only recommend to use two dictionaries, where the second one is created out of the first one, so that they key, value pair is reversed. If you need some code for the latter, let me know. Claudio "Florian Lindner" schrieb im Newsbeitrag news:d9f38l$v46$05$1 at news.t-online.com... > Hello, > is there in python a kind of dictionary that supports key - key pairs? > I need a dictionary in which I can access a certain element using two > different keys, both unique. > > For example: > > I've a dictionary with strings and times. Sometimes I have the string and I > want to have the time, other time I've the time and I want the string. It > is important that one of the keys supports the min/max builtin function. > > Thanks, > > Florian From duncan.booth at invalid.invalid Fri Jun 24 09:25:57 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jun 2005 13:25:57 GMT Subject: Two questions on lambda: References: Message-ID: Xavier D?coret wrote: > Is there a particular syntax for lambda that I am missing > or is it simply limited and I cannot do what I want with lambda. Lambda is deliberately limited. Just define a function. The only downside to defining a function is that you have to think of a name for it, but that name is simply a variable like any other and can be rebound at will. Any attempt to write an expression such as: f = lambda x : y=x*x,y+y should instantly set off lots of alarm bells in your mind. Defining a lambda simply to assign it to a name is obviously wrong: it should be a function definition instead. From aahz at pythoncraft.com Sat Jun 11 11:11:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2005 08:11:43 -0700 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: In article <8B6qe.1742$pa3.909 at newsread2.news.atl.earthlink.net>, flyingfred0 wrote: > >A small software team (developers, leads and even the manager when he's >had time) has been using (wx)Python/PostgreSQL for over 2 years and >developed a successful 1.0 release of a client/server product. > >A marketing/product manager has brought in additional management and >"architecture" experts to propose moving the entire thing to a Java >(application server) platform for the next release. They want a >"scalable, enterprise solution" (though they don't really know what that >means) and are going crazy throwing around the Java buzzwords (not to >mention XML). Point out that pushing this means they're almost certainly going to lose at least some of their development team, which means the next release is going to start from ground zero without the necessary expertise. Even if that doesn't happen, switching to Java is going to take much more time than improving the current product: http://www.JoelOnSoftware.com/articles/fog0000000069.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From rkern at ucsd.edu Wed Jun 29 15:08:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 29 Jun 2005 12:08:39 -0700 Subject: Inheriting from object In-Reply-To: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> Message-ID: Fuzzyman wrote: > Hello, > > To create a classic (old style) class, I write : > > class foo: > pass > > To do the equivalent as a new style class, I write : > > class foo(object): > pass > > *Should* I in fact write : > > class foo(object): > def __init__(self, *args, **kwargs): > object.__init__(self) > > ? I don't believe so. > Also, can anyone explain any tangible benefit of inheriting from > object, when not explicitly using any features of new style classes ? This class might not, but you (or someone else) may decide later to subclass it and want to use those features. It's a good habit to get into even if you don't initially plan on using those features. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From johan at sege.nu Thu Jun 9 07:21:30 2005 From: johan at sege.nu (Johan =?iso-8859-1?Q?Segern=E4s?=) Date: Thu, 9 Jun 2005 13:21:30 +0200 Subject: XML + SOAP + Webservices Message-ID: <20050609112130.GA5931@segernas.se> I'm put on building a system in Python and I haven't used either webservices, SOAP or Python so I'm a bit lost. This system will require callback functions, should I use Python thru Apache for this or build my own listening daemon? Use module for Apache or do I make some kind of CGI script in Python? Where do I start? What lib do I use for XML? SOAP? Webservices? Is there any nice project/tutorial for this so I can give it a taste and try to estimate how much time I need and stuff. Help needed. =) Thanks. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From karthish at gmail.com Mon Jun 13 15:55:35 2005 From: karthish at gmail.com (Karthish) Date: 13 Jun 2005 12:55:35 -0700 Subject: Access Database Using Python Message-ID: <1118692535.061915.239510@o13g2000cwo.googlegroups.com> I'm writing a script to look through DNA sequences in a database and select sequences I require. So far, my code looks like this for authentication: import os import Bio.Clustalw from Bio.Alphabet import IUPAC import pdb import sys import os import urllib import urllib2 import urllib userid = 'something' password = 'something2' location = 'index.html' params = urllib.urlencode({'user': userid, 'password': password, 'request_uri': location}) f = urllib2.urlopen("http://www.gene-regulation.com/login?%s" % params) print f.read() When I run the program, I see the following: ______________ Redirect

Please stand by, you will be redirected toindex.html...

________________ The code works as it is. How would I modify this script to display the page "http://www.gene-regulation.com/cgi-bin/pub/databases/transfac/getTF.cgi?AC=R00077"? I can't figure out how to authenticate and then load a page, since the page requires cookies for authentication. Thanks. From tim.golden at viacom-outdoor.co.uk Tue Jun 28 09:08:14 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 28 Jun 2005 14:08:14 +0100 Subject: Open running processes Message-ID: <9A28C052FF32734DACB0A288A3533991EBB93D@vogbs009.gb.vo.local> [DeRRudi] | I have a programm. In this program i've made the restriction that only | one instance can run at the time. (done with mutex). | Now i'd like it to open the running (make visible) instance when | someone want's to open it a second time. | Does anybody know how to do this? I hope you all understand what i | mean. My English isn't to good... | | Greetz Rudi Rudi; you're going to have to give some more information. It's clear that you're on Windows (because of the Mutex) but you don't say what form your program takes: is it a console app? something with a visible window? something which runs in the systray? Is it done using wxPython? PyQT? Tkinter? Something else? Assuming it's a program with a window, there are several options open to you (as I think I mentioned when you asked this question last week). Unless someone has a ready-made solution they're ready to post, a fair amount would depend on the nature of your program, and the amount you know already or are prepared to learn about how Windows apps work. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ptmcg at austin.rr.com Thu Jun 23 10:14:28 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jun 2005 07:14:28 -0700 Subject: List of all installed applications (XP)? In-Reply-To: References: Message-ID: <1119536067.946953.123360@g44g2000cwa.googlegroups.com> Get Tim Golden's wmi module (http://tgolden.sc.sabren.com/python/wmi.html). I recently had to help my brother remove some spyware, and so I used some of the example that came with WMI to read through the registry to extract startup keys, services, etc. Even if your users aren't sophisticated enough to mess with the registry, rest assured that the software installation programs are. You should be able to find traces of any installed commercial program that was released in the past 5 years - I suspect they *all* leave traces in the registry at this point. Go to HKEY_LOCAL_MACHINE\SOFTWARE and you will get a list of software vendors, and you can enumerate keys from there. Good luck! -- Paul From holbertr at dma.org Tue Jun 7 15:09:56 2005 From: holbertr at dma.org (Rick Holbert) Date: Tue, 07 Jun 2005 15:09:56 -0400 Subject: different time tuple format References: Message-ID: Like the last poster said, use %Z. On my Mandriva Linux system I get the following results: >>> time.localtime() (2005, 6, 7, 15, 7, 12, 1, 158, 1) >>> time.strptime("2005-06-07 15:07:12 EDT", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 1, 158, 1) Rick Maksim Kasimov wrote: > hi all, sorry if i'm reposting > > why time.strptime and time.localtime returns tuple with different DST (9 > item of the tuple)? is there some of setting to fix the problem? > > > Python 2.2.3 (#1, May 31 2005, 11:33:52) > [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 > Type "help", "copyright", "credits" or "license" for more information. > >>> import time > >>> time.strptime("2005-06-07 21:00:00", "%Y-%m-%d %H:%M:%S") > (2005, 6, 7, 21, 0, 0, 6, 1, 0) > >>> time.localtime() > (2005, 6, 7, 21, 2, 39, 1, 158, 1) > >>> > > From no at spam.com Sun Jun 12 18:27:18 2005 From: no at spam.com (Roose) Date: Sun, 12 Jun 2005 22:27:18 GMT Subject: How to test if an object IS another object? References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> Message-ID: This isn't a good example to test with, since 3 is an immutable object, as is 300 and all ints. It's more meaningful if the objects are mutable. Why do you want to test identity in the first place? Roose wrote in message news:1118607204.001609.25310 at g47g2000cwa.googlegroups.com... > Sorry about removing my message, I posted with the wrong google > account, I don't really want my email where those irritating spam bots > can find it. > >>The most obvious way (as usual ?): >> >>if obj1 is obj2: >> // your code here > > I immediately thought of is, and tested it in the console, but it > didn't work quite like I expected: > >>foo = 3 >>bar = 3 >>zoo = foo >>foo is zoo > True >>foo is bar > True >>zoo is bar > True > > clearly foo and bar have the same value but they are different objects > aren't they? Yet applying the is operator yields True. > > Thanks, > -Dan > From apoptozinho at gmail.com Tue Jun 7 07:46:32 2005 From: apoptozinho at gmail.com (Apoptozinho) Date: Tue, 7 Jun 2005 12:46:32 +0100 Subject: how to show simulation at web In-Reply-To: References: Message-ID: <200506071246.40219.apoptozinho@gmail.com> If your problem is plotting graphics from numerical simulations perhaps this fragment of code from my learning python and mod_python may help you. def show(req): req.content_type="image/png" put,get=os.popen4('echo "set term png size 400,400 ; set out ; splot(sin(x)*cos(y))" | gnuplot') img=get.read() req.write(img) put.close() get.close() return apache.OK I feel there must be an easier, more elegant and performant method of doing this. On Monday 06 June 2005 10:57, Hallo (Ha) wrote: >hi all, > >I have tried making a simulation with python. I want it to be shown at >a web. It is ok when I run it. so, I decided using cgi. but, when I try >it using a web browser it doesn't work. > >Is it problem in the header or something else ? > >If there are any suggestions about this problem, I will be very happy. > >thanks -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From thomasbartkus at comcast.net Mon Jun 13 15:47:18 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 13 Jun 2005 14:47:18 -0500 Subject: Dealing with marketing types... References: <1118686670.891440.88180@g14g2000cwa.googlegroups.com> Message-ID: "fuzzylollipop" wrote in message news:1118686670.891440.88180 at g14g2000cwa.googlegroups.com... > man this is the worst advice I have ever heard, you can't "walk away > with code" someone else paid you to write. Regardless of what your > perceived slight is. > > NEVER take code you were paid to write unless you have it in writing > that you can, you will lose that one everytime. I'll agree here. If you were hired as an employee for salary or an hourly wage, you will have no standing whatsover as "owner" of the work you produced. If your ex employer charges you with theft, it will be a slam dunk in court. You don't own what you produced for your employer. Even if you were fool enough to do much if it on your own unpaid off hours. Even if they reneged on some verbal promises to you in order to con you into doing so. It sucks but that's the way it is. However - I certainly sympathize with the desire to fight thievery with thievery. Unfortunately, you can't win that way. Unless, of course, you can do it without being caught :-) But that only gets you revenge - not payment. Thomas Barkus From nid_oizo at yahoo.com_remove_the_ Thu Jun 23 09:43:26 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 23 Jun 2005 09:43:26 -0400 Subject: Reraise exception with modified stack Message-ID: <20zue.74584$Kk4.909739@news20.bellglobal.com> Hi, I've made a small utility to re-raise an exception with the same stack as before with additional information in it. Since I want to keep the same exception type and that some types have very specific constructors (which take, for example, more than one parameter), the only safe way I have found to made it is by hacking the str representation: import sys class ExceptionStr: def __init__(self, content): self.content = content self.infos = [] def addinfo(self, info): self.infos.insert(0, info) def __call__(self): return '\n' + '\n'.join(self.infos + [self.content]) def reraise(exception, additionalInfo): strFunc = getattr(exception, "__str__", None) if not isinstance(strFunc, ExceptionStr): strFunc = ExceptionStr(str(exception)) exception.__str__ = strFunc strFunc.addinfo(additionalInfo) raise exception, None, sys.exc_info()[-1] if __name__ == '__main__': def foo(): raise AttributeError('Test') def bar(): foo() try: try: try: bar() except Exception, exception: reraise(exception, "While doing x:") except Exception, exception: reraise(exception, "While doing y:") except Exception, exception: reraise(exception, "While doing z:") Suppose the resulted traceback is: Traceback (most recent call last): File "somefile.py", line 52, in ? reraise(exception, "While doing z:", MyException) File "somefile.py", line 50, in ? reraise(exception, "While doing y:", Exception) File "somefile.py", line 48, in ? reraise(exception, "While doing x:") File "somefile.py", line 46, in ? bar() File "somefile.py", line 40, in bar foo() File "somefile.py", line 38, in foo raise AttributeError('Test') AttributeError: While doing z: While doing y: While doing x: Test I would like to know how to code the reraise function so that the lines 48, 50 and 52 don't appear in the stack. Is it possible? Thx and regards, Nicolas From donald.welch at NOSPAM.hp.com Wed Jun 8 11:49:55 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Wed, 08 Jun 2005 08:49:55 -0700 Subject: MoinMoin WikiName and python regexes References: Message-ID: <42a65db8@usenet01.boi.hp.com> Ara.T.Howard wrote: > > hi- > > i know nada about python so please forgive me if this is way off base. > i'm trying to fix a bug in MoinMoin whereby > > WordsWithTwoCapsInARowLike > ^^ > ^^ > ^^ > > do not become WikiNames. this is because the the wikiname pattern is > basically > [snip] PHPWiki has the same "feature", BTW. (Sorry, couldn't get MoinMoin to work on Sourceforge, had to use PHPWiki). -Don From roy at panix.com Thu Jun 30 11:03:18 2005 From: roy at panix.com (Roy Smith) Date: 30 Jun 2005 11:03:18 -0400 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: There's a reprint this morning on slashdot of a 1984 review Byte did on the brand-new Macintosh (executive summary: cool machine, needs more memory). The first four software packages available for the new machine? MacWrite/MacPaint (they seem to count this as one package) Microsoft Multiplan Microsoft BASIC CSI MacForth No mention of Python :-( From onfrek at yahoo.com Thu Jun 2 10:02:12 2005 From: onfrek at yahoo.com (Michael Onfrek) Date: 2 Jun 2005 07:02:12 -0700 Subject: How to restrict lenght of entry widget to certain number of character In-Reply-To: <3g87tnFb1qrlU1@news.dfncis.de> References: <1117396149.334908.238580@g14g2000cwa.googlegroups.com> <1117700375.764690.305820@g44g2000cwa.googlegroups.com> <3g87tnFb1qrlU1@news.dfncis.de> Message-ID: <1117720932.415725.166490@o13g2000cwo.googlegroups.com> Ideed, good idea! From dirgesh at gmail.com Thu Jun 16 22:02:12 2005 From: dirgesh at gmail.com (GujuBoy) Date: 16 Jun 2005 19:02:12 -0700 Subject: substitue for LISTS and TUPLEs in C++ Message-ID: <1118973731.985650.256790@g49g2000cwa.googlegroups.com> I am trying to transfer some code from PYTHON to C++. What is the best substitute for a LIST and TUPLE in C++. please advice. From philippe at philippecmartin.com Mon Jun 13 15:04:56 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 13 Jun 2005 19:04:56 GMT Subject: recursive import list Message-ID: Hi, I have a fairly large project going on and would like to figure out automatically from the source which files are being imported. ex: find_out mymain.py Is there an easy way to achieve that ? Regards, Philippe From hancock at anansispaceworks.com Wed Jun 29 01:52:16 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 29 Jun 2005 00:52:16 -0500 Subject: what is your opinion of zope? In-Reply-To: References: Message-ID: <200506290052.16999.hancock@anansispaceworks.com> On Tuesday 28 June 2005 08:35 pm, Avery Warren wrote: > On Sun, 26 Jun 2005 23:14:48 -0500, Terry Hancock wrote: > > > However, I'm not sure why you want this information. If you are > > trying to import data into Zope, you are more likely going to be > > using Zope, not accessing ZODB directly. > > The real problem is that the version of wiki we currently use > doesn't support any concept of workflow. That is fine for the > company now but as it matures in its processes, a more mature > solution will become more and more compelling. I don't think you quite understood my response: I wasn't asking why you were interested in Zope, but rather why you think you need to access ZODB directly to do what you want. It's very unlikely that you do. Usually with Zope, you never really have to think about the ZODB, you just know it's there, and that's about it. More probably, you can import what you need by scripting on top of Zope. Then Zope takes care of talking to the ZODB for you. While it may be technically feasible to write a script to translate files from another source and put them directly into the ZODB database, it probably means reinventing the wheel quite a bit. I think you probably should be looking at how to do what you need with Zope scripts. ZWiki, for example, uses a pretty simple "file format" (this is technically a bit of a fiction since "files" in Zope are really just objects in the ZODB), which I think is defined by the Wiki standard (it resembles "structured text" in any case --- I'm uncertain whether they are actually the same or not). Assuming that the format is the same as in other Wiki packages (and I think it is), this *could* be as simple as FTPing the files into Zope's FTP interface. Or, at a slightly more complex level, manually adding each wiki page object. Or, creating a script using Zope's through-the-web interface to recursively copy your old site using ZWiki page objects. There could be some gotchas in there, but this is almost certainly going to be better than trying to access the ZODB directly. I can understand that this would not be your expectation if you were used to SQL-backed systems. With those, the SQL back end is often going to be a better interface point. But it's different with ZODB and Zope. Perhaps more importantly, I think this task will be easier than you are expecting it to be --- I'd hate for you to waste a lot of time on a complicated solution when a "quick and dirty" one will do. > > Without more specifics about what you are looking for, it would be > > hard to reply further than this. And of course, by this, I meant to go beyond what I already said. I don't mind telling you I like Zope and/or what I use it for, but it's a big subject! ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tjreedy at udel.edu Fri Jun 10 13:10:02 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Jun 2005 13:10:02 -0400 Subject: Annoying behaviour of the != operator References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: "Rocco Moretti" wrote in message news:d8c9cg$pa7$1 at news.doit.wisc.edu... > The "wackyness" I refered to wasn't that a list of complex numbers isn't > sortable, but the inconsistent behaviour of list sorting. As you > mentioned, an arbitraty collection of objects in a list is sortable, but > as soon as you throw a complex number in there, you get an exception. This 'wackyness' is an artifact resulting from Python being 'improved' after its original design. When Guido added complex numbers as a builtin type, he had to decide whethter to make them sortable or not. There were reasons to go either way. ... and the discussion has continued ever since ;-) Terry J. Reedy From nospam at nospam.nospam Sun Jun 12 06:41:58 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Sun, 12 Jun 2005 03:41:58 -0700 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118429907.140244.298390@g43g2000cwa.googlegroups.com> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 11 Jun 2005 11:51:02 -0500, tom wrote: ... >Let me add an Item #3 - >If you have some entrepeneurial savvy and can keep your emotions out of >it tou can simply tell them you have decided strike out on your own and >tell them that you will be available. They will be happy to hear you are >leaving and happier still to hear you can be available for backup. >Their goals and fears are addressed at the same time. AND there is a very >high possibility that they will *need* you at a later date for which you >can charge them dearly. > >That last item #3 has actually worked for me with (2) prior employers. >I did have to eat my indignation and keep it friendly but it did pay off >in the end. >Thomas Bartkus I have to say that, although I have yet to write a line of Python code for money, I've found that this concept basically works. When you realize that your employer is cutting you out to save the cost of paying you, funny enough, they'll be willing to -really- pay you as a consultant later when they get stuck, and one or more paying customers are impacted. They also win't mind figuring out how to have you come in after hours so it won't conflict with your new day job if you have one. In my case, the work was in VB/VBA, but the same principle should apply to any technology. Do make sure that your contract with any new employer allows you to do at least small amounts of moonlighting - they probably won't object. They will insist that any moonlighting shall not compete with their line of business, and you should agree to that stipulation. From ypaami at gmail.com Thu Jun 30 07:49:56 2005 From: ypaami at gmail.com (Xinyue Ye) Date: Thu, 30 Jun 2005 07:49:56 -0400 Subject: sys.ps2 Message-ID: when I type sys.ps2 after import sys, I got the message like: Traceback (most recent call last): File "", line 1, in -toplevel- sys.ps2 AttributeError: 'module' object has no attribute 'ps2' why does it happen? From __peter__ at web.de Fri Jun 3 03:59:11 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Jun 2005 09:59:11 +0200 Subject: read input for cmd.Cmd from file References: Message-ID: Achim Domma (Procoders) wrote: > I'm writing a simple shell using cmd.Cmd. It would be very usefull if I > could read the commands as batchjob from a file. I've tried the following: > > class MyShell(cmd.Cmd): > def __init__(self,stdin): > cmd.Cmd.__init__(self,stdin=stdin) > ... > ... > > if __name__=='__main__': > if len(sys.argv)==2: > shell=MyShell(file(sys.argv[1])) > else: > shell=MyShell(sys.stdin) > shell.cmdloop() > > Calling 'myshell.py inputfile' with an invalid inputfile, I get an > error, so it seems that the file is opened. But the shell starts as > usuall, ignoring the content of the file. There is no output and no > errors (if I write nonsens into the inputfile). [While I'm at it, duplicated from de.comp.lang.python] Interesting idea. The simplest approach I found was to feed the file directly into the cmdqueue-Attribute: import cmd class Cmd(cmd.Cmd): ????def?do_this(self,?arg): ????????print?"this>",?arg ????def?do_that(self,?arg): ????????print?"????? ????? ????? <874qc3inla.fsf@hector.domek> Message-ID: "Peter Dembinski" wrote in message news:874qc3inla.fsf at hector.domek... > "Terry Reedy" writes: >> I believe the top-level production is something like >> BYTECODE := (OPCODE ARGS)* > > ROTFL :) Glad to make your day ;-) I am aware that since ARGS depends on OPCODE, the above would lead to context-dependent productions for ARGS. Upon thoroughly perusing http://docs.python.org/lib/bytecodes.html 18.10.1 Python Byte Code Instructions I discovered that there is at most one (non-stack) argument in the byte stream (contrary to the possibly plural implication of "All of the following opcodes expect arguments"). So the above could be written context-freely as BYTECODE := (NO_ARG_CODE | ARG_CODE TWO_BYTE_ARG)* where the symbolic expansions of NO_ARG_CODE and ARG_CODE, with semantic explanations, constitute the contents of the doc above. Terry J. Reedy From fperez.net at gmail.com Fri Jun 17 19:07:59 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 17 Jun 2005 17:07:59 -0600 Subject: whos -- a function listing objects References: <1118948272.051392.323240@g14g2000cwa.googlegroups.com> <1119040825.743795.228870@z14g2000cwz.googlegroups.com> Message-ID: benyang22 at yahoo.com wrote: > That is nice. I didn't know iPython can do whos. Will try it. > > iPython seems to infinitely configurable. Hope it will not suck too > much of my time into it. It is. It probably will. It did to me :) At least, I hope it will have been time well spent. Best, f ps - you mention using matlab. Note that ipython integrates with matplotlib in its -pylab mode, to provide interactive plotting without blocking for almost all GUI backends (Tk, GTK, WX and Qt are supported, FLTK is not, though it might work). From gilles.lenfant at nospam.com Tue Jun 14 13:51:57 2005 From: gilles.lenfant at nospam.com (Gilles Lenfant) Date: Tue, 14 Jun 2005 19:51:57 +0200 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: References: Message-ID: <42af1b28$0$10131$626a14ce@news.free.fr> rbt a ?crit : > Here's the scenario: > > You have many hundred gigabytes of data... possible even a terabyte or > two. Within this data, you have private, sensitive information (US > social security numbers) about your company's clients. Your company has > generated its own unique ID numbers to replace the social security numbers. > > Now, management would like the IT guys to go thru the old data and > replace as many SSNs with the new ID numbers as possible. You have a tab > delimited txt file that maps the SSNs to the new ID numbers. There are > 500,000 of these number pairs. What is the most efficient way to > approach this? I have done small-scale find and replace programs before, > but the scale of this is larger than what I'm accustomed to. > > Any suggestions on how to approach this are much appreciated. Are this huge amount of data to rearch/replace stored in an RDBMS or in flat file(s) with markup (XML, CSV, ...) ? -- Gilles From chinook.nr at tds.net Tue Jun 28 21:02:15 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 21:02:15 -0400 Subject: OO refactoring trial ?? References: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> <0001HW.BEE6FEEE000C427BF0407550@news.gmane.org> Message-ID: <0001HW.BEE76B57000F3FDEF0407550@news.gmane.org> Never mind. > > BTW: Is duck-typing a variation on duct-taping? > http://www.rubygarden.org/ruby?DuckTyping http://en.wikipedia.org/wiki/Duck_typing Lee C From fperez.net at gmail.com Wed Jun 1 11:55:14 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 01 Jun 2005 09:55:14 -0600 Subject: Unhappy with numarray docs References: <429dc954$1@nntp0.pdx.net> <1dlr911ln6omm7nov1amaqtbikdvp51p7n@4ax.com> Message-ID: Matt Feinstein wrote: > On Wed, 01 Jun 2005 08:11:36 -0700, Scott David Daniels > wrote: > >>Propose some fixes to the documents that will make this easier for >>the next one in line. You don't even need to get it exactly right; >>the person after you can fix the mistakes you make. This is the >>process we use for this. See this as an opportunity to contribute, >>not simply a frustration about how much you overpaid for the product. > > Which is why I was specific about what I didn't like about the > documentation and why I didn't like it. Seriously, what more should I > do? It's plainly inappropriate for me to write documentation for a > module that I'm still struggling to learn. Just a suggestion: post your message on the numeric discussion list (where numarray is also discussed). Most of the num* developers only check c.l.py on occasion, so it's very easy that your message will be simply missed by the appropriate people, which would be a shame. They are generally very responsive to user requests and constructive criticism. best, f From steve at REMOVETHIScyber.com.au Fri Jun 17 12:53:10 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Jun 2005 02:53:10 +1000 Subject: Multiple instances of a python program References: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> Message-ID: On Thu, 16 Jun 2005 11:47:10 -0700, Rahul wrote: > Hi. > I am part of a group in my univ where we organize a programming > contest. In this contest we have a UDP based server. The server > simulates a game and each contestant is to develop a team of virtual > players. Each team is composed of 75 similar bots...i.e. governed by > the same logic. Thus the contestant submits a single copy of the client > and we instantiate the same program 75 times at the same time. > The problem is that while executables from C source files are small and > we can make 75 processes but we dont know what to do with python. > > If you have a python script and you want that 75 copies of the script > be run simultaneously how will you do it? Is there anyway to do so > without running 75 copies of the python interpreter simultaneously? Have you actually tested the performance of 75 instances of Python running? Do you know that it will be too slow for your server, or are you trying to optimize before testing? I wrote a short Python script, then launched 115 instances of Python executing the script. There was no detectable slowdown of my system, which is far from a high-end PC. The details of the script aren't important. It may even be that what I tested is not even close to the load your server needs to deal with. But you may be surprised at just how easily even a low-end PC copes 75 instances of Python. Or perhaps not -- but the only way to tell is to try. -- Steven. From ivanlan at pauahtun.org Wed Jun 1 17:11:00 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Wed, 01 Jun 2005 15:11:00 -0600 Subject: PySol not working on WinXP, SP2 References: <429DC8F7.38AFB2B5@pauahtun.org> Message-ID: <429E2464.42EF8539@pauahtun.org> Hi All-- James Carroll wrote: > > You might try finding the source to pysol, and you might notice that > you have a bunch of *.py files and for each of those, a corresponding > .pyc file. If you delete all the pyc files, then they'll get > re-created from the .py files, and you might be all set. > Nope. The pyc files don't match the py files, and he imports the pyc files directly. That's what 'imp.load_compiled("__main__", sys.argv[0])' means. The windows version that Markus shipped never included the .py files anyway, since he didn't need them. Getting the source and trying to run it directly would work if there were any doc help at all, but there's none. What little there is is aimed at Linux. Makefiles need to be constructed, & there are templates that get filled out automatically. I can get it working eventually, I suppose, but I was really hoping someone else had done the work already, or at least had pointers to docs on how to get it working. Metta, Ivan > -Jim > > On 6/1/05, Ivan Van Laningham wrote: > > Hi All-- > > I've been using PySol-4.40 for years, because that was the last Windows > > installer version I could find. My wife's been using it for almost the > > same length of time. That version's worked just fine on W98, W98SE, W2K > > (server included), and WinXP SP1. > > > > I upgraded to SP2 and pysol fails silently. Running 'python pysol.pyw' > > gives me this error: > > > > Traceback (most recent call last): > > > > File "pysol.pyw", line 64, in ? > > > > imp.load_compiled("__main__", sys.argv[0]) > > > > ImportError: Bad magic number in C:\Program > > Files\PySol-4.40\data\pysol.pyc > > > > I can't find any later version on google, although I turned up a thread > > on this list regarding running pysol in a later version on W98. I also > > found http://avitous.net/software/pysol-windows/py23.shtml but the > > version he has REQUIRES ActiveState python 2.2, even though he says he's > > put together a version for 2.3--and of course, I'm running Python 2.4. > > > > My wife's going to be force to upgrade to SP2 some of these days, and > > she won't be happy if her solitaire doesn't work. Does anyone have a > > working version? Anyone know what happened to Markus ... Oberhumer? > > > > Metta, > > Ivan > > ---------------------------------------------- > > Ivan Van Laningham > > God N Locomotive Works > > http://www.andi-holmes.com/ > > http://www.foretec.com/python/workshops/1998-11/proceedings.html > > Army Signal Corps: Cu Chi, Class of '70 > > Author: Teach Yourself Python in 24 Hours > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From lee at example.com Tue Jun 28 08:07:36 2005 From: lee at example.com (Lee Harr) Date: Tue, 28 Jun 2005 12:07:36 GMT Subject: pyqt, windows xp and systray applications.. possible? References: <1119959705.054932.159780@g47g2000cwa.googlegroups.com> Message-ID: On 2005-06-28, bastian.salmela at gmail.com wrote: > hi, > > I've been searching long, and found some information, but still not > enough for me to actually make it happen. so, I ask here. > > is it possible, in windows, to make PyQT application hide itself into > systray area? > > I read,that you might have to use winEventFilter(), and do some magic > with WM_ messages. well, I don't know enough windows API.. so if anyone > here have done this, could you please help me out and show a little > example how it's done.. > I recommend joining the pyqt mailing list: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde From AzizMcTang at gmail.com Wed Jun 22 05:48:47 2005 From: AzizMcTang at gmail.com (Aziz McTang) Date: 22 Jun 2005 02:48:47 -0700 Subject: Want to learn a language - is Python right? References: <1119264546.393296.245650@f14g2000cwb.googlegroups.com> <7x3brdjnyt.fsf@ruckus.brouhaha.com> <1119278824.847517.294700@g47g2000cwa.googlegroups.com> <1119358700.737855.20410@z14g2000cwz.googlegroups.com> Message-ID: <1119433727.566561.326690@z14g2000cwz.googlegroups.com> Hi Everyone, Thanks for all the helpful advice. Downloaded 2.4.1 and already have an inkling of some of the things it can do. Time to start learning! ATB Aziz From harold.fellermann at upf.edu Tue Jun 21 08:15:57 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 21 Jun 2005 14:15:57 +0200 Subject: eval() in python In-Reply-To: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> References: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> Message-ID: > the doc seems to suggest that eval is only for expressions... it says > uses exec for statements, but i don't seem to see a exec function? Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> s="print 'hello Xah Lee :-)'" >>> exec(s) hello Xah Lee :-) >>> - harold - -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called "brightness", but it doesn't seem to work. -- Gallagher From newsgroups at jhrothjr.com Sun Jun 12 21:05:14 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 12 Jun 2005 19:05:14 -0600 Subject: changing how instances are "created" References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> <11api166se4itcc@news.supernews.com> <1118620840.352981.60420@g14g2000cwa.googlegroups.com> Message-ID: <11apmugku536u8d@news.supernews.com> "newseater" wrote in message news:1118620840.352981.60420 at g14g2000cwa.googlegroups.com... >> > class Creator >> > def createInstance(cls, *args, **kwargs): >> > anewinstance = cls.__new__(cls, *args, **kwargs) >> > anewinstance.__init__(*args, **kwargs) >> > >> > return anewinstance >> > createInstance = staticmethod(createInstance) >> > >> > >> > can anyone help?? >> >> __new__ is the proper way to do this, but making it work >> is a bit tricky. If you could post the code you tried to >> get to work for __new__(), we could critique it. >> >> The current documentation is in 3.3.1 of the Python >> Reference Manual (Python 2.4 version). In earlier >> versions, there were a couple of other documents >> that did a better (IMO) job of explaining things. >> >> The trick is that __new__ must return an instance. >> It can be a newly created instance (and the doc shows >> how to do this) or an existing instance of any new style >> class. > > from the documentation it was very hard to guess what the "..." was > supposed to be. also i wasn't able to find out how to control if > __init__() would be called on an instance (if i reused that instance.. > and that instance could be of a completely different type). I believe that __init__() is not called if the instance is not of the same type as the class with the __new__() method. There was a thread on that not too long ago, and I believe that was the resolution: the docs were wrong, __init__ is only called if the returned instance is for the class with the __new__ method. The 2.4 docs seem to say it properly. > eg. i didn't get much out of > http://docs.python.org/ref/customization.html > > from http://gnosis.cx/publish/programming/metaclass_1.html This has nothing to do with metaclasses. Wandering into that will fry your brain. ... > > but that way of creating objects is just plain silly! Yep. If you don't need a metaclass, don't use one. Metaclasses are a special purpose construct. If you need it, you'll know that you need it. Othewise you don't, and you certainly don't here. > I tried looking at the __new__ buildin but this seems to be addressing > old-style objects (which i'm not interested in using). __new__ is only invoked for new style classes; it is not invoked for old style classes.f The following may be helpful: it's a relatively extended article on new style classes that was left out of the 2.4 references because the content had supposedly been absorbed into the mainline documentation. http://www.python.org/2.2.3/descrintro.html >> By the way - when you post code, please use spaces >> for indentation. There are a number of popular mail >> clients that don't play fair with tabs, and people using >> these clients will frequently ignore code that isn't >> properly indented. > > sorry. maybe people should complain to those lousy newsreader authors > instead of everyone having to comply to the lowest standards? I guess > the readers are actually un*x readers although your comment typically > is found in the w*ndows world where everyone is forced into using word > :-) This dead horse has been beaten into a pulp many times. People with newsreaders and mail clients that don't play fair with tabs are not going to change; snide remarks will only reflect on the person making the remark. The major problem is IE, although I've seen other newsreaders and mail clients do the same thing. Also, I don't even have Word on my Windows system; I use Open Office. Being "forced" to use Word is a choice. John Roth > > >> John Roth > From marcel.vandendungen at gmail.com Sun Jun 12 09:34:14 2005 From: marcel.vandendungen at gmail.com (marcel.vandendungen at gmail.com) Date: 12 Jun 2005 06:34:14 -0700 Subject: Slicing an IXMLDOMNodeList Message-ID: <1118583254.338881.208620@f14g2000cwb.googlegroups.com> Hi, I'm using MSXML to select elements from a XML document and want to slice off the last part of an IXMLDOMNodeList. >>> import win32com.client >>> xmldoc = win32com.client.Dispatch('msxml.DOMDocument') >>> xmldoc.load('file.xml') True >>> rgelem = xmldoc.selectNodes('/root/elem') >>> if rgelem.length > 10: ... rgelem = rgelem[-10:] ... Traceback (most recent call last): File "", line 2, in ? File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 454, in __getattr__ raise AttributeError, "'%s' object has no attribute '%s'" % (repr(self), attr) AttributeError: '' object has no attribute '__len__' >>> The IXMLDOMNodeList obviously doesn't have a '__len__' member function (why not?). Is there a way to make the IXMLDOMNodeList support slicing? I've tried to give the rgelem object a __len__ member, but got an exception from __setattr__: File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 462, in __setattr__ raise AttributeError, "'%s' object has no attribute '%s'" % (repr(self), attr) AttributeError: '' object has no attribute '__len__' Anybody know how to make this work? TIA, -- Marcel From peter at engcorp.com Thu Jun 9 17:19:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 17:19:54 -0400 Subject: Interpreter-like help in cmd.Cmd In-Reply-To: References: Message-ID: <2MCdnf5cFKCCLjXfRVn-pw@powergate.ca> Sarir Khamsi wrote: > Is there a way to get help the way you get it from the Python > interpreter (eg, 'help(dir)' gives help on the 'dir' command) in the > module cmd.Cmd? I know how to add commands and help text to cmd.Cmd > but I would also like to get the man-page-like help for classes and > functions. Does anyone know how to do that? Thanks. >>> dir(help) ['__call__', '__class__', '__delattr__', '__dict__', ... [Hmm... unexpected result... let's see what it is.] >>> help.__class__ [ah... loading site.py and looking for "_Helper"...] class _Helper(object): """Define the built-in 'help'. This is a wrapper around pydoc.help (with a twist). """ def __repr__(self): return "Type help() for interactive help, " \ "or help(object) for help about object." def __call__(self, *args, **kwds): import pydoc return pydoc.help(*args, **kwds) HTH :-) -Peter From slava at crackpot.org Tue Jun 14 05:21:48 2005 From: slava at crackpot.org (slava at crackpot.org) Date: Tue, 14 Jun 2005 02:21:48 -0700 Subject: sudo open() ? (python newbee question) Message-ID: <1118740908.42aea1accf02f@secure.crackpot.org> hello, i am writing a python script that will be run by a non root user the script needs to open a file in write mode that is owned by root file = open('/etc/apt/sources.list', 'r+') returns permission error how can i call sudo on open()? thanks alot slava From daniel.dittmar at sap.corp Tue Jun 28 05:39:34 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 28 Jun 2005 11:39:34 +0200 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119946239.413507.93080@g44g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1119946239.413507.93080@g44g2000cwa.googlegroups.com> Message-ID: gatti at dsdata.it wrote: > List comprehensions, however, *are* the basic control flow; loops are > much more verbose and they should be used only when necessary. List comprehensions are probably a bad idea for entry level programmers: - for and while loops are much easier to debug as you can insert print statements everywhere - list comprehensions don't allow you to break complex expressions into several simpler ones by using local variables, everything has to happen in one expression Daniel From sjmachin at lexicon.net Thu Jun 30 07:49:20 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 30 Jun 2005 21:49:20 +1000 Subject: aligning text with space-normalized text In-Reply-To: References: <42C35438.2010207@lexicon.net> Message-ID: <42C3DC40.4050806@lexicon.net> Steven Bethard wrote: > John Machin wrote: > >> If "work" is meant to detect *all* possibilities of 'chunks' not >> having been derived from 'text' in the described manner, then it >> doesn't work -- all information about the positions of the whitespace >> is thrown away by your code. >> >> For example, text = 'foo bar', chunks = ['foobar'] > > > This doesn't match the (admittedly vague) spec That is *exactly* my point -- it is not valid input, and you are not reporting all cases of invalid input; you have an exception where the non-spaces are impossible, but no exception where whitespaces are impossible. which said that chunks > are created "as if by ' '.join(chunk.split())". For the text: > 'foo bar' > the possible chunk lists should be something like: > ['foo bar'] > ['foo', 'bar'] > If it helps, you can think of chunks as lists of words, where the words > have been ' '.join()ed. If it helps, you can re-read my message. > > STeVe From http Sun Jun 5 19:14:47 2005 From: http (Paul Rubin) Date: 05 Jun 2005 16:14:47 -0700 Subject: "Opposite" of splitting? References: <42a38506$1@griseus.its.uu.se> Message-ID: <7x7jh8v1js.fsf@ruckus.brouhaha.com> Jan Danielsson writes: > I have a list of integers: > q = [ 1, 2, 4, 7, 9 ] > which I would like to convert to a string: > "1,2,4,7,9" s = ','.join([str(n) for n in q]) Alternatively, just repr(q) gives you '[1, 2, 4, 7, 9]' (with the brackets and spaces). From johannes.stromberg at strusoft.com Thu Jun 9 05:13:37 2005 From: johannes.stromberg at strusoft.com (Johannes) Date: 9 Jun 2005 11:13:37 +0200 Subject: Extending Python Message-ID: <42a80841@news.wineasy.se> I am thinking of replacing Lua as internal script controller and I know how to extend/embed python but is there a way of limiting what functionality can be actually be accessible to the user, f.e. I don't want the script to be able to read/write files? /Johannes From ivanlan at pauahtun.org Wed Jun 1 10:40:55 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Wed, 01 Jun 2005 08:40:55 -0600 Subject: PySol not working on WinXP, SP2 Message-ID: <429DC8F7.38AFB2B5@pauahtun.org> Hi All-- I've been using PySol-4.40 for years, because that was the last Windows installer version I could find. My wife's been using it for almost the same length of time. That version's worked just fine on W98, W98SE, W2K (server included), and WinXP SP1. I upgraded to SP2 and pysol fails silently. Running 'python pysol.pyw' gives me this error: Traceback (most recent call last): File "pysol.pyw", line 64, in ? imp.load_compiled("__main__", sys.argv[0]) ImportError: Bad magic number in C:\Program Files\PySol-4.40\data\pysol.pyc I can't find any later version on google, although I turned up a thread on this list regarding running pysol in a later version on W98. I also found http://avitous.net/software/pysol-windows/py23.shtml but the version he has REQUIRES ActiveState python 2.2, even though he says he's put together a version for 2.3--and of course, I'm running Python 2.4. My wife's going to be force to upgrade to SP2 some of these days, and she won't be happy if her solitaire doesn't work. Does anyone have a working version? Anyone know what happened to Markus ... Oberhumer? Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From mcherm at mcherm.com Fri Jun 10 15:38:46 2005 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 10 Jun 2005 12:38:46 -0700 Subject: match groups: optional groups not accessible Message-ID: <20050610123846.fc34s9m28y40ok08@login.werra.lunarpages.com> David Reitter writes: > Why does the following result in an IndexError? [...] > >>> import re > >>> m = re.match('(?Pmaybe)?yes', "yes") > >>> m.group(1) > >>> m.group('maybe') > Traceback (most recent call last): > File "", line 1, in ? > IndexError: no such group Because the name of the named group in your example is 'm' not 'maybe'. 'maybe' is the text to match. Try it like this: >>> import re >>> m = re.match('(?Pmaybe)?yes', "yes") >>> print m.group(1) None >>> print m.group('m') None -- Michael Chermside From jjl at pobox.com Sat Jun 4 18:43:39 2005 From: jjl at pobox.com (John J. Lee) Date: 04 Jun 2005 22:43:39 +0000 Subject: method = Klass.othermethod considered PITA Message-ID: <87oeallp44.fsf@pobox.com> It seems nice to do this class Klass: def _makeLoudNoise(self, *blah): ... woof = _makeLoudNoise One probably wants the above to work as if you'd instead defined woof in the more verbose form as follows: def woof(self, *blah): return self._makeLoudNoise(self, *blah) It doesn't, though. Two problems: 1. In derived classes, inheritance doesn't work right: >>> class A: ... def foo(s):print 'foo' ... bar = foo ... >>> a = A() >>> a.bar() foo >>> class B(A): ... def foo(s):print 'moo' ... >>> b = B() >>> b.bar() foo >>> 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do this. John From martin at v.loewis.de Sun Jun 12 13:09:15 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 12 Jun 2005 19:09:15 +0200 Subject: Custom type: PyObject_IS_GC access violation In-Reply-To: References: Message-ID: <42AC6C3B.1080107@v.loewis.de> Bue Krogh Vedel-Larsen wrote: > But if I call > > SA_PyVector_Type.tp_new = PyType_GenericNew; > PyType_Ready( &SA_PyVector_Type ); > > then, when Py_Finalize is called, PyObject_IS_GC(op) in visit_decref() in > gcmodule.c causes an access violation. If I don't call PyType_Ready, then > the access violation doesn't occure, but then the type can't be used... > > So, the question is, does anyone have any idea about what could be > causing this? Most likely some code that you haven't shown. Here is the expansion of PyObject_IS_GC(op) #define PyObject_IS_GC(o) (PyType_IS_GC((o)->ob_type) && \ ((o)->ob_type->tp_is_gc == NULL || (o)->ob_type->tp_is_gc(o))) so it becomes PyType_IS_GC(op->type) && (op->ob_type->tp_is_gc==NULL || op->ob_type->tp_is_gc(op)) Then, PyType_IS_GC(op->type) becomes PyType_HasFeature((op->type), Py_TPFLAGS_HAVE_GC) which in turn becomes (op->tp_flags & Py_TPFLAGS_HAVE_GC) != 0 So typically, PyObject_IS_GC goes to the type of the object, which should never crash, and then looks into the flags of the type, which cannot crash - unless somebody messed with ob_type of the object, and unless this isn't a Python object in the first place. You did not say what kind of object op was in the crash - this is something you should investigate further. Does it point to a Python object? If so, what is the type of the Python object? Regards, Martin From toutatis at xsFOURall.nl Wed Jun 29 11:23:16 2005 From: toutatis at xsFOURall.nl (TouTaTis) Date: 29 Jun 2005 15:23:16 GMT Subject: Python/IDLE - text in different colours References: Message-ID: "Bill Davy" wrote in news:d9rfb9$ob7$1 at nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com: > To make life easier for my users, I'd like to colour my prompt string > (as handed to raw_input()) a different colour to that produced by > print. I'm using Python 2.4.1 and IDLE 1.1.1 on Windows XP. Is it > possible, and if so, how? > tia, > Bill > > Communicating with a Program Say we want the shell to distinguish more clearly, the output of external programs from the input prompt, the commands, and the shell feedback. We want the output of external programs to be indented and displayed in a different colour than the other text. Setting the colour of the text is fairly easy using ANSI terminal escape sequences. For instance, to set the text colour to dark red, write " [31;2m" to the terminal (where is the escape code ? in emacs use "C-q ESC" to write ). We can reset the output colour using " 0m". Printing the output of external programs in dark red, we can do using the execute() function: def runCommand(command): print 'Running:', command # set output colour: sys.stdout.write("[31;2m") ; sys.stdout.flush() os.system(command) # reset output colour sys.stdout.write("[0m") (Here we need to flush the stdout file to make sure that the escape code is written to the terminal before the output of the program) http://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/process- management.html From richardlewis at fastmail.co.uk Thu Jun 16 11:31:44 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Thu, 16 Jun 2005 16:31:44 +0100 Subject: utf8 and ftplib Message-ID: <1118935904.13487.236520202@webmail.messagingengine.com> Hi there, I'm having a problem with unicode files and ftplib (using Python 2.3.5). I've got this code: xml_source = codecs.open("foo.xml", 'w+b', "utf8") #xml_source = file("foo.xml", 'w+b') ftp.retrbinary("RETR foo.xml", xml_source.write) #ftp.retrlines("RETR foo.xml", xml_source.write) It opens a new local file using utf8 encoding and then reads from a file on an FTP server (also utf8 encoded) into that local file. It comes up with an error, however, on calling the xml_source.write callback (I think) saying that: "File "myscript.py", line 75, in get_content ftp.retrbinary("RETR foo.xml", xml_source.write) File "/usr/lib/python2.3/ftplib.py", line 384, in retrbinary callback(data) File "/usr/lib/python2.3/codecs.py", line 400, in write return self.writer.write(data) File "/usr/lib/python2.3/codecs.py", line 178, in write data, consumed = self.encode(object, self.errors) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 76: ordinal not in range(128)" I've tried using both the commented lines of code in the above example (i.e. using file() instead of codecs.open() and retlines() instead of retbinary()). retlines() makes no difference, but if I use file() instead of codecs.open() I can open the file, but the extended characters from the source file (e.g. foreign characters, copyright symbol, etc.) all appear with an extra character in front of them (because of the two char width in utf8?). Is the xml_source.write callback causing the problem here? Or is it something else? Is there any way that I can correctly retrieve a utf8 encoded file from an FTP server? Cheers, Richard From jepler at unpythonic.net Tue Jun 21 08:33:36 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 21 Jun 2005 07:33:36 -0500 Subject: Embedding Python - Deleting a class instance In-Reply-To: References: Message-ID: <20050621123331.GA950@unpythonic.net> I wrote the following module to test the behavior of PyInstance_New. I called it something like this: import vedel class k: def __del__(self): print "deleted" vedel.g(k) I get output like: after creation, x->refcnt = 1 doing decref deleted after decref Unless there's a cycle and GC gets involved, all there is to deleting *anything* in Python is correctly managing the refcount. On the other hand, you can never free an object while it is still reachable. Some local name "x" may never spontaneously lose the thing it refers to. /*------------------------------------------------------------------------*/ #include static PyObject *g(PyObject *s, PyObject *o) { PyObject *x = PyInstance_New( o, NULL, NULL); if(x) { printf("after creation, x->refcnt = %d\n", x->ob_refcnt); printf("doing decref\n"); Py_DECREF(x); printf("after decref\n"); } else { printf("x == NULL\n"); } Py_INCREF(Py_None); return Py_None; } static PyMethodDef methods[] = { {"g", (PyCFunction)g, METH_O, NULL}, {NULL}, }; void initvedel(void) { Py_InitModule("vedel", methods); } /*------------------------------------------------------------------------*/ -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From hancock at anansispaceworks.com Wed Jun 22 18:02:01 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 22 Jun 2005 17:02:01 -0500 Subject: Package organization In-Reply-To: References: Message-ID: <200506221702.01081.hancock@anansispaceworks.com> On Wednesday 22 June 2005 01:42 pm, Thomas Lotze wrote: > Assume I have a package called PDF. Should the classes then be called > simply File and Objects, as it is clear what they do as they are > imported from PDF? Or should they be called PDFFile and PDFObjects, as > the names would be too undescriptive otherwise? If you import PDF instead of importing from PDF, you will get that anyway: import PDF then you can refer to: PDF.File and PDF.Object the only downside to this is that you are using a "." operator each time, which is a (TINY) performance hit. In tightly optimized loops, some folks recommend avoiding this. But then, so what? PDE_File = PDF.File and the problem goes away. This always seems cleaner to me than: PDF.PDFFile etc, which drives me crazy to read. Useless repetition just gets annoying. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From atulkshirsagar at yahoo.com Thu Jun 16 17:41:10 2005 From: atulkshirsagar at yahoo.com (Atul Kshirsagar) Date: Thu, 16 Jun 2005 14:41:10 -0700 (PDT) Subject: import error on solaris Message-ID: <20050616214110.51245.qmail@web30710.mail.mud.yahoo.com> Hello, I am embedding python in C++ using SWIG. * The appication runs as a server. * Mutiple clients send requests which execute some python scripts with import statements. * Each request is handled in a separate thread which has its own interepreter for script execution. * Requests are succesfully completed fine for some time and then I see some "ImportErrors" for example "ImportError: No module named string" Apart from these python replated errors I see some "too many files open" errors in my other server code. Other than solaris things work fine on other unix platforms and windos too. One additional thing I do for solaris is "import DLFCN; sys.setdlopenflags(DLFCN.RTLD_NOW | DLFCN.RTLD_PARENT);" One of my question is, is importing some module create a file handle ? Any help on this is appreciated. Thanks, Atul Kshirsagar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From Gerald.Klix at klix.ch Mon Jun 13 11:51:15 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Mon, 13 Jun 2005 17:51:15 +0200 Subject: [OT ?] (Pythonic) detection word protected files In-Reply-To: <42ada90e$0$14696$636a15ce@news.free.fr> References: <42ada90e$0$14696$636a15ce@news.free.fr> Message-ID: <42ADAB73.1010103@klix.ch> Perhaps you can use OpenOffice and it's python UNO Bindings? I only know about their existence, but perhaps this will be a starting point: http://udk.openoffice.org/ HTH, Gerald Gilles Lenfant schrieb: > Hi, > > This is certainly off topic, but as my problem must have a pythonic answer. > > I'm building an utility that makes a catalog of M$ word files in a giant > directory tree. The password protected files must be marked, and I > didn't find how to guess which files are password protected and which > ones are not. > > I can't use the COM interface for this because the utility must run on a > Linux Samba server. > > I didn't find anything satisfying in M$ related sites (like msdn) or > forums or google. > > Any hint ? > > Many thanks by advance. > > -- > Gilles -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From michele.simionato at gmail.com Thu Jun 9 03:11:13 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Jun 2005 00:11:13 -0700 Subject: Abstract and concrete syntax In-Reply-To: References: Message-ID: <1118301073.559077.129230@g49g2000cwa.googlegroups.com> >From a purist perspective the distinction statements/expressions is a mistake. However, if your primary concerns is readability, it makes sense, since it enforces ifs, try.. excepts, etc. to be consistently written for all coders. This definitely helps code review. Michele Simionato From lambacck at gmail.com Sun Jun 19 22:30:43 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Sun, 19 Jun 2005 22:30:43 -0400 Subject: Using swig to use an existing dll/library In-Reply-To: <1119085859.495422.169890@g14g2000cwa.googlegroups.com> References: <1119085859.495422.169890@g14g2000cwa.googlegroups.com> Message-ID: You should be able to access regular dlls and handle callbacks with the ctypes module without needing to resort to any real c code: http://starship.python.net/crew/theller/ctypes/ -Chris On 18 Jun 2005 02:10:59 -0700, peter.o.mueller at gmx.de wrote: > Hi together, > > i have a Windows DLL in C that is internally multithreaded and provides > a callback function to signal specific events. As I understood one can > use "normal" C-code with swig. Is it also possible to use existing > DLLs? Does swig can also handel the callback method? If not - is there > another wrapper toolkit that can do that? > > Thanks, > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From __peter__ at web.de Tue Jun 28 10:07:53 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Jun 2005 16:07:53 +0200 Subject: [OT] Re: What is different with Python ? (OT I guess) References: <42AED7B3.8060009@carmen.se> <6kh2c151vvhda93jghhm8qcrf9v64llf7t@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > and then, apart from t-shirts, the PSF could sell Python-branded > shampoos named "poetry in lotion" etc. Which will once and for all solve the dandruffs problem prevalent among the snake community these days. Not funny? know then that German has one term for both 'dandruff' and 'scale' (Schuppe). Still not funny? at least you have learned some German. Peter From steve at REMOVETHIScyber.com.au Sun Jun 12 12:40:42 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 02:40:42 +1000 Subject: How to get/set class attributes in Python References: Message-ID: On Sun, 12 Jun 2005 15:35:46 +0200, Kalle Anke wrote: > Anyway, I got another "problem" (read: being used to do it like this in other > languages). I'm used to use statically typed languages and for me one of the > advantages is that I can be sure that a parameter is of a certain type. So in > Java I could write > > void doSomething( data : SomeClass ){ ... } > > and I would be sure at compile time that I would only get SomeClass objects > as parameters into the method. > > In learning Python I've understood that I should write code in such a way > that it can handle different data and this is fine with me. But what if I > have a class where different attributes should only have values of a certain > type and everything else is an error. > > For example, if I have an class that defines three attributes: first and last > name plus email address. The only valid data types for the first two are > strings and for the last an EmailAddress class. > > How should I handle this in Python? > > Should I use just don't care (but I'm going to send the data to a database so > I need to ensure that the data is OK)? Should I use 'isinstance' and check > manually? Or should I do something else? As you have worked out, Python doesn't do automatic type-checking for you. But if you really do need type-checking, you can do it yourself with isinstance() and/or type(). It isn't forbidden :-) Or, you can try just coercing the data you have to the type you want. eg instead of testing to see if obj is an integer, you might do: try: obj = int(obj) except: raise TypeError("can't convert to integer") insert_in_database(obj) This may be appropriate for your application. Another method that is sometimes useful: you are expecting an instance of Waterfowl class, but actually you are happy to use duck-typing: if it looks like a duck, swims like a duck, and quacks like a duck, it is close-enough to a duck: def process_waterfowl(duck): """do things to an instance of Waterfowl, or equivalent""" try: look, swim, quack = duck.look, duck.swim, duck.quack except AttributeError: raise TypeError("object is not a waterfowl") # process any object that has look, swim and quack attributes # as if it were a waterfowl duck.look() duck.swim() duck.quack() -- Steven. From tiang_ono at yahoo.com Wed Jun 22 00:19:43 2005 From: tiang_ono at yahoo.com (Titi Anggono) Date: Tue, 21 Jun 2005 21:19:43 -0700 (PDT) Subject: need help with mod_python in RH 9 Message-ID: <20050622041943.49763.qmail@web30706.mail.mud.yahoo.com> Hi all, I use apache2.0, mod_python 3.0, and python2.2.2. In /etc/httpd/conf.d/python.conf, I added following (as I read in the manual) AddHandler python-program .py PythonHandler mptest PythonDebug On and create mptest.py under directory /var/www/html/htdocs, (as I read in the manual) ------------------------ from mod_python import apache def handler(req): req.content_type="text/html" req.send_http_header() req.write("Hello World!") return apache.OK ----------------------------------- when I use url http://192.168.231.3/html/htdocs/mptest.py, I get the code listing. Apache doesn't execute the file. Could somebody tell me how to tell apache to execute the code. ____________________________________________________ Yahoo! Sports Rekindle the Rivalries. Sign up for Fantasy Football http://football.fantasysports.yahoo.com From phillip.watts at anvilcom.com Thu Jun 30 17:19:10 2005 From: phillip.watts at anvilcom.com (phil) Date: Thu, 30 Jun 2005 16:19:10 -0500 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: <42C461CE.7070204@anvilcom.com> Python is in my opinion the best "all-purpose" language ever designed ( lisp is extremely cool but not as all purpose.) Much more elegant than perl and far far easier to do cool things than java (java is c++ on valium). HOWEVER, "all purpose" needs a little disclosure. A well coded C program may be 100 times faster than Python. C forces you to learn some things about relative addressing and memory management. C is pretty much required for interrupt handling. Python is coded in C. (everthing is coded in C, including C) The C language embodies a language design philosophy which has influenced everything for 30 years. So Python is just a wonderful way to learn about things like algorithms, with relatively little pain. But the bottom line for a would be computer scientist is that Python is sort of like a model or an abstraction of C (which itself is a very weak (but convenient) model of the CPU) IMHO There probably is NO college where you can get out of C++ and Java. Too bad. xeys_00 at yahoo.com wrote: > I posted a article earlier pertaining programming for my boss. Now I am > gonna ask a question about programming for myself. I just finished my > first C++ Class. Next semester is a class on encryption(and it's > probably gonna be a math class too). And finally back in programming in > the fall with C++ and Java 1. The C++ will cover pointers, and linked > lists, sorting algorithms, etc... I run linux and OS X. I have read in > the old days that C was used for everything. It was a systems > programming language, and also did a lot of the same stuff Bash scripts > and perl do now. So, in that era, C did it all, from short to tall. My > question is, can Python "do it all"? I am wondering what to learn as my > scripting language. I have read that perl is good up to about 250 > lines, and after that it gets kind of hairy. However, from what little > I have heard about Python, it's very well suited for readability due to > the whitespace requirements of the language, and very good for large > projects due to it's large amount of modules and it's object oriented > structure. I would like opinions as to the suitability of Python as a > general purpose language for programming unix, everything from short > scripts to muds. Thanks for your patience, opinions, and comments. > > Xeys > > From no.spam at thanks.com Tue Jun 21 10:23:33 2005 From: no.spam at thanks.com (Mike P.) Date: Wed, 22 Jun 2005 00:23:33 +1000 Subject: UML to Python/Java code generation References: <873brhufez.fsf@hector.domek> <1119066144.174522.193340@f14g2000cwb.googlegroups.com> <42B71FE6.1020107@carmen.se> Message-ID: <42b822e7$0$29752$afc38c87@news.optusnet.com.au> "Magnus Lycka" wrote in message news:42B71FE6.1020107 at carmen.se... > James wrote: > > The brain may be fine for generating Python from UML but it is MANY > > MANY orders of magnitude harder to generate UML from code with just > > your brain than using a tool (usually zero effort and error free) no > > matter how good you are at Python. > > I've really only used Rational Rose, but that tool is > really limited in both directions. Class structure to > class diagrams work both ways (not for Python, but for > Java and C++ at least) but that's just a tiny part of > UML. > > I don't expect any tool to do anything meaningful about e.g. > use case diagrams, but what about activity diagrams, sequence > diagrams, collaboration diagrams and state diagrams? > > I agree that the brain is poor at such things, but I doubt > that any current tool is much better except for trivial > subsets of UML. Have a look at Enterprise Architect from Sparx Systems (http://www.sparxsystems.com.au). It is a really nice UML tool that is also affordable. I have also used Rational Rose since about 96-97, and although it doesn't have Python support for code generation, it most likely isn't a huge job to modify one of the existing code generation templates (say the Java one) to generate Python from the class diagrams. Enterprise Architect has a separate free downloadble plug-in which can generate Python. See: http://sparxsystems.com.au/resources/mdg_tech/ Enterprise Architect is also much cheaper than Rose, and they can both do C++ and Java. Also, both of these tools have VBA/COM interfaces. What this means is that you can control them and read data directly from them using the win32 python extension models. I haven't tried it with EA, but a couple of years ago I wrote Python scripts that controlled Rose. I did stuff like creating UML diagrams on the fly including changing colours and shapes, and also reading data from UML models. The Rose Extensibility Interface (REI) is very well documented. One could potentially write Python scripts coupled with some Python introspection/reflection code to automatically generate and reverse engineer (and document) Python <-> UML. It was always something I wanted to do but never got around to it. Mike From JOHNWUN at aol.com Mon Jun 27 18:36:03 2005 From: JOHNWUN at aol.com (Grooooops) Date: 27 Jun 2005 15:36:03 -0700 Subject: pulling multiple instances of a module into memory In-Reply-To: <1119881167.255259.251880@f14g2000cwb.googlegroups.com> References: <1119881167.255259.251880@f14g2000cwb.googlegroups.com> Message-ID: <1119911763.863269.137460@g43g2000cwa.googlegroups.com> in spam.py, how about something like this: try: eggs.someFunction() except: import eggs From gvandyk.nospam at agileworks.net Thu Jun 30 01:36:22 2005 From: gvandyk.nospam at agileworks.net (Gerrit van Dyk) Date: Thu, 30 Jun 2005 07:36:22 +0200 Subject: ANN: PyGaim released - Gaim Python plugin Message-ID: PyGaim has been released. Summary: Gaim Python plug-in. The product provides developers with the capability to develop python plugins for Gaim This release is just a get it out there release and a lot of polishing still needs to be done. However, it does enable a python developer to develop gaim plugins using python as the programming language. The current packages is available from http://sourceforge.net/projects/pygaim ToDo: Web page CVS Instructions on installing and using More examples A interface to the gaim gui using pygtk Lots of other stuff. The mailing list should be up in the next 24 hours From dreamingpython at 163.com Wed Jun 1 22:37:08 2005 From: dreamingpython at 163.com (ÒÊÃÉɽÈË) Date: Thu, 2 Jun 2005 10:37:08 +0800 Subject: where to find the doc about python regular expression? Message-ID: thanks From exarkun at divmod.com Fri Jun 24 21:42:48 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 24 Jun 2005 21:42:48 -0400 Subject: Newbie question: SOLVED (how to keep a socket listening), but still some questions In-Reply-To: <11bpd9on9phitad@corp.supernews.com> Message-ID: <20050625014248.26278.1402372286.divmod.quotient.87@ohm> On Sat, 25 Jun 2005 01:36:56 -0000, Grant Edwards wrote: >On 2005-06-25, Giovanni Tumiati wrote: > >> (2)Does one have to do a socket.shutdown() before one does a >> socket.close?? > >No. > >[I've never figured out why one would do a shutdown RDWR >rather than close the connection, but I haven't put a lot of >thought into it.] shutdown actually tears down the TCP connection; close releases the file descriptor. If there is only one file descriptor referring to the TCP connection, these are more or less the same. If there is more than one file descriptor, though, the difference should be apparent. Jp From http Wed Jun 22 16:09:51 2005 From: http (Paul Rubin) Date: 22 Jun 2005 13:09:51 -0700 Subject: PEP 343, second look References: Message-ID: <7xhdfq2lww.fsf@ruckus.brouhaha.com> Ron Adam writes: > > A new statement is proposed with the syntax: > > with EXPR as VAR: > > BLOCK > > Here, 'with' and 'as' are new keywords; EXPR is an arbitrary > > expression (but not an expression-list)... > > How is EXPR arbitrary? Doesn't it need to be or return an object that > the 'with' statement can use? (a "with" object with an __enter__ and > __exit__ method?) That's not a syntactic issue. "x / y" is a syntactically valid expression even though y==0 results in in a runtime error. From ilochab at gmail.com Wed Jun 29 06:31:48 2005 From: ilochab at gmail.com (ilochab at gmail.com) Date: 29 Jun 2005 03:31:48 -0700 Subject: Reading output from a child process non-blockingly In-Reply-To: References: Message-ID: <1120041108.374630.238410@g43g2000cwa.googlegroups.com> Yuan HOng ha scritto: > In my program I have to call an external program and parse its output. > For that I use the os.popen2 function, and then read the output > stream. > > But the complexity is that the external program gives back its output > in a piecemeal manner, with long delays between the outputs. In the > main program I want to therefore read the output in a non-blocking > manner, to read as many bytes as the child process is spitting out. > > The question is, how can I achieve that? > What about using a thread to control the child process? Licia From thomasbartkus at comcast.net Wed Jun 22 12:38:34 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 22 Jun 2005 11:38:34 -0500 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: Will McGugan" wrote in message news:42b97240$0$24467$da0feed9 at news.zen.co.uk... > Hi, > > I'd like to write a windows app that accesses a locally stored database. > There are a number of tables, the largest of which has 455,905 records. > > Can anyone recommend a database that runs on Windows, is fast / > efficient and can be shipped without restrictions or extra downloads? > > I have googled and found plenty of information on databases, its just > that I dont have enough experience with databases to know which one is > best for my task! If you are writing strictly for the MS Windows platform And If the database is running single user with a "locally stored database" on a Windows workstation. Then The MS Access file based (.mdb) system is hard to argue with. You wouldn't have to distribute the (rather expensive) Access application since this is little more than a front for the underlying DAO/ADO database libraries that are built into the warp and woof of MS Windows. Your Python application can address the DAO or ADO directly as these will libraries will be pre-installed and/or freely available for MS Windows. Fast, freely available, no license restrictions, and no need for extra downloads for a reasonably recent (Win2000, XP) operating system. On the other hand, if operating system portability were a concern (as it should be!), I might suggest MySQL. A Python/MySQL application can jump between Windows to Linux (all flavors!) to Unix to BSD without need to alter a single line of code. You were writing a Python app, weren't you :-) Thomas Bartkus From igorcarron at gmail.com Sat Jun 4 16:13:20 2005 From: igorcarron at gmail.com (igorcarron at gmail.com) Date: 4 Jun 2005 13:13:20 -0700 Subject: Grand Challenge Pegasus Team: Programming Pegasus Bridge 1 ? Message-ID: <1117915995.759559.240730@g47g2000cwa.googlegroups.com> Folks, In a previous post[*] we made an announcement about the release of the drive-by-wire code for our entry in the DARPA Grand Challenge. We will do more in the future (including more data and more code). With regards to our building the full autonomous code, things are going along well. However, the somewhat large traffic on our web site had us thinking: Provided we give a good HOW-TO/API, would there be any interest from anybody to try their code on our vehicle as long as it is in Python and safe to run ? Many people think of way to deal with the programming side of road-following and collision avoidance at 60 mph, but very few have the time to build a vehicle that can make these concepts a reality. In order to respond to this, I was thinking of a possibility where somebody would submit a code, pay $200 and we would try it on a closed circuit. Then the programmer would be getting all the data attendant to the vehicle driving itself through the course following their programs? The pros for us: - raise some money for the vehicle - identify potentially better algorithms -> identify people we would like to associate ourselves with. The cons for us: - this is time not dedicated to focusing on the race - issues with proprietary code/IP - issues with safety - coordination with many parties Right now I am thinking the cons are overwhelming, what do y'all think ? Igor. [*] http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/5f78e2ecb3e9139d/af28daca5e385af3#af28daca5e385af3 From cookedm+news at physics.mcmaster.ca Fri Jun 10 13:53:27 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 10 Jun 2005 13:53:27 -0400 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> <3gpsl0Fdhq0mU1@individual.net> <42A94EC4.8020106@cosc.canterbury.ac.nz> Message-ID: Robert Kern writes: > greg wrote: >> David M. Cooke wrote: >> >>>>To solve that, I would suggest a fourth category of "arbitrary >>>>ordering", but that's probably Py3k material. >>> >>>We've got that: use hash(). >>>[1+2j, 3+4j].sort(key=hash) >> What about objects that are not hashable? >> The purpose of arbitrary ordering would be to provide >> an ordering for all objects, whatever they might be. > > How about id(), then? > > And so the circle is completed... Or something like def uniquish_id(o): try: return hash(o) except TypeError: return id(o) hash() should be the same across interpreter invocations, whereas id() won't. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From newsgroups at jhrothjr.com Thu Jun 16 08:22:00 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 16 Jun 2005 06:22:00 -0600 Subject: __str__ vs __repr__ References: <42b021ba$1@griseus.its.uu.se> <11b16e3mld1s9b7@news.supernews.com> <1118898421.887013@yasure> Message-ID: <11b2rnf9his2qd9@news.supernews.com> "Donn Cave" wrote in message news:1118898421.887013 at yasure... > Quoth "John Roth" : > ... > | str() should be something that's meaningful to a human being when > | it's printed or otherwise rendered. > > I can't believe how many people cite this explanation - meaningful, > friendly, pretty to a human being. What on earth does this mean, > that couldn't be said more unambiguously? > > According to my impression of common applications for Python programs, > rarely would anyone be looking at the output for esthetic gratification. > I mean, imagine your users casting an appraising eye over the contours > of a phrase emitted by the program, and praising the rhythmic effect of > the punctuation it chose to use, or negative space created by tabs. heh. > > Whether for human eyes or any destination, properly formed output will > carry the information that is required for the application, in a complete > and unambiguous way and in the format that is most readily processed, > and it will omit extraneous information. Are we saying anything other > than this? I thought that's what I said. I fail to see how you derive any other meaning from it. Possibly less verbiage and a concerete example of how "meaningful" equates to "esthetics that obfustificate understanding" and does not equate to "immediately useable, without having to wade through a lot of irrelvant mental transformations" would help my understanding. John Roth > > Donn Cave, donn at drizzle.com From simon.brunning at gmail.com Fri Jun 3 04:34:57 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 3 Jun 2005 09:34:57 +0100 Subject: Console Scripts In-Reply-To: <1117786864.925308.59260@o13g2000cwo.googlegroups.com> References: <1117786864.925308.59260@o13g2000cwo.googlegroups.com> Message-ID: <8c7f10c60506030134457b1896@mail.gmail.com> On 3 Jun 2005 01:21:04 -0700, Prema wrote: > Just something which will be a simple answer for someone ..... > With an interactive python script, sometimes it seems necessary to > clear the terminal in order to provide a clear presentation to users > > With Bash then we just do a 'clear' statement but this does not seem to work well in python. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3edf6589c533f78e -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From kent37 at tds.net Fri Jun 24 06:18:30 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 06:18:30 -0400 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: References: <11bh7ffsps4ea3@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> <1f7befae05062309012e86599d@mail.gmail.com> Message-ID: <42bbdd52$1_1@newspeer2.tds.net> Robert Kern wrote: > > And floating point is about nothing if not being usefully wrong. > +1 QOTW and maybe it could be worked into the FAQ about floats as well :-) http://www.python.org/doc/faq/general.html#why-are-floating-point-calculations-so-inaccurate Kent From mwm at mired.org Sun Jun 12 21:24:17 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 12 Jun 2005 20:24:17 -0500 Subject: Sending mail from 'current user' in Python References: <3gsve7Fe8957U1@individual.net> <863brp6c11.fsf@guru.mired.org> <42AC1B7D.8090502@abo.fi> Message-ID: <86aclv122m.fsf@guru.mired.org> Marcus Alanen writes: > Mike Meyer wrote: >>>Finally, if at all possible I'd also like to get this working on >>>Windows, so I'd rather stick with the standard smtplib if I can. >> smtplib needs an SMTP server to connect to. For unix systems, this is >> typically localhost. What do you use for Windows systems? Or are you >> connecting to your machine to deliver the mail? > I'd be very surprised if the typical SMTP server is localhost on > unix-like computers. On reflection, you're right. It was the way I described when I started working with Unix, and I still configure all my Unix systems that way. But recently there's been move to have no servers configured by default. I've been bit by this, now having to enable TCP on Postgres by every time I upgrade the server. So most modern Unix systems probably come out of the box without a local SMTP listener. > Rather, sendmail is configured to transport the message to > company/university mailserver(s). Sendmail? Don't you mean qmail/postfix/exim? > If that happens to fail, > the mail is put on the queue at localhost, and transported later > (e.g. via a cronjob) to the server. At no point is there a server on > localhost involved. Of course, not everybody's computer is on such a > network and a sendmail server may indeed be running on localhost, but > that's not a very informed guess. Let the sendmail program take care > of those details. Well, maybe you do mean sendmail. The other MTAs typically aren't that configurable. qmail, for instance, always queues messages to the local disk if they are bound for another host. In lieue of the current discussion, this stuff doesn't matter. All of these MTAs come with a "sendmail" program designed specifically so that programs that invoke sendmail to arrange delivery of a message will continue work if you replace the system sendmail with their version. On FreeBSD, this has been carried a step further: the system sendmail is a wrapper that reads /etc/mail/mailer.conf to figure out what sendmail binary to invoke, so that users don't have to deal with replacing the system sendmail, or worry about accidently overwriting the replaced system sendmail if they upgrade their system. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From pdemb at gazeta.pl Sat Jun 4 12:18:26 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sat, 04 Jun 2005 18:18:26 +0200 Subject: idiom for constructor? References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> <87acm6e9ei.fsf@hector.domek> <8764wue8t0.fsf@hector.domek> Message-ID: <87wtpaayel.fsf@hector.domek> Steven Bethard writes: > Peter Dembinski wrote: >>class A: >> def __init__(self, a, b, c, d): >> initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d} >> for param in initial.keys(): >> exec "self.%s = initial['%s']" % (param, param) > > This is not a good use case for exec. Use setattr: OK, true. >From the other side: what are the usual uses of 'exec'? From Xavier.Decoret at imag.fr Tue Jun 14 03:25:11 2005 From: Xavier.Decoret at imag.fr (=?ISO-8859-1?Q?Xavier_D=E9coret?=) Date: Tue, 14 Jun 2005 09:25:11 +0200 Subject: Controlling assignation In-Reply-To: <42aded8f$0$31916$636a15ce@news.free.fr> References: <42aded8f$0$31916$636a15ce@news.free.fr> Message-ID: <42AE8657.9070806@imag.fr> Bruno Desthuilliers a ?crit : > Xavier D?coret a ?crit : > (snip) > >> What I wanted to do is something like this: >> >> def change(x,v): >> x = v >> >> class A(object): >> def __init__(self,v): >> self.x = v >> >> a = A(3) >> print a.x # displays 3 >> change(a.x,4) >> print a.x # still displays 3 >> >> >> It may seem weird, > > > It does > >> but I ensure there is a reason for doing this. > > > I really wonder what it can be ??? It's the ability to develop the equivalent of GeoNext (and much more) in Python with a very nice syntax. > > You could achieve the same effect with: > > class A( object): > def __init__(self, value): > self.value = value > > a = A(3) > a.value = 4 > a.value > => 4 > Of course, and even simpler ;-) print "4" More seriously, try to do this with your simpler approach. a = A(4) b = A(lambda : a.x+5) a.x = 2 print b.x # I want this to be 7, not 9 > And it's *much* more simple/readable/efficient. > > Ever googled for "evolution of a programmer" ?-) > > Not to brag, but I think I know what programming is. Google for my name. C'est bien un commentaire de francais ca ;-) From steve at REMOVETHIScyber.com.au Mon Jun 6 12:00:26 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 07 Jun 2005 02:00:26 +1000 Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: On Sun, 05 Jun 2005 03:57:29 -0400, Terry Reedy wrote: > "Robert Kern" wrote in message > news:d7u737$8or$1 at sea.gmane.org... >> Mike Meyer wrote: >>> I've heard people argue otherwise on this case. In particular, if you >>> allow an employee to use your GPL'ed-but-not-distributed software, >>> they are the end user, and have all the rights granted by the GPL. So >>> they can distribute the software - possibly to your >>> competitors. Employment contracts can't prohibit this, because the GPL >>> specifically disallows "distribution" (allowing your employee to use >>> the software) under licenses that restrict the rights granted by the >>> GPL. >> >> Well, the FSF at least thinks that internal use within an organization >> does not constitute distribution. > > The fact that GPL effectively discriminates in favor of large corporations > (and other organizations) and programmers employed by such (versus those > contracting with such), is something I don't like about it. I'm sorry, I don't follow your reasoning here. How does the GPL discriminate in favour of large corporations? What advantage does the corporation get that I don't get? The way I see it, if my left hand and right hand both use the software, that isn't distribution. And if Acme Inc's accounting department and sales department both use the software, that shouldn't count as distribution either, in precisely the same way that there has been no transfer of ownership when Fred from Accounting takes an unused computer from Sales and starts using it himself. > This seems > contrary to the spirit of the thing. It certainly supports the myth that > organizations are 'people'. By law, corporations (and possibly some other organisations) *are* people. Not natural people like you or I, but nevertheless people. For good or bad, this is the legal fact (or perhaps "legal fiction") in most countries, and not a myth. > What if a whole country claimed to be 'one organization' (as the entire > Soviet Union once was, in a real sense). I doubt that was ever the case, not even in a figurative sense. But for the sake of the argument, I'll accept that (say) the country of Freedonia might claim the entire population of Freedonia to be a single organisation. > Could it distribute modifications > 'privately' while denying such to the rest of the world? Freedonia is a country. Unless some other country takes them on, they can do whatever they like within their borders because they make the laws. Of course, they may run foul of international law, and may suffer the consequences, which may range from angry words in the UN to trade sanctions to a blockade all the way to invasion (although probably not over some random piece of GPLed code). But this is hardly a problem unique to the GPL. What if you publish code under the BSD licence, and Freedonia rips your copyright notice out of it and tries to pass it off as their own creation? What if Microsoft licences Freedonia some software under Shared Source, and they promptly modify and distribute the source code? When nation states decide they are beyond the law, or subject only to whatever laws it is convenient for them to follow, no licence will protect you. -- Steven From donn at drizzle.com Sat Jun 18 10:54:47 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 18 Jun 2005 14:54:47 -0000 Subject: Loop until condition is true References: <1119074614.700809@yasure> Message-ID: <1119106486.799186@yasure> Quoth Peter Otten <__peter__ at web.de>: ... | 'until' in C is actually | | do | statement | while (expression); Oops. Well, QED - I sure don't need it often. Donn Cave, donn at drizzle.com From whimsica at aol.com Wed Jun 22 04:33:42 2005 From: whimsica at aol.com (whimsica) Date: 22 Jun 2005 01:33:42 -0700 Subject: C++ ActiveX python javascript communication trouble. Message-ID: <1119429222.073229.269720@g47g2000cwa.googlegroups.com> I'm investingating a c++ api, Panda3d.com, that has a python binding. I want to convert this api into an ACtiveX control so it will run on the web. When I do so I want to use Microsoft Script Control to call api routines from Javascript in the browser. Let's say I write up a game in python with my own functions. Then I embed it in a web page and I want to call my functions from javascript? How can I do it. Script control allows you to bind api functions to javascript, but not the functions in my python file. Adobe Atmoshere a 3D application that ran in a web page, had a javascript binding. You could write code in a javascript file, and it would be interpreted during start-up. After that, I could send function calls in the form of a string from the browser to atmosphere. How did this work? Is the api aware of the python functions and variables after it is loaded up? Confused, Dan From fredrin at ifi.uio.no Tue Jun 28 05:54:41 2005 From: fredrin at ifi.uio.no (Fredrik Normann) Date: Tue, 28 Jun 2005 11:54:41 +0200 Subject: Reading files in /var/spool/rwho/whod.* In-Reply-To: References: Message-ID: Fredrik Normann wrote: > Hello, > > I'm trying to read the binary files under /var/spool/rwho/ so I'm > wondering if anyone has done that before or could give me some clues on > how to read those files. I've tried to use the binascii module without > any luck. A friend of mine made this C-program, that does the trick :) #include #include #include #include #include #include #include #include #include #ifdef SOL #include #else #include #endif int main (int argc, char **argv) { char *filename, *binary; FILE *fp; struct whod entry; struct outmp who; size_t ret; size_t cnt = 0; char *user = (char*) malloc (8); char *timestr = (char*) malloc (512); char *hostname = (char*) malloc (512); int hostlen, ulen; size_t prefix, we_len; hostlen = 0; ulen = 0; struct timeval now; struct tm *tptr; time_t t; binary = *argv; ret = gettimeofday (&now, 0); if (ret < 0) { perror ("Error getting time of day"); exit (2); } if (argc < 2) { printf ("%s: ERROR, no whod file specified\n", binary); exit (1); } filename = *(argv + 1); fp = fopen (filename, "r"); if (fp == NULL) { perror ("Error opening file"); exit (3); } #ifdef SOL ret = fread (&entry, 1, sizeof (entry), fp); #else ret = fread_unlocked (&entry, 1, sizeof (entry), fp); #endif if (ret < 0) { perror ("Error reading file"); exit (4); } prefix = offsetof (struct whod, wd_we) / sizeof (struct whoent); we_len = ret / sizeof (struct whoent) - prefix; /* Find lengths of strings */ for (cnt = 0; cnt < we_len; cnt++) { who = entry.wd_we[cnt].we_utmp; strncpy (user, who.out_name, 8); if (strlen (user) > ulen) ulen = strlen (user); if ((strlen (entry.wd_hostname) + strlen (who.out_line) + 1) > hostlen) hostlen = strlen (entry.wd_hostname) + strlen (who.out_line) + 1; } for (cnt = 0; cnt < we_len; cnt++) { who = entry.wd_we[cnt].we_utmp; strncpy (user, who.out_name, 8); strncpy (hostname, entry.wd_hostname, 512); strcat (hostname, ":"); strncat (hostname, who.out_line, 8); t = now.tv_sec - ntohl (entry.wd_we[cnt].we_idle); entry.wd_we[cnt].we_idle = ntohl (entry.wd_we[cnt].we_idle) / 60; printf ("%-*s %-*s", ulen, user, hostlen, hostname); if (entry.wd_we[cnt].we_idle >= 0) { tptr = localtime (&t); strftime (timestr, 512, "%a %b %d %H:%m", tptr); printf (" %s ", timestr); printf ("%5d:%02d", entry.wd_we[cnt].we_idle / 60, entry.wd_we[cnt].we_idle % 60); } printf ("\n"); } fclose (fp); } From idontneednostinkinid at yahoo.com Wed Jun 1 13:50:59 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 10:50:59 -0700 Subject: idiom for constructor? Message-ID: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Is there a nice Python idiom for constructors which would expedite the following? class Foo: def __init__(self, a,b,c,d,...): self.a = a self.b = b self.c = c self.d = d ... I would like to keep the __init__ parameter list explicit, as is, rather than passing in a dictionary, as I want the code to be explicit about what arguments it expects... in effect enforcing the right number of arguments. From rkern at ucsd.edu Fri Jun 3 22:23:14 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 03 Jun 2005 19:23:14 -0700 Subject: Scope In-Reply-To: References: Message-ID: Elliot Temple wrote: > Nothing is wrong with it in this case. I just want to know if Python > can do what I said. With a number of difficult hacks, yes. Passing around objects as namespaces, however, is vastly easier and far superior. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From pwilkins at noaddress.org Fri Jun 24 15:19:02 2005 From: pwilkins at noaddress.org (pwilkins) Date: Fri, 24 Jun 2005 15:19:02 -0400 Subject: Newbie question: how to keep a socket listening? References: Message-ID: On Fri, 24 Jun 2005 13:59:19 -0400, pwilkins wrote: > if data == 'q': > ##disconnect client but keep waiting for connections > ... > client.close() Sorry - made a mistake in my posting... the above should have been: if data == 'q': ##disconnect client but keep waiting for connections ... client.close() break # return to the wait for connections while loop Again thanks... From chinook.nr at tds.net Sun Jun 26 21:03:45 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 26 Jun 2005 21:03:45 -0400 Subject: OO approach to decision sequence? References: <1119820490.656027.249730@g14g2000cwa.googlegroups.com> <1119823091.503532.60180@g44g2000cwa.googlegroups.com> Message-ID: <0001HW.BEE4C8B100087F76F0407550@news.gmane.org> On Sun, 26 Jun 2005 17:58:11 -0400, George Sakkis wrote (in article <1119823091.503532.60180 at g44g2000cwa.googlegroups.com>): > "Paul McGuire" wrote: > >> Lee C - >> >> Here is a technique for avoiding the if-elseif-elseif...-else method >> for building objects. It is a modified form of ChainOfResponsibility >> pattern, in which you have a collection of factory methods that all >> have a common signature, or a collection of Factory classes that all >> implement a "makeObject" method. These common methods probably take a >> string, and return a generic object. Fortunately, such type >> flexibility is *very* easy in Python. :) >> >> Example: >> I want to convert individual strings to native data types. I want to >> detect integers, reals, complex numbers, and booleans (indicated by >> 'True' or 'False'). This is kind of similar to a parsing problem, but >> it could also be used for deserializing or unpickling data of an >> unknown original type. >> >> Note the special treatment I have to go through with boolean values - I >> needed to write a special makeBool routine, since Python will take any >> non-empty string to be True, when what I want is 'True' to yield true >> and 'False' to yield false. >> >> Hope this gives you some alternative ideas to your cascading if's. >> >> -- Paul >> >> >> def makeBool(s): >> if s in ('True','False'): >> return s == 'True' >> raise ValueError >> >> converters = [ int, float, complex, makeBool, str ] >> >> def makeObject(stringVar): >> for conv in converters: >> try: >> val = conv(stringVar) >> except Exception: >> continue >> else: >> break; >> return val >> >> def test(s): >> val = makeObject(s) >> print s, val, type(val) >> >> test('1') >> test('1.0') >> test('1+2j') >> test('1+0j') >> test('True') >> test('False') >> test('A') >> >> prints: >> 1 1 >> 1.0 1.0 >> 1+2j (1+2j) >> 1+0j (1+0j) >> True True >> False False >> A A > > Nice technique. Something that needs to be pointed out is that the > order of the converters *is* important; int takes precedence over > float, which take precedence over complex and bool takes precedence > over string. More succinctly: > { int -> float -> complex } > { bool -> str } > In general the converters will form a strict partially ordered set, so > the list of converters should be a topological sort of the respective > DAG. > > George > > Ah yes, there is more than one way to skin a cat :~) and your samples are helping me get a better grasp of both Python and OOP in such. I find both Bengt's and Paul's variation on a theme understandable (I must be making progress :~) and interesting. I must admit that I did have to look twice at Bengt's clever little slice on 'an' though. I had already worked my way through this though, so they were that much more understandable. Actually, I'm using a superclass as a factory, similar to Steve B's example (as modified by someone I can't find the name of). The difference is that my criteria does not map easily to class names so I have the verbose decision sequence in my superclass. Of course, if I want to get really fancy, I could use the COR pattern within such. I'm making more hay out of this one little pasture than I expected (i.e. increasing my understanding) thanks to all of you. I'm going to have to start writing down names (rather than rely on this ol head) so I can properly thank everyone - like those clarifying other examples. At some point I'll put up the original top-down and OO refactored versions of my little utility in the hope that I will learn even more from criticism of my efforts. The "new deal" top-down structured programming encountered in my continuing post grad work at BU in the 1960s was easier to get a solid handle on ;') Much appreciated, Lee C "Wonder rather than doubt is the root of knowledge." --Abraham Joshua Heschel From lambacck at gmail.com Wed Jun 8 14:46:23 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Wed, 8 Jun 2005 14:46:23 -0400 Subject: [Pyrex] Allocating an array.array of a specific length in pyrex In-Reply-To: References: <396556a2050608111658e56203@mail.gmail.com> Message-ID: I replaced: a = array.array('B', , [0] * (pixels * 2)) with: a = PyString_FromStringAndSize(NULL, pixels * 2) and got: C:\work\testing\plink_o_ip>python ycbycr.py Traceback (most recent call last): File "ycbycr.py", line 62, in ? ycbycr = image2ycbycr(im) File "ycbycr.py", line 38, in image2ycbycr return _ycbycr.ycbcr2ycbycr(w, h, ycbcrim.tostring()) File "_ycbycr.pyx", line 42, in _ycbycr.ycbcr2ycbycr res = get_w_buffer(a, &out_str, &buffer_len) TypeError: Cannot use string as modifiable buffer Strings are not mutable so this is not going to work for me :( Is there a way to allocate a python buffer object and give that to array.array or a string object? -Chris On 6/8/05, Chris Lambacher wrote: > The memory is not temporary, I am passing it out as an array, thus the > malloc/free route will require double allocation(once for malloc/free, > once for array.array). I am not using string because when I tried to > pass the data in as string, pyrex complained about the conversion. > However, I could probably use the same PyObject_AsReadBuffer function > call to get at the data passed in to the function as a string and then > pass it out as a string as well using the interface suggested ( > PyString_FromStringAndSize and PyString_AsString ). Perhapse I need > to substitute PyObject_AsWriteBuffer instead of PyString_AsString in > order for my changes to get propegated back to the string object? > > -Chris > > > On 6/8/05, Adam Langley wrote: > > On 6/8/05, Chris Lambacher wrote: > > > My question is, is there a better way to > > > allocate the memory for the array.array object than: > > > a = array.array('B', [0] * (pixels * 2)) > > > > cdef unsigned char *buffer > > temp_string = PyString_FromStringAndSize(NULL, length) > > buffer = PyString_AsString(temp_string) > > > > That's one way to do it. But it looks like you just want an area of > > memory so why not: > > > > cdef extern from "stdlib.h": > > ctypedef unsigned long size_t > > void *malloc(size_t size) > > void free(void *mem) > > > > ? > > > > AGL > > > > -- > > Adam Langley agl at imperialviolet.org > > http://www.imperialviolet.org (+44) (0)7906 332512 > > PGP: 9113 256A CC0F 71A6 4C84 5087 CDA5 52DF 2CB6 3D60 > > > > > -- > Christopher Lambacher > lambacck at computer.org > -- Christopher Lambacher lambacck at computer.org From jwaixs at gmail.com Sat Jun 25 08:03:44 2005 From: jwaixs at gmail.com (jwaixs) Date: 25 Jun 2005 05:03:44 -0700 Subject: execute python code and save the stdout as a string Message-ID: <1119701023.896260.4770@g47g2000cwa.googlegroups.com> Hello, I've a question. Can I execute a part of a python code and put it's output in a string? Something like this: s = "" s = exec """print "Hello World" """ print s Greetz, Noud From http Sun Jun 12 02:28:56 2005 From: http (Paul Rubin) Date: 11 Jun 2005 23:28:56 -0700 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> <7xekb84rsa.fsf@ruckus.brouhaha.com> <7x7jh0l5kg.fsf@ruckus.brouhaha.com> Message-ID: <7xwtp09jh3.fsf@ruckus.brouhaha.com> Andrew Dalke writes: > I know little about it, though I read at > http://goathack.livejournal.org/docs.html > ] LiveJournal source is lots of Perl mixed up with lots of MySQL > > I found more details at > http://jeremy.zawodny.com/blog/archives/001866.html > > It's a bunch of things - Perl, C, MySQL-InnoDB, MyISAM, Akamai, > memcached. The linked slides say "lots of MySQL usage." 60 servers. LM uses MySQL extensively but what I don't know is whether it serves up individual pages by the obvious bunch of queries like a smaller BBS might. I have the impression that it's more carefully tuned than that. > I don't see that example as validating your statement that > LAMP doesn't scale for mega-numbers of hits any better than > whatever you might call "printing press" systems. What example? Slashdot? It uses way more hardware than it needs to, at least ten servers and I think a lot more. If LJ is using 6x as many servers and taking 20x (?) as much traffic as Slashdot, then LJ is doing something more efficiently than Slashdot. > How permanent though does the history need to be? Your > approach wipes history when the user clears the cookie and it > might not be obvious that doing so should clear the history. The cookie is set at user login and it only has to persist through the login session. It's not as if the info only exists in the cookie and nowhere else. > > As for "big", hmm, I'd say as production web sites go, 100k users is > > medium sized, Slashdot is "largish", Ebay is "big", Google is huge. > > I'ld say that few sites have >100k users, much less > daily users with personalized information. As a totally made-up > number, only few dozens of sites (maybe a couple hundred?) would > need to worry about those issues. Yes, but for those of us interested in how big sites are put together, those are the types of sites we have to think about ;-). I'd say there's more than a few hundred of them, but it's not like there's millions. And some of them really can't afford to waste so much hardware--look at the constant Wikipedia fundraising pitches for more server iron because the Wikimedia software (PHP/MySQL, natch) can't handle the load. > If that's indeed the case then I'll also argue that each of > them is going to have app-specific choke points which are best > hand-optimized and not framework optimized. Is there enough > real-world experience to design a EnterpriseWeb-o-Rama (your > "printing press") which can handle those examples you gave > any better than starting off with a LAMP system and hand-caching > the parts that need it? Yes, of course there is. Look at the mainframe transaction systems of the 60's-70's-80's, for example. Look at Google. Then there's the tons of experience we all have with LAMP systems. By putting some effort into seeing where the resources in those things go, I believe we can do a much better job. In particular, those sites like Slashdot are really not update intensive in the normal database sense. They can be handled almost entirely with some serial log files plus some ram caching. At that point almost all the SQL overhead and a lot of the context switching can go away. From ramen at lackingtalent.com Tue Jun 28 14:23:25 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 28 Jun 2005 11:23:25 -0700 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: <7Dgwe.89653$yV4.25604@okepread03> Sakesun Roykiattisak wrote: > >> What's being ignored is that type information is useful for other things >> than compile type checking. The major case in point is the way IDEs >> such as IntelliJ and Eclipse use type information to do refactoring, code >> completion and eventually numerous other things. A Java programmer >> using IntelliJ or Eclipse can eliminate the advantage that Python >> used to have, and possibly even pull ahead. >> > 1. Automatic refactoring never solve the readability issue. True, but with the aid of automatic refactoring, you can make code more readable, by splitting up classes and functions, giving things better names, etc. Another readability issue in a similar vein is "intellisense" / context-sensitive menus. They allow you to give every class and method really long or confusing names without slowing you down, since you can just pick it from a menu. But I think this has some negative consequences. First, as you've stated, you still have to read the code. Second, you become reliant on these menus, rather than just "flowing". For instance, I almost never have to look up documentation for any of Python's list, dictionary, and string methods. They're short and simple, and they're easy to memorize. I think this is at least partially a consequence of the fact that people type them in, by hand, all the time, so they're designed to be friendly and memorable. > 2. I've never been lucky enough to have enough resource for those IDE. It's worth noting that IntelliJ IDEA has gotten rather slow and bulky with the more recent releases. It used to be pretty quick. Emacs, which was at one point considered a total resource hog, is lean and mean in comparison, and doesn't seem to be expanding much these days... =) Dave From python at rcn.com Mon Jun 27 19:46:02 2005 From: python at rcn.com (Raymond Hettinger) Date: 27 Jun 2005 16:46:02 -0700 Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: <1119915962.214293.142800@g49g2000cwa.googlegroups.com> [Roy Smith] > I also think the published description is needlessly confusing. Why does > it use > > {'one': 2, 'two': 3} > > as the example mapping when > > {'one': 1, 'two': 2} > > would illustrate exactly the same point but be easier to comprehend. The > mapping given is the kind of thing I would expect to see in an obfuscated > programming contest. > > Also, what's the point of the last example: > > dict([(['one', 'two'][i-2], i) for i in (2, 3)]) > > It boils down to passing a list of tuples as an argument, which is already > illustrated by other examples. This is just a complicated and obtuse way > to construct the list of tuples. What does it add to the understanding of > how the dict() constructor works? If you can switch from indignation to constructive criticism, then consider sending a note to Andrew Kuchling suggesting ways to improve the examples. Raymond From jabel at plus.net Mon Jun 20 11:24:28 2005 From: jabel at plus.net (John Abel) Date: Mon, 20 Jun 2005 16:24:28 +0100 Subject: Python choice of database In-Reply-To: <42B6DF1F.2060304@plus.net> References: <42B6DF1F.2060304@plus.net> Message-ID: <42B6DFAC.9030209@plus.net> Just thought of a couple more: SnakeSQL KirbyBase J John Abel wrote: >Gadfly >PySQLite ( requires SQLite library ) > >J > >Philippe C. Martin wrote: > > > >>Hi, >> >>I am looking for a stand-alone (not client/server) database solution for >>Python. >> >>1) speed is not an issue >>2) I wish to store less than 5000 records >>3) each record should not be larger than 16K >> >> >>As I start with Python objects, I thought of using shelve, but looking at >>the restrictions (record size + potential collisions) I feel I should study >>my options a bit further before I get started. >> >> >>Regards, >> >>Philippe >> >> >> >> >> > > > . From cjbottaro at alumni.cs.utexas.edu Fri Jun 3 17:59:20 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Fri, 03 Jun 2005 16:59:20 -0500 Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <1116869986.145116.303340@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: > we just recently on > this forum had someone ask about "polymorphism" when what they really > meant was "overloaded method signatures." (It is even more unfortunate > that language features such as overloaded method signatures and > operator overloading get equated with OOP I've actually heard "overloaded method signatures" be referred to as ad-hoc polymorphism. Aren't there like 4 types of polymorphism: inheritance, ad-hoc, parameter templetization (sp?), and something else...can't remember. -- C From thecollector.2k at gmail.com Thu Jun 30 16:38:44 2005 From: thecollector.2k at gmail.com (The Collector) Date: 30 Jun 2005 13:38:44 -0700 Subject: Controlling WinAMP (WM_COPYDATA problem) References: <1120157311.921062.21570@o13g2000cwo.googlegroups.com> Message-ID: <1120163924.344837.33960@f14g2000cwb.googlegroups.com> Hi, i changed the code to this: ---------------------------------- from win32gui import FindWindow from win32api import SendMessage import struct import array hWnd = FindWindow('Winamp v1.x', None) def packData( dwData, item ): global cds, lpData lpData = array.array('c', item) lpData_ad = lpData.buffer_info()[0] cbData = lpData.buffer_info()[1] cds = array.array('c', struct.pack("IIP", dwData, cbData, lpData_ad) ) cds_ad = cds.buffer_info()[0] return cds_ad def addItemToPlaylist( item ): SendMessage( hWnd, 0x004A, 0, packData( 100, item ) ) file = r"C:\Party Animals - Atomic.mp3" addItemToPlaylist( file ) ---------------------------------- it's working like a charm now... I did found some other mistakes, but the main problem was indeed solved by the 'global' thingy... so simple (/me bangs head against the wall), thanks very much! From lee at example.com Sat Jun 25 12:06:57 2005 From: lee at example.com (Lee Harr) Date: Sat, 25 Jun 2005 16:06:57 GMT Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: >> Higher-order functions like map, filter and reduce. As of Python 3000, >> they're non-python tricks. Sigh - i guess it's time for me to get to know >> list comprehensions a bit better. >> Couldnt there just be a "functional" module ?... from functional import map, filter, reduce From gsakkis at rutgers.edu Sun Jun 26 10:35:12 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 26 Jun 2005 07:35:12 -0700 Subject: noob question References: <42BE37C0.3000306@maudit.net> Message-ID: <1119796512.220953.233900@g14g2000cwa.googlegroups.com> "Konstantin Veretennicov" wrote: > On 6/26/05, Matt Hollingsworth wrote: > > Seems like an _extremely_ elegent language that is very easy to read, so > > I suppose it's not really as much of an issue as it is with other > > languages. Still, I would like to see what other people do and what are > > some good ideas for this kind of thing. > > Nouns-for-variables vs. verbs-for-functions work for me equally well > in Python, C++ and C#. I rarely feel the need for hungarian notation, > but it has it's uses (and abuses); see > http://joelonsoftware.com/articles/Wrong.html > > - kv I second this. Please keep python readable by trying to use plain english words for identifiers and stay away from hungarian notation. If more than one words are required, use a consistent convention (e.g. CamelCase for classes, mixedCase for methods, etc.). See also http://www.python.org/peps/pep-0008.html for some (semi-)standard conventions. George From erik.myllymaki at aviawest.com Fri Jun 24 16:47:18 2005 From: erik.myllymaki at aviawest.com (Erik Myllymaki) Date: Fri, 24 Jun 2005 20:47:18 GMT Subject: trouble with win32serviceutil In-Reply-To: <5aJue.1786098$6l.413556@pd7tw2no> References: <5aJue.1786098$6l.413556@pd7tw2no> Message-ID: <42BC715D.809@aviawest.com> Erik Myllymaki wrote: > I am trying to start and stop a service with python. This used to work > on an NT box but not on this 2003 server machine. (note- using "net stop > myService" and net start myService" from the command line works just > fine). The event viewer does tell me that a "Start command was sent to > myService" but the service never starts. > > ------------------------------------------------------------------------- > > import win32serviceutil > > def service_control(service,action,machine='192.168.1.9'): > if action == 'stop': > try: > win32serviceutil.StopService(service, machine) > return('%s stopped successfully' % service) > except: > return ("Error stopping %s" % (service)) > elif action == 'start': > try: > win32serviceutil.StartService(service, machine) > return('%s started successfully' % service) > except: > return ("Error starting %s" % (service)) > elif action == 'restart': > try: > win32serviceutil.RestartService(service, machine) > return('%s restarted successfully' % service) > except: > return ("Error restarting %s" % (service)) > elif action == 'status': > if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4: > return("%s is running normally" % service) > else: > return("%s is *not* running" % service) > > > if __name__ == '__main__': > machine = '192.168.1.9' > service = 'myService' > action = 'start' > print service_control(service,action,machine) Answering my own question - seems to work i you do not specify machine name: win32serviceutil.StartService(service) instead of win32serviceutil.StartService(service, machine) From mwm at mired.org Mon Jun 13 02:54:53 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 13 Jun 2005 01:54:53 -0500 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: <86mzpuzqyq.fsf@guru.mired.org> Andrea Griffini writes: >>In short, you're going to start in the middle. > > I've got "bad" news for you. You're always in the > middle :-D. That's what I just said. >>Is it really justified to confuse them all >>by introducing what are really extraneous details early on? > > I simply say that you will not able to avoid > introducing them. If they're going to write software > those are not "details" that you'll be able to hide > behind a nice and perfect virtual world (this is much > less true about bus cycles... at least for many > programmers). I disagree. If you're going to make competent programmers of them, they need to know the *cost* of those details, but not necessarily the actual details themselves. It's enough to know that malloc may lead to a context switch; you don't need to know how malloc actually works. > But if you need to introduce them, then IMO is > way better doing it *first*, because that is the > way that our brain works. That's the way *your* brain works. I'd not agree that mine works that way. Then again, proving either statement is an interesting proposition. >>You've stated your opinion. Personally, I agree with Abelson, Sussman >>and Sussman, whose text "The Structure and Interpretation of Computer >>Programs" was the standard text at one of the premiere engineering >>schools in the world, and is widely regarded as a classic in the >>field: they decided to start with the abstract, and deal with concrete >>issues - like assignment(!) later. > > Sure. I know that many think that starting from > higher levels is better. However no explanation is > given about *why* this should work better, and I > didn't even see objective studies about how this > approach pays off. This is of course not a field > that I've investigated a lot. The explanation has been stated a number of times: because you're letting them worry about learning how to program, before they worry about learning how to evaluate the cost of a particular construct. Especially since the latter depends on implementation details, which are liable to have to be relearned for every different platform. > What I know is that every single competent programmer > I know (not many... just *EVERY SINGLE ONE*) started > by placing firmly concrete concepts first, and then > moved on higher abstractions (for example like > structured programming, OOP, functional languages ...). I don't normally ask how people learned to program, but I will observe that most of the CS courses I've been involved with put aside concrete issues - like memory management - until later in the course, when it was taught as part of an OS internals course. The exception would be those who were learning programming as part of an engineering (but not software engineering) curriculum. The least readable code examples almost uniformly came from the latter group. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From idontneednostinkinid at yahoo.com Wed Jun 1 22:49:37 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 19:49:37 -0700 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117676088.978273.272940@g47g2000cwa.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <1117676088.978273.272940@g47g2000cwa.googlegroups.com> Message-ID: <1117680577.332110.241060@g47g2000cwa.googlegroups.com> After I wrote my post I realized I didn't provide enough context of what I'm doing, hence it is not quite clear to any readers why the heck I would want this. The gist is this. I have a number of algorithms that perform the same task. I'm trying to assess which ones work better under which circumstances, which means I'm timing them (interested in *relative* speed, so Python is acceptable). I also have a second app which allows me to "observe" the operation of said algorithms by consuming such emitted debug objects and graphically displaying the information therein. I'm "observing" with a very fine granularity, which means a debug object is emitted between almost every single line. Naturally, if every second line is debug code (or worse, as above, 1 line of real code, 2 lines of debug code), the readability of the algorithm is horrendous, making further development a pain. Since, when I'm NOT observing the algorithms then I'm timing them, I want the debug/observe code to have minimal impact on the runtimes; instantiating some of these debug objects is rather costly. There, hopefully this gives a better picture of my motivation. If anyone can suggest alternate way to structure such code, I'm all ears (... well, eyes, really... :) Your proposal for one-lining the code as "if debug: emit_....." occurred to me, but for readability reasons I want as visually *short* a line as possible, so it doesn't detract from the other code. The C preprocessor was particularly helpful in such "shortening". (e.g., print "foo"; DBG(DbgObj(..)); print "bar";) Hmm, with this setup you can't get any shorter than the instantiation of the DebugObject... which gives me an idea... the "if debug:" could be placed within DebugObjectBase, and all the DebugObjects inherit from it... no... wait... no good, the problem is the following case: ... # real line of code DbgObjFoo(a,b,costly_function(c)) # real line of code On a debugging/observing run, the debugging objects occasionally have their constructor values computed externally, as above, and the proposed solution would not save us from that costly computation. From tdaitx at gmail.com Sat Jun 4 21:11:21 2005 From: tdaitx at gmail.com (=?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=) Date: Sat, 4 Jun 2005 22:11:21 -0300 Subject: No subject In-Reply-To: <1117875121.42a16bb150ac2@mailbox.textualanalytics.com> References: <1117875121.42a16bb150ac2@mailbox.textualanalytics.com> Message-ID: That depends on what "using" a file means. You could check the thread "executing a command" ( http://mail.python.org/pipermail/python-list/2005-June/283963.html) and see if there's something related there, otherwise it would help if you could post what exactly you are trying to do (execute a file, open a file, write into a file, etc). Regards, Tiago S Daitx On 6/4/05, Jatinder Singh wrote: > > Hi guys > I am working in a complex directory structure. I want to use a file (not > .py) > which is in some other directory. I couldn't do it.but if I copy the file > in > the same directory then it is working fine. Can anybody guide me how and > where > to add the path of the file. I have tried it with sys.path but it is not > for > that. > > > -- > Regards, > Jatinder Singh > > " Everyone needs to be loved... especially when they do not deserve it." > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From riccardo_cut1 at cut2_sideralis.net Wed Jun 15 05:50:27 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Wed, 15 Jun 2005 11:50:27 +0200 Subject: dynamic Message-ID: Hi all. It's easier if I show an example first. Say I have class A(object): def speak(self): print 'A!' class B(object): def speak(self): print 'B!' I also have a factory function like this. def foo(kind,*args,**kwds): if kind=='a': return A(*args,**kwds) else: return B(*args,**kwds) I need foo to be a class, so that I could inherit from it and still use it as a factory, so that I can do: Foo('a').speak() Foo('b'.speak() class Final(Foo): def __init__(self,kind,*args,**kwds): super(Foo,self).__init__(kind,*args,*kwds) Can I do it? How ? If it is possible, I'm pretty sure it involves using __new__ on Foo, but I can't figure out how to make it works. Any help is appreciated. Thank you, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From peter at engcorp.com Thu Jun 2 12:30:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 12:30:35 -0400 Subject: Two questions In-Reply-To: <1117728650.316100.291750@g14g2000cwa.googlegroups.com> References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> <3g8kqaFb5v3dU2@individual.net> <1117728650.316100.291750@g14g2000cwa.googlegroups.com> Message-ID: qscomputing at gmail.com wrote: > Thanks to you all for the quick response. > > I've noticed that when I do > $ python myprog.py > the file myprog.pyc file is not created, but the .pyc files for files I > import *are* created. Is this intentional and, if so, how do I get the > myprog.pyc file? I thought the docs covered this, so I left it out. The "main" .py file is not converted to a .pyc file for reasons I can't remember (and don't care... after it, that's just the way it is). If you really need a .pyc for it, the simplest thing to do is "import myprog" from the interactive prompt. The compileall module I mentioned would also be able to do this. -Peter From could.net at gmail.com Tue Jun 28 22:29:30 2005 From: could.net at gmail.com (could ildg) Date: Wed, 29 Jun 2005 10:29:30 +0800 Subject: How to compare two directories? Message-ID: <311b5ce105062819292a8a0ad0@mail.gmail.com> I want to compare 2 directories, and find If all of theire sub-folders and files and sub-files are identical. If not the same, I want know which files or folders are not the same. I know filecmp moudle has cmpfiles function and a class named dircmp, they may help, but I wonder if there is a ready-to-use function in python libs? If not, would somebody like to give me some propositions? Thank you. From listserver at tdw.net Thu Jun 9 17:23:51 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 9 Jun 2005 22:23:51 +0100 Subject: smtpd module References: <42C7E766869C42408F0360B7BF0CBD9B014B6156@pnlmse27.pnl.gov> Message-ID: <001301c56d39$8917f7e0$ccbefea9@twilliams> ----- Original Message ----- From: "Hughes, Chad O" > No, I know how to use the smtplib module and I can send email through > that. However what I want is a the ability to set up a very simple mail > server with python, for some tests that I need to run that just prints > out the message to the standard out and disregards the message. The > smtpd module seems to provide this ability via the DebuggingServer. > According to the documentation that is provided with python the: Already posted this for another thread today, you will be able to make it do what you need in a couple of minutes. If not post back and I'll knock something up :) ----- Original Message ----- From: "Tim Williams" To: Sent: Thursday, June 09, 2005 3:20 PM Subject: Re: Simple SMTP server ----- Original Message ----- From: "Jesse Noller" > I am looking at implementing a simple SMTP server in python - I know > about the smtpd module, but I am looking for code examples/snippets as > the documentation is sparse. > > If anyone has any good examples/recipes I'd greatly appreciate it. This is a test server I put together (part adapted from somewhere else) earlier in the week, it is multithreaded inbound. You could add your required functionality quite easily. It currently starts on port 2525 (watch out for line-wraps) ## #! /usr/bin/python import sys from socket import * from SocketServer import * class SMTPServer(ThreadingMixIn, TCPServer): # # other functions exist here in the live server # def noFunction(): pass #end of class SMTPServer class SMTPRequestHandler(StreamRequestHandler): def handle(self): self.terminated = 0 self.SendResponse('220 ** Welcome **') commands={ 'HELO' : self.__HELO, # supported commands 'QUIT' : self.__QUIT, #'MAIL' : self.__MAIL, #'RCPT' : self.__RCPT, 'NOOP' : self.__NOOP, #'RSET' : self.__RSET, 'EHLO' : self.__HELO, # handled by HELO #'DATA' : self.__DATA, } while not self.terminated: try: self.inputline = self.rfile.readline() self.inputline = self.inputline.rstrip().upper() except: self.inputline = '*?*' request = self.inputline.split() print "request=",request if request and commands.has_key(request[0]): # eg: if has_key FROM commands[request[0]](request) else: self.SendResponse("?? "+ self.inputline) def __HELO(self,request): if request[0]== 'HELO': self.SendResponse('250 2.1.0 Hello') else: self.SendResponse('250-Hello\r\n250-SIZE 9999999\r\n250-ENHANCEDSTATUSCODES\r\n250 HELP') def __NOOP(self,request): self.SendResponse('250 2.1.0 OK') def __QUIT(self,request): self.terminated = 1 self.SendResponse('Goodbye') print "Session Closed" def SendResponse(self,msg): print msg msg = msg + '\r\n' self.wfile.write(msg) self.wfile.flush() # end of class SMTPRequestHandler def StartSMTPServer(): print '*'*35 print 'Server Starting, CTRL-C to end' print '*'*35 setdefaulttimeout( 30 ) # timeout incoming connections server = SMTPServer(('', 2525 ), SMTPRequestHandler) server.serve_forever() #end of def StartSMTPServer if __name__ == '__main__': StartSMTPServer() From kveretennicov at gmail.com Tue Jun 21 10:28:32 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 17:28:32 +0300 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <4660fe3005062107282e3ffcc9@mail.gmail.com> On 6/21/05, Magnus Lycka wrote: > I don't know anything about the Python compiler internals, > but it doesn't seem very hard to identify simple literals following > while and if, and to skip the runtime test. (Perhaps it's done > already?) True doesn't seem to be a literal, it is looked up by name and can be rebound to, say, 0 anytime: >>> import dis >>> o = compile('while True: pass', '', 'exec') >>> dis.dis(o) 1 0 SETUP_LOOP 12 (to 15) >> 3 LOAD_NAME 0 (True) 6 JUMP_IF_FALSE 4 (to 13) 9 POP_TOP 10 JUMP_ABSOLUTE 3 ... OTOH, >>> p = compile('while 1: pass', '', 'exec') >>> dis.dis(p) 1 0 SETUP_LOOP 5 (to 8) >> 3 JUMP_ABSOLUTE 3 ... - kv From martin.witte at gmail.com Sun Jun 12 16:28:13 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 12 Jun 2005 13:28:13 -0700 Subject: How to test if an object IS another object? In-Reply-To: <1118607204.001609.25310@g47g2000cwa.googlegroups.com> References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> Message-ID: <1118608093.758427.280220@g49g2000cwa.googlegroups.com> You can use the id() function to test equality of objects: martin at ubuntu:~$ python Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = 3 >>> b = 3 >>> id(a) 135585176 >>> id(b) 135585176 >>> From steve at REMOVETHIScyber.com.au Thu Jun 23 06:34:36 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 23 Jun 2005 20:34:36 +1000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> Message-ID: On Thu, 23 Jun 2005 00:11:20 -0400, Tim Peters wrote: > Well, I try, Ivan. But lest the point be missed , 754 doesn't > _want_ +0 and -0 to act differently in "almost any" way. The only > good rationale I've seen for why it makes the distinction at all is in > Kahan's paper "Branch Cuts for Complex > Elementary Functions, or Much Ado About Nothing's Sign Bit". There > are examples in that where, when working with complex numbers, you can > easily stumble into getting real-world dead-wrong results if there's > only one flavor of 0. And, of course, atan2 exists primarily to help > convert complex numbers from rectangular to polar form. It isn't necessary to look at complex numbers to see the difference between positive and negative zero. Just look at a graph of y=1/x. In particular, look at the behaviour of the graph around x=0. Now tell me that the sign of zero doesn't make a difference. Signed zeroes also preserve 1/(1/x) == x for all x, admittedly at the cost of y==x iff 1/y == 1/x (which fails for y=-0 and x=+0). Technically, -0 and +0 are not the same (for some definition of "technically"); but practicality beats purity and it is more useful to have -0==+0 than the alternative. > Odd bit o' trivia: following "the rules" for signed zeroes in 754 > makes exponeniation c**n ambiguous, where c is a complex number with > c.real == c.imag == 0.0 (but the zeroes may be signed), and n is a > positive integer. The signs on the zeroes coming out can depend on > the exact order in which multiplications are performed, because the > underlying multiplication isn't associative despite that it's exact. That's an implementation failure. Mathematically, the sign of 0**n should depend only on whether n is odd or even. If c**n is ambiguous, then that's a bug in the implementation, not the standard. > I stumbled into this in the 80's when KSR's Fortran compiler failed a > federal conformance test, precisely because the test did atan2 on the > components of an all-zero complex raised to an integer power, and I > had written one of the few 754-conforming libms at the time. They > wanted 0, while my atan2 dutifully returned -pi. I haven't had much > personal love for 754 esoterica since then ... Sounds to me that the Feds wanted something broken and you gave them something that was working. No wonder they failed you :-) -- Steven. From ashokbellur at gmail.com Wed Jun 8 17:49:00 2005 From: ashokbellur at gmail.com (ashokbellur at gmail.com) Date: 8 Jun 2005 14:49:00 -0700 Subject: pack heterogeneous data types Message-ID: <1118267340.026766.188450@g14g2000cwa.googlegroups.com> Hello, How do i pack different data types into a struct or an array. Examples would be helpful. Say i need to pack an unsigned char( 0xFF) and an long( 0xAAAAAAAA) into a single array? The reason i need to do this is send a packet over a network. Thanks, -AB From fabioz at esss.com.br Tue Jun 28 12:07:01 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Tue, 28 Jun 2005 13:07:01 -0300 Subject: ANN: PyDev 0.9.5 released In-Reply-To: <42A720BD.5050701@esss.com.br> References: <42A720BD.5050701@esss.com.br> Message-ID: <42C175A5.5000206@esss.com.br> Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.5 has just been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Release Highlights: - File encodings now follow the python convention - Overview ruler now works - Editor is synchronized when working in multiple windows with the same file - Code folding improved - Syntax highlighting is not confused by escaped quote + triple quote anymore - Insertion of parentheses now replaces selected text - Some more bugs... Regards, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com From xah at xahlee.org Tue Jun 7 14:03:55 2005 From: xah at xahlee.org (Xah Lee) Date: 7 Jun 2005 11:03:55 -0700 Subject: What are OOP's Jargons and Complexities? In-Reply-To: <1117830051.520099.129930@g44g2000cwa.googlegroups.com> References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <1117003340.900449.124180@o13g2000cwo.googlegroups.com> <1117264336.229771.245070@g49g2000cwa.googlegroups.com> <1117532688.513061.162750@f14g2000cwb.googlegroups.com> <1117830051.520099.129930@g44g2000cwa.googlegroups.com> Message-ID: <1118167434.974707.319730@g43g2000cwa.googlegroups.com> The Rise of Class Hierarchy Because of psychological push for purity, in Java there are no longer plain subroutines. Everything is a method of some class. Standard functions like opening a file, square root a number, for loop thru a list, if else branching statements, or simple arithmetic operations... must now somehow become a method of some class. In this way, coupled with the all-important need to manage data with inheritance, the OOP Class Hierarchy is born. Basic data types such as now the various classes of numbers, are now grouped into a Number class hierarchy, each class having their own set of methods. The characters, string or other data types, are lumped into one hierarchy class of data types. Many types of lists (variously known as arrays, vectors, lists, hashes...), are lumped into a one hierarchy, with each Classe node having its own set methods as appropriate. Math functions, are lumped into some math class hierarchy. Now suppose the plus operation +, where does it go? Should it become methods of the various classes under Number headings, or should it be methods of the Math class set? Each language deals with these issues differently. As a example, see this page for the hierarchy of Java's core language classes: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/package-tree.html (local copy) OOP being inherently complex exacerbated by marketing propaganda, and the inheritance and hierarchy concept is so entangled in OOP, sometimes OOP is erroneously thought of as languages with a hierarchy. (there are now also so-called Object-Oriented databases that ride the fad of ?all data are trees? ...) Normally in a program, when we want to do some operation we just call the subroutine on some data. Such as open(this_file) square(4) But now with the pure OOP style, there can no longer be just a number or this_file path, because everything now must be a Object. So, the "this_file", usually being just a string representing the path to a file on the disk, is now some "file object". Initiated by something like this_file = new File("path to file"); where this file class has a bunch of methods such as reading or writing to it. see this page for the complexity of the IO tree http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-tree.html (local copy) see this page for the documentation of the File class itself, along with its 40 or so methods and other things. http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html (local copy) ------- to be continued... This is part of an installment of the article ?What are OOP's Jargons and Complexities? by Xah Lee, 20050128. The full text is at http://xahlee.org/Periodic_dosage_dir/t2/oop.html ? Copyright 2005 by Xah Lee. Verbatim duplication of the complete article for non-profit purposes is granted. The article is published in the following newsgroups: comp.lang.c,comp.lang.c++,comp.lang.lisp,comp.unix.programmer comp.lang.python,comp.lang.perl.misc,comp.lang.scheme,comp.lang.java.programmer comp.lang.functional,comp.object,comp.software-eng,comp.software.patterns Xah xah at xahlee.org ? http://xahlee.org/ From rex.eastbourne at gmail.com Wed Jun 29 11:40:32 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 29 Jun 2005 08:40:32 -0700 Subject: Debugger Confusion In-Reply-To: References: Message-ID: <1120059632.832595.245480@g47g2000cwa.googlegroups.com> One thing: is it possible to go through the code within emacs? Doing it on the command line is useful, but it would be very helpful if I could have a little marker within the emacs buffer that showed me where I am. Rex From tchur at optushome.com.au Fri Jun 3 17:01:04 2005 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 04 Jun 2005 07:01:04 +1000 Subject: Python interest group software In-Reply-To: <20050603204724.GB8195@goliath.ag.com> References: <20050603204724.GB8195@goliath.ag.com> Message-ID: <42A0C510.2060405@optushome.com.au> David Stanek wrote: > Is there already any software out there to manage a Python Interest > Group? Something that can register users, take RSVPs for meetings, > etc. I dare say that Roundup - http://roundup.sourceforge.net/ - (not to be confused with Roundup - http://www.roundup.com/ ) - could be used effectively for such purposes, since it provides both Web and email interfaces for ad hoc interest groups. Not good for weedy types, though. Tim C From philippe at philippecmartin.com Sat Jun 25 16:14:55 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 20:14:55 GMT Subject: Excellent Site for Developers References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: <3Xive.2320$W74.614@newssvr30.news.prodigy.com> Woof! And I thought my english was improving ! I'm laughing very hard right now, thanks ! Philippe Skip Montanaro wrote: > > Philippe> Not being from anglo-saxon heritage, I keep wondering why > Philippe> spammers always (or very often) get called 'trolls' ? > > Fishing from a boat that is moving slowly is called "trolling". You're > slowly dragging bait or a lure through the water to entice a fish to bite > your hook. Similarly, when someone posts a provocative message to a > mailing list or Usenet newsgroup (or other discussion forum, I suppose) > they are often trying to get someone else to "take their bait". > > See also: http://www.answers.com/troll > > Skip From poisondart985 at gmail.com Thu Jun 2 02:42:23 2005 From: poisondart985 at gmail.com (poisondart) Date: 1 Jun 2005 23:42:23 -0700 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> Message-ID: <1117694543.931985.290720@g44g2000cwa.googlegroups.com> If this thread has shown anything it is I'm a bit green with respect to software licenses, but the other thing is that I consider myself as an isolated case and I wanted to know if there were others who wanted the same thing as me. I'm curious to know what the money that open source or GPL'd projects get and what this money means to these people's overall income. I am sure that any amount would motivate somebody to continue their work on a project, but myself in particular, I consider my project to be a tool for teaching and I view teaching as helping others...which I would gladly offer without price. I wanted to see if there were others who shared my view of helping others freely with their knowledge. Yes, what I ask may seem ridiculous, but I don't view it that way. Instead, I find that it is the implication of using a restrictive license such as I described to be ridiculous: if there is no monetary gain option in the license, then this implies that nobody (or very few) will be willing to do any work or "asking for something for nothing". It isn't for nothing if you value knowledge and learning. I admit that my view is a bit idealistic which leads me to believe that maybe I should reconsider the whole decision altogether. From steven.bethard at gmail.com Sat Jun 25 02:25:54 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Jun 2005 00:25:54 -0600 Subject: How does one write a function that increments a number? In-Reply-To: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> Message-ID: anonymousnerd at gmail.com wrote: > Apologies if this question seems stupid: How does one write a > function that increments a value in Python? When I tried, the variable > never changed. > The session went like this: > >>>>def incr(counter): > counter = int(counter) > counter += 1 > >>>>counter = 1 >>>>incr(counter) >>>>print counter > 1 You probably don't really want to write code like this in Python. How about: class Counter(object): def __init__(self, start=0): self.value = start def incr(self): self.value += 1 counter = Counter(1) counter.incr() print counter.value Or you can likely get everything you need from itertools.count. STeVe From lycka at carmen.se Wed Jun 15 11:46:50 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 15 Jun 2005 17:46:50 +0200 Subject: Strange socket problem In-Reply-To: References: Message-ID: huy wrote: > Hi, > > I'm using cherrypy to provide a user interface for users to start a > linux server program eg. os.system("nohup myserver.py &"). The problem > is that if I stop cherrypy server and restart, I get the "Address > Already In Use" problem until I stop myserver.py. Can someone shed some > light on why this happens ? Why would the socket be held up in the other > process ? As I understand it, if a socket is closed by the server, the OS will typically hold on to the socket for a while, in case the client wants some packages resent etc. This might be a part of your problem. Andrew Dalke explained it much better to me when I ran into this some time ago. Quoted below: > Magnus Lyck? wrote: >> Why doesn't my socket >> get released by the OS when I exit via my handle_error? > > Hi Magnus, > > I wrote about this at > http://www.dalkescientific.com/writings/diary/archive/2005/04/21/using_xmlrpc.html > > The reason for it is described at > http://hea-www.harvard.edu/~fine/Tech/addrinuse.html > > You can set the class variable "allow_reuse_address = True" in > your derived ExitableSocketServer to get the behaviour you > expect, at the expense of some problems mentioned in the > above URL. > > Andrew > dalke at dalkescientific.com From Stephen_Toledo_Brown at uk.ibm.com Wed Jun 29 06:22:05 2005 From: Stephen_Toledo_Brown at uk.ibm.com (Stephen Toledo-Brown) Date: Wed, 29 Jun 2005 11:22:05 +0100 Subject: ANN: PyDev 0.9.5 released In-Reply-To: References: <42A720BD.5050701@esss.com.br> Message-ID: <42c27cb2_2@news2.prserv.net> Dave Cook wrote: > On 2005-06-28, Fabio Zadrozny wrote: >>PyDev - Python IDE (Python Development Enviroment for Eclipse) version >>0.9.5 has just been released. > Does it work with the newly released Eclipse 3.1? It's worked with previous release candidates. From sjmachin at lexicon.net Wed Jun 1 20:58:42 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 10:58:42 +1000 Subject: Performance Issues please help In-Reply-To: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> Message-ID: <429E59C2.8010405@lexicon.net> PyPK wrote: > I was testing this piece of code and it takes about 24-30 seconds to do > a look up on a list(m) of size 1000x1000 > m -> list of size 1000x1000 > import time > print time.ctime() > box = {} > for r,row in enumerate(m): > for c,e in enumerate(row): > if box.has_key(e): > params = box[e] > box[e] = ( min(c, params[0]), min(r, params[1]), > max(c, params[2]), max(r, params[3] ) ) > else: > box[e] = [c, r, c, r] > print time.ctime() > > Can some one tell me what exactly is taking more time here. Is it > because I am using dictionaries or what is the problem. Can some one > help me improve this .Is there a better way to write this. > Without gross changes to the algorithm, and in no particular order: 0. Stop worrying. Find something else to do during the 30 seconds. 1. Use psyco, if your [unspecified] platform supports it. 2. Why has_key()? Try "if e in box:" instead, if your [unspecified] version of Python supports it. If it doesn't, (a) consider upgrading (b) try doing box_has_key = box.has_key outside the loops and using the result inside the loops. 3. Ensure this code is inside a function, not at global level in a script [not apparent from your post]. 4. Outside the loops, put "local_min = min", ditto for max. Then use box[e] = (local_min(c, etc etc 5. Upgrade your [unspecified] hardware. 6. Use try/except, if indicated by the [unspecified] percentage of times "e in box" is true. Hint: printing len(box) at the end might be useful. 7. Consider using pyrex. 8. Consider using numarray/mumeric. Info req'd for discussing algorithm changes: 1. How much free memory do you have? 2. What can you tell us about the distribution of "e"? 3. Is "m" a rectangle, or are the rows of variable length? 4. Do you have control over "m" i.e. are you stuck with that data structure, or can we design a different one? From lbates at syscononline.com Mon Jun 20 10:01:13 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 20 Jun 2005 09:01:13 -0500 Subject: import via pathname In-Reply-To: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> References: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> Message-ID: <42B6CC29.4050507@syscononline.com> If it is Windows use py2exe and Inno Installer to create an installation program that does this for you. If it is another OS, you need to put your modules into a subdirectory of site-packages and then Python will be able to see your modules. If you have a lot of modules you might consider turning them into a package. -Larry passion_to_be_free at hotmail.com wrote: > Okay, so in my li'l python script I'm importing a few 3rd party modules > that I have installed on my comp. I need to distribute this script to > several other people, but I won't have access to install the modules on > their comp's. I'm thinking I'll include these modules with my script > and deliver them as a bundle. When I write my script, is there a way to > declare the import statements and specify a relative path to where the > modules are located? > > I know this is wrong syntax, but I think it demonstrates what I'm > trying to do: > > import myModule path = /modules/myModule > import myModule2 path = /modules/myModule2 > > Something like that. Is it possible? > > -Thx > From Kyle.Robertson at ni.com Thu Jun 2 11:58:54 2005 From: Kyle.Robertson at ni.com (Kyle.Robertson at ni.com) Date: Thu, 2 Jun 2005 10:58:54 -0500 Subject: TkInter Listbox Widget Formatting Message-ID: I've searched high and low, and I can't seem to find a way to center or right justify the text in a Listbox widget using TkInter. The justify option is unrecognized. Any options I'm missing, or a known work-around? Thanks! Kyle -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Thu Jun 30 10:56:33 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 30 Jun 2005 14:56:33 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> <8c7f10c605063001207fd379ec@mail.gmail.com> Message-ID: <11c8211tl4sc107@corp.supernews.com> On 2005-06-30, Luis M. Gonzalez wrote: > Well, yes, it is kinda off topic, but very interesting... > Being myself an argentine with spanish as mother tongue and a > very bad English, it's hard foro me to tell the difference > between accents. I can hardly tell an Irish from an English... > But what I did tell is the broad range of different accents > within London when I visited the city in 2001. > > Some people seemed to speak very clear to me, and others > seemed to be speaking german! I'm an American who grew up watching plenty of BBC, and I run into afew native Londoners whom I have hard time understanding. I don't ever remember having troubly understanding people outside the city. -- Grant Edwards grante Yow! I KAISER ROLL?! What at good is a Kaiser Roll visi.com without a little COLE SLAW on the SIDE? From martin.witte at gmail.com Fri Jun 10 07:44:53 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 10 Jun 2005 04:44:53 -0700 Subject: EOFError not getting raised In-Reply-To: References: Message-ID: <1118403893.652561.266720@g47g2000cwa.googlegroups.com> See http://docs.python.org/lib/module-exceptions.html: EOFError gets raised when input() or raw_input() hit an EOF condition without reading data. From renting at astron.nl Thu Jun 23 08:46:12 2005 From: renting at astron.nl (Adriaan Renting) Date: Thu, 23 Jun 2005 14:46:12 +0200 Subject: No subject Message-ID: I'm using Eric3 and realy like it. http://www.die-offenbachs.de/detlev/eric3.html Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> "Doug Ly" 06/22/05 4:37 PM >>> Is there a good IDE for Python? I have heard that Eclipse has a plugin for Jython only. Thanks --Doug From robin at SPAMREMOVEjessikat.fsnet.co.uk Sun Jun 12 05:22:52 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sun, 12 Jun 2005 09:22:52 +0000 Subject: subprocess module and blocking Message-ID: <42ABFEEC.3010505@jessikat.fsnet.co.uk> I'm using a polling loop in a thread that looks approximately like this while 1: p = find_a_process() rc = p.poll() if rc is not None: out, err = p.communicate() #deal with output etc sleep(1) the process p is opened using p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=cwd) stdin is actually never written to. I notice that under both win32 and freebsd that things are fine provided that the subprocess doesn't write too much to stdout/stderr. However, the subprocess seems to lock often if too much is written (under freebsd I see a process state of POLL). I assume that the subprocess is filling up the pipe and then failing to wake up again. I had expected that subprocess would take care of this for me, but possibly I'm being utterly clueless and stupid. What should I do to avoid blocking in the subprocess? -- Robin Becker From desertgarden at netscape.com Sat Jun 11 10:59:05 2005 From: desertgarden at netscape.com (Brian) Date: Sat, 11 Jun 2005 14:59:05 GMT Subject: cgi script runs under Opera, but not firefox In-Reply-To: <1118501642.065924.83560@z14g2000cwz.googlegroups.com> References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> <1118501642.065924.83560@z14g2000cwz.googlegroups.com> Message-ID: Bingo, found it! Notice that you accidentally close the document before displaying any information... nephish at xit.net wrote: > > Customer Data > > >

Watkins Crop Consulting

> > Notice the tag above. There's the problem! Brian From ivanlan at pauahtun.org Wed Jun 8 23:06:08 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Wed, 08 Jun 2005 21:06:08 -0600 Subject: file permissions on windows XP (home) References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> <1118178009.923372.160210@g44g2000cwa.googlegroups.com> <1118266606.590200.118970@g44g2000cwa.googlegroups.com> <1118277656.983871.142170@z14g2000cwz.googlegroups.com> Message-ID: <42A7B220.89257B4@pauahtun.org> Hi All-- gratzel at gmail.com wrote: > > I have noticed a bug that if I have a folder open for viewing in > Windows Explorer with Thumbnail view enabled that I often run into > inexplicable problems with modify permissions, say when I want to > rename or delete an item. Changing the view to Detailed or rebooting > seems to make the issue go away. > Makes sense. With the thumbnail view enabled, Windows has to monitor every file in the directory for changes, and update the thumbs all the time. With other types it watches for changes, but it doesn't have to be so obsessive about it. Now that I think about it, the times that I've had permission trouble it's always been with thumbs. Not definitive, but worth looking out for. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From newsgroups at jhrothjr.com Sun Jun 12 08:49:02 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 12 Jun 2005 06:49:02 -0600 Subject: unittest: collecting tests from many modules? References: Message-ID: <11aobq2hg218v0c@news.supernews.com> "Jorgen Grahn" wrote in message news:slrndao1p4.4m5.jgrahn-nntq at frailea.sa.invalid... >I have a set of tests in different modules: test_foo.py, test_bar.py and so > on. All of these use the simplest possible internal layout: a number of > classes containing test*() methods, and the good old lines at the end: > > if __name__ == "__main__": > unittest.main() > > This is great, because each of the modules are runnable, and I can select > classes or tests to run on the commandline if I want to. However, running > all the tests from e.g. a Makefile is not that fun; I don't get a single > pass/fail summary across the modules. > > What's the best way of creating a test.py which > - aggregates the tests from all the test_*.py modules? > - doesn't require me to enumerate all the test classes in test.py > (forcing each module to define test_foo.theSuite or someting would > be OK though) > - retains the ability to select tests and verbosity (-q, -v) from the > command line? I use your second point: I build a TestAll module. However, I'm going to look at building the test suite using the TestLoader class in the next version of PyFit. It sholdn't be all that difficult to find all the Test*.py modules in a directory, import them and use the TestLoader class to add them to the test suite. Or, for that matter, to use reflection to find all the classes that derive from TestCase and add them to the suite manually. That has the advantage that one could then select classes according to some parameter. John Roth > > Something like: > > import unittest > import test_foo > import test_bar > > if __name__ == "__main__": > unittest.main(modules = ['test_foo', > 'test_bar']) > > Seems to me this should be possible, since all the logic for doing it /is/ > there for the local module; I'd assume there would be a way to make > unittest > search additional modules for test classes. But my head starts spinning > when I read the source code ... > > /Jorgen > > -- > // Jorgen Grahn \X/ algonet.se> R'lyeh wgah'nagl fhtagn! From peter at somewhere.com Wed Jun 29 03:04:42 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 29 Jun 2005 09:04:42 +0200 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119990282.791576.196130@g43g2000cwa.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1119990282.791576.196130@g43g2000cwa.googlegroups.com> Message-ID: muldoon schrieb: > Now, what forum would you recommend? Any help would be appreciated. alt.culture.us.* -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From mg.mailing-list at laposte.net Tue Jun 21 02:43:19 2005 From: mg.mailing-list at laposte.net (mg) Date: Tue, 21 Jun 2005 08:43:19 +0200 Subject: catch argc-argv In-Reply-To: <42B6C133.6040203@lexicon.net> References: <42B68463.90501@lexicon.net> <42B6C133.6040203@lexicon.net> Message-ID: <42B7B707.3020209@laposte.net> John Machin wrote: >Duncan Booth wrote: > > >>John Machin wrote: >> >> >> >> >>>>So, my question is: does the Python API containe fonctions like >>>>'get_argc()' and 'get_argv()' ? >>>> >>>> >>>> >>>If you can't see them in the documentation, they aren't there. If they >>>aren't there, that's probably for a good reason -- no demand, no use >>>case. >>> >>> >>> >>> >>Leaving aside whether or not there is a use-case for this, the reason they >>aren't there is that they aren't needed. >> >> > >"no use-case" == "no need" in my book > > > >>As the OP was already told, to >>access argv, you simply import the 'sys' module and access sys.argv. >> >> > >Simple in Python, not in C. > > > >>There are apis both to import modules and to get an attribute of an >>existing Python object. >> >> > >I know that; my point was why should you do something tedious like that >when you shouldn't be interested in accessing sys.argv from a C >extension anyway. > > > >> So all you need is something like (untested): >> >>PyObject *sys = PyImport_ImportModule("sys"); >>PyObject *argv = PyObject_GetAttrString(sys, "argv"); >>int argc = PyObject_Length(argv); >>if (argc != -1) { >> ... use argc, argv ... >>} >>Py_DECREF(argv); >>Py_DECREF(sys); >> >> I understand all the good arguments explained before, and I am agree with them. Nevertheless, I implement Python bindings from a generic parallel framework and a new application based on this framework needs to call a kind of initilization class : the constructor arguments are argc and argv... Then, the previous solution can be a work around to test some behavours of my bindings. Thanks for your answers ;-) From could.net at gmail.com Tue Jun 28 04:37:05 2005 From: could.net at gmail.com (could ildg) Date: Tue, 28 Jun 2005 16:37:05 +0800 Subject: How to compress a folder and all of its sub directories and files into a zip file? In-Reply-To: <42C0FFCC.8030708@po-box.mcgill.ca> References: <311b5ce105062723167e892833@mail.gmail.com> <42C188F3.7010704@rt.sk> <311b5ce1050628002075da2e3@mail.gmail.com> <311b5ce10506280029682b9366@mail.gmail.com> <42C0FFCC.8030708@po-box.mcgill.ca> Message-ID: <311b5ce1050628013753c12b6a@mail.gmail.com> Thanks to Brian van den Broek , I've just reached the doc, too. I'm now very clear. On 6/28/05, Brian van den Broek wrote: > could ildg said unto the world upon 28/06/2005 03:29: > > but the file is just stored, > > and not compressed. > > > > On 6/28/05, could ildg wrote: > > > >>Thank you, > >>it works~~ > >> > >>On 6/29/05, Peter Szinek wrote: > >> > >>>Hi, > >>> > >>>What about this: > >>> > >>>import os,zipfile > >>>from os.path import join > >>> > >>> > >>>zip = zipfile.ZipFile("myzipfile.zip", 'w') > >>>for root, dirs, files in os.walk('.'): > >>> for fileName in files: > >>> zip.write(join(root,fileName)) > >>>zip.close() > >>> > >>>Maybe it zips also the myzipfile.zip ;-) > >>>Probably this is not needed, so an additional test (something like > >>>fileName != 'myfile.zip' would be needed. > >>> > >>>HTH, > >>>Peter > >>> > >>>could ildg wrote: > >>> > >>>>I want to compress a folder and all of its sub files including empty folders > >>>>into a zip file. what's the pythonic way to do this? > >>>> > >>>>Thanks in advance. > >>> > >>> > > This thread got me to read the relevant docs: > > 7.18.1 ZipFile Objects > "class ZipFile( file[, mode[, compression]]) > Open a ZIP file, where file can be either a path to a file (a > string) or a file-like object. The mode parameter should be 'r' to > read an existing file, 'w' to truncate and write a new file, or 'a' to > append to an existing file. For mode is 'a' and file refers to an > existing ZIP file, then additional files are added to it. If file does > not refer to a ZIP file, then a new ZIP archive is appended to the > file. This is meant for adding a ZIP archive to another file, such as > python.exe. Using > > cat myzip.zip >> python.exe > > also works, and at least WinZip can read such files. compression > is the ZIP compression method to use when writing the archive, and > should be ZIP_STORED or ZIP_DEFLATED; unrecognized values will cause > RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib > module is not available, RuntimeError is also raised. The default is > ZIP_STORED." > http://docs.python.org/lib/zipfile-objects.html > > So, it would appear that compression requires a 3rd party module, not > included in Python (and not present on my Windows box). > > I'm presently filing a bug suggesting this be made a touch more > explicit in the zlib docs. > > Best to all, > > Brian vdB > > From peter at engcorp.com Wed Jun 22 09:28:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Jun 2005 09:28:31 -0400 Subject: asynchronous comunication, wxPython and threads. In-Reply-To: References: Message-ID: Zunbeltz Izaola wrote: > I opened the socket once (i don't know if > itit is important to open inside or outside the comunication thread). I don't believe it is important where it is opened, provided you don't try to do things with it from two threads at a time (without adequate protection). > I didn't try it out but I > think the problem is that i *do* comunication in both threads. Almost certainly it is. It would be simplest to set up a worker thread once, when the GUI thread begins, and simply send requests to it via a Queue. It can create the socket, connect to the server, communicate, close it down, and go back to waiting all in one place (so to speak... of course this would be several methods all called from a top-level loop in that thread). No chance of mis-steps. -Peter From spam.csubich+block at block.subich.spam.com Sat Jun 11 19:43:24 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sat, 11 Jun 2005 19:43:24 -0400 Subject: TKinter -- '' event executing more than once? Message-ID: <6EKqe.115932$J25.63349@bignews6.bellsouth.net> I'm building an application involving both twisted and Tkinter. Since twisted co-opts .mainloop() in its reactor.run(), and since it behaves very badly if the application quits without reactor.stop() running, I attach the following function to '' in the main window (root = Tk()): def stop_reactor_bind(x): reactor.stop() Then: root.bind('',stop_reactor_bind) The problem, however, comes that when I add a Text widget inside the root window, upon destroying the window (closing it) the callback seems to execute twice. In interactive testing, it's executed once per widget inside the root window. Since twisted doesn't take multiple reactor.stop()s gracefully, how (short of wrapping this inside a class/scope that keeps state) can I ensure that the callback executes only once? Am I attaching to the wrong signal? From christopher.saunter at durham.ac.uk Tue Jun 28 17:42:19 2005 From: christopher.saunter at durham.ac.uk (c d saunter) Date: Tue, 28 Jun 2005 21:42:19 +0000 (UTC) Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: Michael Hoffman (cam.ac.uk at mh391.invalid) wrote: : muldoon wrote: : > Americans consider having a "British accent" a sign of sophistication : > and high intelligence. Many companies hire salespersons from Britain to : > represent their products,etc. Question: When the British hear an : > "American accent," does it sound unsophisticated and dumb? : > : > Be blunt. We Americans need to know. : To be blunt, I have no idea what this has to do with Python. Surely : selecting the right forum to use indicates more sophistication and high : intelligence than the way one speaks. ;-) Well you could draw a tenuous Python link on the headache inducing subject of trying to remember which spelling is which when doing something like: thirdparty_module_1.color = thirdparty_module_2.colour >>> from __future__ import sane_spelling :-) cds From mh at pixar.com Wed Jun 15 19:44:22 2005 From: mh at pixar.com (Mark Harrison) Date: Wed, 15 Jun 2005 23:44:22 GMT Subject: splitting delimited strings References: Message-ID: Paul McNett

wrote: > Mark Harrison wrote: > > What is the best way to process a text file of delimited strings? > > I've got a file where strings are quoted with at-signs, @like this at . > > At-signs in the string are represented as doubled @@. > > Have you taken a look at the csv module yet? No guarantees, but it may > just work. You'd have to set delimiter to ' ' and quotechar to '@'. You > may need to manually handle the double-@ thing, but why don't you see > how close you can get with csv? This is great! Everything works perfectly. Even the double-@ thing is handled by the default quotechar handling. Thanks again, Mark -- Mark Harrison Pixar Animation Studios From wuwei23 at gmail.com Sun Jun 12 06:56:42 2005 From: wuwei23 at gmail.com (alex23) Date: 12 Jun 2005 03:56:42 -0700 Subject: How to get/set class attributes in Python In-Reply-To: References: Message-ID: <1118573802.257329.271860@g43g2000cwa.googlegroups.com> Kalle Anke wrote: > I'm coming to Python from other programming languages. I like to > hide all attributes of a class and to only provide access to them > via methods. I'm pretty fond of this format for setting up class properties: class Klass(object): def propname(): def fget: pass def fset: pass def fdel: pass def doc: """pass""" return locals() propname = property(**propname()) (Replacing 'pass' in the getters & setters et.al with the actual functionality you want, of course...) This method minimises the leftover bindings, effectively leaving the getter/setter methods bound only to the property, ensuring they're only called when the property is acted upon. Incidentally, kudos & thanks to whomever I originally stole it from :) -alex23 From philippe at philippecmartin.com Sat Jun 11 15:28:07 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 11 Jun 2005 19:28:07 GMT Subject: What is different with Python ? Message-ID: I apologize in advance for launching this post but I might get enlightment somehow (PS: I am _very_ agnostic ;-). - 1) I do not consider my intelligence/education above average - 2) I am very pragmatic - 3) I usually move forward when I get the gut feeling I am correct - 4) Most likely because of 1), I usually do not manage to fully explain 3) when it comes true. - 5) I have developed for many years (>18) in many different environments, languages, and O/S's (including realtime kernels) . Yet for the first time I get (most) of my questions answered by a language I did not know 1 year ago. As I do try to understand concepts when I'm able to, I wish to try and find out why Python seems different. Having followed this newsgroup for sometimes, I now have the gut feeling (see 3)) other people have that feeling too. Quid ? Regards, Philippe From irmen.NOSPAM at xs4all.nl Wed Jun 29 18:13:45 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 30 Jun 2005 00:13:45 +0200 Subject: python broadcast socket In-Reply-To: <11c5alob44cc3da@corp.supernews.com> References: <11c5alob44cc3da@corp.supernews.com> Message-ID: <42c31d19$0$60131$e4fe514c@news.xs4all.nl> Grant Edwards wrote: > Under Linux, you need to be root to send a broadcase packet. I don't think this is true. --Irmen From cdkrug at worldnet.att.net Sat Jun 25 13:45:54 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Sat, 25 Jun 2005 17:45:54 GMT Subject: Excellent Site for Developers References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: On Sat, 25 Jun 2005 14:50:48 GMT, Brian wrote: > Do Re Mi chel La Si Do wrote: >> rather... super troll > > 100% Agreed. > > Can anyone say, "This looks like spam... Feels like spam... and is about > as useful here in the Python forums as spam -- therfore my conclusion is > that his VB message probably IS SPAM." :-D > > Brian > --- Hmmmm . . .tough call. After all, Spam is nearly ALWAYS ON topic for a Python group. *enjoys his spam bacon eggs spam spam and spam* From david.van.mosselbeen at telenet.be Mon Jun 13 18:13:27 2005 From: david.van.mosselbeen at telenet.be (David Van Mosselbeen) Date: Mon, 13 Jun 2005 22:13:27 GMT Subject: Show current ip on Linux References: Message-ID: Lee Harr wrote: > On 2005-06-13, David Van Mosselbeen > wrote: >> Hi, >> Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine >> man :-) >> >> My question is : How can i rwite a script that show my current ip. If i >> have more than one network card, the script must then show all used ip. >> >> It's important that this will work on a linux. i Have rwite some piece of >> code that realy work under Windows XP, but the same script wil not work >> on Linux. >> >> Verry thanks to all vulunteers. >> > > This comes up at least once a month. Google. Is. Your. Friend. > > http://mail.python.org/pipermail/python-list/2005-January/258883.html Thanks for support. I have read the refered page you show above. I try some piece of code that im have copy and paste it into a blank file that i give the name "ip_adress.py" to test it. THE SOURCE CODE : ----------------- import commands ifconfig = '/sbin/ifconfig' # name of ethernet interface iface = 'eth0' # text just before inet address in ifconfig output telltale = 'inet addr:' def my_addr(): cmd = '%s %s' % (ifconfig, iface) output = commands.getoutput(cmd) inet = output.find(telltale) if inet >= 0: start = inet + len(telltale) end = output.find(' ', start) addr = output[start:end] else: addr = '' return addr # End python code But now, it's fine to have some piece of code but this wil not work on my computer. I'm sure that y do somethings bad. To run the python script on a Linux machine. How to proceed it ? 1) I have open a terminal 2) then i type "python ip_adress.py" (to run the script) But nothings, i not view the current ip of my computer. What happend ? -- David Van Mosselbeen - DVM http://dvm.zapto.org:3333 --- Fedora Core 3 User From bronger at physik.rwth-aachen.de Sun Jun 26 06:39:39 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 26 Jun 2005 12:39:39 +0200 Subject: Favorite non-python language trick? References: Message-ID: <87r7eptn9w.fsf@wilson.rwth-aachen.de> Hall?chen! Terry Hancock writes: > [...] > > BASIC did it that way, IIRC. Right. > [...] > > I don't think Python's use of "==" has *ever* helped me find a > bug, it just creates them. I really think "=" ought to be > accepted as well, and "==" deprecated. However, then you must forbid a=b=1 for assigning to two variables at the same time. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From exarkun at divmod.com Fri Jun 10 12:28:53 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 10 Jun 2005 12:28:53 -0400 Subject: Annoying behaviour of the != operator In-Reply-To: <1118419552.982312.228410@g43g2000cwa.googlegroups.com> Message-ID: <20050610162853.5047.255176817.divmod.quotient.483@ohm> On 10 Jun 2005 09:05:53 -0700, Dan Bishop wrote: >Steven D'Aprano wrote: >... >> If you were to ask, "which is bigger, 1+2j or 3+4j?" then you >> are asking a question about mathematical size. There is no unique answer >> (although taking the absolute value must surely come close) and the >> expression 1+2j > 3+4j is undefined. >> >> But if you ask "which should come first in a list, 1+2j or 3+4j?" then you >> are asking about a completely different thing. The usual way of sorting >> arbitrary chunks of data within a list is by dictionary order, and in >> dictionary order 1+2j comes before 3+4j because 1 comes before 3. >> >> This suggests that perhaps sort needs a keyword argument "style", one of >> "dictionary", "numeric" or "datetime", which would modify how sorting >> would compare keys. >> >> Perhaps in Python 3.0. > >What's wrong with the Python 2.4 approach of > >>>> clist = [7+8j, 3+4j, 1+2j, 5+6j] >>>> clist.sort(key=lambda z: (z.real, z.imag)) >>>> clist >[(1+2j), (3+4j), (5+6j), (7+8j)] > It's not a general solution: >>> L = [1, 'hello', 2j] >>> L.sort(key=lambda x: (x.real, x.imag)) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in AttributeError: 'int' object has no attribute 'real' Jp From mrmaple at gmail.com Mon Jun 27 20:09:25 2005 From: mrmaple at gmail.com (James Carroll) Date: Mon, 27 Jun 2005 20:09:25 -0400 Subject: FlashMX and Py2exe doesn't fly... In-Reply-To: <1119910271.719937.101370@g43g2000cwa.googlegroups.com> References: <1119910271.719937.101370@g43g2000cwa.googlegroups.com> Message-ID: They did it with Gush: (I think) http://2entwine.com/ It's a py program that embeds Flash.... very nice. -Jim On 27 Jun 2005 15:11:11 -0700, Grooooops wrote: > Flash and Python could be a VERY powerful pair of tools for building > quick apps, Yet I don't see much on the web about it. > > I was excited to see that it is possible to make them play together > here: > http://www.klaustrofobik.org/blog/archives/000235.html > > Unfortunately, these folks seem to have gotten stuck on compiling the > py files to exe, and since I don't see reference to it anywhere else, I > was wondering if anyone here knew why it didn't work, or if anyone had > ideas about how to make it work. > > Normally I would put some test code here, but I'm way out of my league. > Just insanely curious... > > Any thoughts??? > > > Thanks, > -J > > -- > http://mail.python.org/mailman/listinfo/python-list > > From hello at spamm.er Tue Jun 21 17:45:00 2005 From: hello at spamm.er (alex goldman) Date: Tue, 21 Jun 2005 14:45:00 -0700 Subject: tree functions daily exercise: Table References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119357221.467207.149480@f14g2000cwb.googlegroups.com> <1119389873.409227.225680@f14g2000cwb.googlegroups.com> Message-ID: <3761002.h3scgg4rtt@yahoo.com> Xah Lee wrote: > > well yes... but this was emulation of Mathematica functions. > (Disclaimer: Mathematica is a trademark of Wolfram Research Inc, who is > not affliated with this project) You could have fooled me. From qwweeeit at yahoo.it Tue Jun 7 14:51:43 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 7 Jun 2005 11:51:43 -0700 Subject: Create our own python source repository In-Reply-To: <1118156654.634103.186390@o13g2000cwo.googlegroups.com> References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> <1118156654.634103.186390@o13g2000cwo.googlegroups.com> Message-ID: <1118170303.568984.242610@z14g2000cwz.googlegroups.com> Hi Rob, thank you for your reply. I am further commenting on your doubts ("I'm not entirely sure what the point of your exercise is") and on your proposal of a project for more structured tutorials. About the second item, I fully agree with you. I should be even more drastic: for a certain argument I'd prefer an application fully explained (also if not covering all the features) to a more general tutorial with only brief and unrelated code snippets. Unfortunately, that's not the way things are normally done, because it is much harder to build a useful application and fully comment it (also from the theoretical point of view, like, for example, OO or database management) As far as the 1st item is concerned, I know that Cookbook Python is frequently updated, but for my purposes also a "freezed" situation is OK, and "grepping" is much more useful than "googling" over the web. For that reason I want also add to the repository "my" examples of Python scripts, to build on already known tools. To give an example, the other day I wanted to use "writelines()" to save a list to a file. Having already used such a file method, but not remembering where and when, I was obliged to consult the Library Reference for the sintax and for the type of list instead of merely cutting and pasting from my code... Bye. From olivier.favre-simon at club-internet.fr Thu Jun 2 02:18:58 2005 From: olivier.favre-simon at club-internet.fr (Olivier Favre-Simon) Date: Thu, 02 Jun 2005 08:18:58 +0200 Subject: scripting browsers from Python References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> <87r7fl7lwf.fsf@pobox.com> Message-ID: On Wed, 01 Jun 2005 22:27:44 +0000, John J. Lee wrote: > Olivier Favre-Simon writes: > >> On Tue, 31 May 2005 00:52:33 -0700, Michele Simionato wrote: >> >> > I would like to know what is available for scripting browsers from >> > Python. > [...] >> ClientForm http://wwwsearch.sourceforge.net/ClientForm/ >> >> I use it for automation of POSTs of entire image directories to >> imagevenue.com/imagehigh.com/etc hosts. > > This doesn't actually address what the OP wanted: it's not a browser. Yep. Didn't read with sufficient care. He really wants scripting not webscraping. > > >> The only drawback I've found are: >> - does not support nested forms (since forms are returned in a list) > > Nested forms?? Good grief. Can you point me at a real life example of > such HTML? Can probably fix the parser to work around this. What I mean is: The parser does not detect a missing , so thinks that there are nested forms, and raises a ParseError. Browsers have an easier task at spotting non-matching form tags, because they can use matching table or div tags around to imply that the form is closed (DOM approach). Not easy with a SAXish approach like HTMLParser. I don't mean nested forms should be supported, they are crap (is this even legal code ?) > > >> - does not like ill-formed HTML (Uses HTMLParser as the underlying >> parser. you may pass a parser class as parameter (say SGMLParser for >> greater acceptance of stupid HTML code) but it's tricky because there >> is no well defined parser interface) > > Titus Brown says he's trying to fix sgmllib (to some extent, at least). > > Also, you can always feed stuff through mxTidy. > > I'd like to have a reimplementation of ClientForm on top of something > like BeautifulSoup... > > > John When taken separately, either ClientForm, HTMLParser or SGMLParser work well. But it would be cool that competent people in the HTML parsing domain join up, and define a base parser interface, the same way smart guys did with WSGI for webservers. So libs like ClientForm would not raise say an AttributeError if some custom parser class does not implement a given attribute. Adding an otherwise unused attribute to a parser just in case one day it will interop with ClientForm sounds silly. And what if ClientForm changes its attributes, etc. No really, whatever the chosen codebase, a common parser interface would be great. From mandus at gmail.com Mon Jun 6 10:55:05 2005 From: mandus at gmail.com (Mandus) Date: Mon, 6 Jun 2005 14:55:05 +0000 (UTC) Subject: Computer Cluster Python Software References: <1118067774.890927.279130@g49g2000cwa.googlegroups.com> Message-ID: 6 Jun 2005 07:22:54 -0700 skrev uli: > Is there any open source Python software (preferably biopython) written > which runs on a cluster. Alternatively are there interfaces written in > Python to existing cluster software. Can you be more specific? There are for example several MPI interfaces (pyMPI, pypar, ScientificPython.MPI). With pyMPI, you can run python interactively on a cluster if you want. But you are probably looking for something else? btw, soon there will be PyFDM (pyfdm.sf.net) which will make it possible to do FDM on a cluster (or any parallel computer) with little effort. mvh, -- Mandus - the only mandus around. From twic at urchin.earth.li Thu Jun 30 12:56:33 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 30 Jun 2005 17:56:33 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: <7x3br1ger1.fsf@ruckus.brouhaha.com> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> <7x3br1ger1.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 29 Jun 2005, it was written: > Rocco Moretti writes: > >> Except that (please correct me if I'm wrong) there is somewhat of a >> policy for not including interface code for third party programs which >> are not part of the operating system. > > I've never heard of Python having such a policy and I don't understand > how such a stupid policy could be considered compatible with a > proclaimed "batteries included" philosophy. Agreed. If this is the policy, it should be reconsidered. It's silly. tom -- How did i get here? From onurb at xiludom.gro Mon Jun 6 03:34:07 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 06 Jun 2005 09:34:07 +0200 Subject: anygui,anydb, any opinions? In-Reply-To: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> Message-ID: <42a3fc70$0$30762$626a14ce@news.free.fr> Thomas Bartkus wrote: > "rzed" wrote in message > news:Xns9667883C1D343jreeder at 63.223.7.253... > > >>So what do you think? What's wrong with the picture? Why isn't >>there a greater priority to work in this direction? > > > > What's wrong with the picture? > > Just one teeny little item. > > The Python world lacks the phenomenally successful development models > enjoyed by the now ancient Turbo Pascal, Delphi and Visual Basic. > AND > If the likes of Visual Basic can have it, then it becomes really, *really* > hard to convince the world that Python is a serious, professional system. You mean the "wimp gui builder + db -> ui pipeline" model ? If yes, C doesn't have it, C++ doesn't have it (in fact most languages doesn't have it) - and the fact is that C and C++ are usually considered as much more "serious and professionnal" than VB and the likes. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From njagan at gmail.com Thu Jun 30 13:53:54 2005 From: njagan at gmail.com (Jags) Date: 30 Jun 2005 10:53:54 -0700 Subject: I have a question. In-Reply-To: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> References: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Message-ID: <1120154034.202596.229340@g47g2000cwa.googlegroups.com> Hi, You can use the "Random" module. You need to first import it using "from random import Random, random". Try the following sequence of steps on the Python/IDLE command line to get an idea: >>> from random import Random, random >>> myRandom = Random() >>> myRandom.random() Hope this helps. Cheers! -- Jags. Nathan Pinno wrote: > Hi all, > > Does Python have a random function? If so, can you show me an example > using it? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > > > > -- > > > ---------------------------------------------------------------- > Posted via UsenetRevolution.com - Revolutionary Usenet > ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** > http://www.UsenetRevolution.com From Scott.Daniels at Acm.Org Sun Jun 12 12:10:10 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 12 Jun 2005 09:10:10 -0700 Subject: unittest: collecting tests from many modules? In-Reply-To: References: Message-ID: <42ac5745@nntp0.pdx.net> Jorgen Grahn wrote: > I have a set of tests in different modules: test_foo.py, test_bar.py and so > on. All of these use the simplest possible internal layout: a number of > classes containing test*() methods, and the good old lines at the end: > if __name__ == "__main__": > unittest.main() > .... > > What's the best way of creating a test.py which > - aggregates the tests from all the test_*.py modules? > - doesn't require me to enumerate all the test classes in test.py > (forcing each module to define test_foo.theSuite or someting would > be OK though) > - retains the ability to select tests and verbosity (-q, -v) from the > command line? > Something like: > > import unittest > import test_foo > import test_bar > > if __name__ == "__main__": > unittest.main(modules = ['test_foo', > 'test_bar']) > > Seems to me this should be possible, since all the logic for doing it /is/ > there for the local module; I'd assume there would be a way to make unittest > search additional modules for test classes. But my head starts spinning > when I read the source code ... > > /Jorgen > How about some variant of: import unittest import test_foo, test_bar, ... def set_globals(modules): glbl = globals() for module in modules: modprefix = module.__name__[5:] + '__' for element in dir(module): data = getattr(module, element) if isinstance(data, type) and issubclass(data, unittest.TestCase): glbl[modprefix + element] = data if __name__ == "__main__": module = type(unittest) set_globals([mod for name, mod in globals().items() if name.lower().beginswith('test') and isinstance(mod, module)]) unittest.main() --Scott David Daniels Scott.Daniels at Acm.Org From jdennett at acm.org Sun Jun 26 03:51:37 2005 From: jdennett at acm.org (James Dennett) Date: Sun, 26 Jun 2005 00:51:37 -0700 Subject: [offtopic] Re: Set of Dictionary In-Reply-To: References: <4660fe3005061608023c4f96ab@mail.gmail.com> <20050616160959.34219.qmail@web53910.mail.yahoo.com> Message-ID: Steven D'Aprano wrote: > On Thu, 16 Jun 2005 21:21:50 +0300, Konstantin Veretennicov wrote: > > >>On 6/16/05, Vibha Tripathi wrote: >> >>>I need sets as sets in mathematics: >> >>That's tough. First of all, mathematical sets can be infinite. It's >>just too much memory :) >>Software implementations can't fully match mathematical abstractions. > > > :-) > > But lists can be as long as you like, if you have enough memory. But you never have enough memory to store, for example, a list of all the prime integers (not using a regular list, anyway). > So > can longs and strings. So I don't think the infinity issue is a big one. > > >>> sets of any unique type of objects including those >>>of dictionaries, I should then be able to do: >>>a_set.__contains__(a_dictionary) and things like that. > > > Standard Set Theory disallows various constructions, otherwise you get > paradoxes. > > For example, Russell's Paradox: the set S of all sets that are not an > element of themselves. Then S should be a set. If S is an element of > itself, then it belongs in set S. But if it is in set S, then it is an > element of itself and it is not an element of S. Contradiction. > > The price mathematicians pay to avoid paradoxes like that is that some > sets do not exist. For instance, there exists no universal set (the set > of all sets), no set of all cardinal numbers, etc. > > So even in mathematics, it is not true that sets can contain anything. See "Set Theory With a Universal Set" by T. Forster, which covers some set theories in which there *is* a set of all things, and in which Russell's paradox is avoided in other ways (such as by restricting the comprehension axioms). (Sorry for drifting offtopic, I happen to find non-standard set theories interesting and thought that some others here might too.) -- James From tdelaney at avaya.com Tue Jun 14 20:48:56 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 15 Jun 2005 10:48:56 +1000 Subject: Python in Games (was RE: [Stackless] Python in Games) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025205AA@au3010avexu1.global.avaya.com> Irmen de Jong wrote: > Also, alledgedly the new BattleField II uses Python in a way... > because I heard that you had to comment out a certain line > in a certain .py file to remove the time limit of the demo :-) Silly silly people - they should have at least had the launcher and that part in Pyrex ;) Tim Delaney From philippe at philippecmartin.com Tue Jun 28 00:53:38 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 04:53:38 GMT Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119931315.996979.176610@f14g2000cwb.googlegroups.com> Message-ID: Ho! I thought the shell commands in ipython (cd, lx ....) might cut it. Regards, Philippe Brett Hoerner wrote: > > > Philippe C. Martin wrote: >> You might want to check out ipyhton. > > I use it. :) I love it. When I meant console I meant the shell app > that runs any text-based programs. The windows console was giving me > loud beeps, etc, which I've now fixed. > > Thanks for your reply though, > Brett From pdemb at gazeta.pl Fri Jun 17 12:16:52 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Fri, 17 Jun 2005 18:16:52 +0200 Subject: UML to Python/Java code generation References: Message-ID: <873brhufez.fsf@hector.domek> "Grigoris Tsolakidis" writes: > There is tool to generate UML from Python Code... The best is human brain. From tprimke at interia.pl Tue Jun 21 02:00:25 2005 From: tprimke at interia.pl (TPJ) Date: 20 Jun 2005 23:00:25 -0700 Subject: A tool for Python - request for some advice Message-ID: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> First I have to admit that my English isn't good enough. I'm still studying and sometimes I just can't express what I want to express. A few weeks ago I've written 'Python Builder' - a bash script that allows anyone to download, compile (with flags given by user) and install Python and some external modules (e.g. wxPython, PyGTK, Numeric...). I use Python every day and when new version of Python (or some external module) is released, I want to check if my projects will run on this new version (sometimes I want to know if my projects will run on specific combination of older Python and some older external modules...). It happens four - five times a year. Frequently not enough to memorize all commands used to configure, compile and install all of this software (so I have to read documentation every time I'm doing it) - but frequently enough to consume considerable amounts of my working time. So I thought that writing a script to do it all automatically (download sources, unpack them, configure them, compile them and then install them; all of this with options given by me - the user) would be a good idea. (It's not about using emerge, get-apt or some another tool of this kind. My need is very special - I want to have Python, it's modules and sometimes documentation installed in particular place; usually somewhere in my home directory. My script installs some additional scripts which I can use to run Python. These additional scripts have properly set LD_LIBRARY_PATH so they are able to run Python and external modules that require libraries installed in non-standard locations.) I've written this script in bash, because I thought it would be better to have a script which would run in environment without Python (it all was about installing Python anyway!). I used bash, dialog, wget... And now someone suggested, that I shuld use Python. That using Python would lead to clearer and - probably - smaller code. (I have to admit it - my code in bash is just messy.) And now I'm considering this idea. Python is already present on (almost?) every distribution today, so why worry about it's presence? Writing in Python would lead to easier i18n (for now it's all in Polish...) and to easier implementation of future enhancements (due to language's features and much more clearer coding style in Python). Well - I've already found it hard to implement new features in pure bash. But, on the other hand, I'm thinking that writing in bash is more universal solution. I mean that requirements to run bash scripts are lower than requirements to run Python scripts. Could this requirements be decisive for some users (or is it only my imagination)? Sometimes users just have no access to Python (e.g. LFS, some stages of Gentoo, some rescue and specialized distros). And there's also something more. For now "Python Builder" works in text mode. It was written in bash and I assumed it should be some kind of "basic" tool - so text mode and bash seemed to be the best choice. But if I rewrote all code in Python I could make some GUI. It could works even better - I could easily check if GUI mode is available and run in proper (GUI or text) mode. But is GUI needed by people who just want it to do it's job and quit? Well, what do you think? From sigzero at gmail.com Mon Jun 13 20:47:03 2005 From: sigzero at gmail.com (sigzero at gmail.com) Date: 13 Jun 2005 17:47:03 -0700 Subject: win32evtlog In-Reply-To: <7PydnRpfyLjuuzPfRVn-qA@powergate.ca> References: <1118705839.260490.13140@z14g2000cwz.googlegroups.com> <7PydnRpfyLjuuzPfRVn-qA@powergate.ca> Message-ID: <1118710023.098700.252130@g43g2000cwa.googlegroups.com> Doh! I didn't think to look in the demo directory. Silly me. From stephen at theboulets.net Mon Jun 27 20:02:18 2005 From: stephen at theboulets.net (stephen at theboulets.net) Date: 27 Jun 2005 17:02:18 -0700 Subject: Photo layout In-Reply-To: <42C00246.5000602@syscononline.com> References: <42C00246.5000602@syscononline.com> Message-ID: <1119913712.104637.65480@o13g2000cwo.googlegroups.com> Thanks! This works well -- I was letting myself be too intimidated with reportlab before looking at the documentation, but it was really not hard at all. I think I figured out how to do landscape mode too. from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter def insertPicture(c): ....c.drawInlineImage("geese1.jpg",100,100,200,150) width, height = letter letter = height, width # change to landscape c = canvas.Canvas("picture.pdf",pagesize=letter) insertPicture(c) c.showPage() c.save() Larry Bates wrote: > You can use Python Imaging Library (PIL) and ReportLab to resize and > place the photos on a page quite easily. Actually ReportLab calls > PIL automatically to resize the photos when you call .drawInlineImage > method of the canvas object with the proper width and height arguments. > > To get ReportLab go to: http://www.reportlab.org > > Note: I'm assuming the photos are in .JPG, .TIF or some format that > PIL can recognize. If they are in some proprietary RAW format you > will need to convert them first. > > -Larry Bates > > Stephen Boulet wrote: > > Is there a python solution that someone could recommend for the following: > > > > I'd like to take a directory of photos and create a pdf document with > > four photos sized to fit on each (landscape) page. > > > > Thanks. > > > > Stephen From hancock at anansispaceworks.com Wed Jun 15 13:36:52 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 15 Jun 2005 12:36:52 -0500 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42aeeee1$1@nntp0.pdx.net> References: <42AED7B3.8060009@carmen.se> <42aeeee1$1@nntp0.pdx.net> Message-ID: <200506151236.52105.hancock@anansispaceworks.com> On Tuesday 14 June 2005 10:21 am, Scott David Daniels wrote: > > Oh well, I guess it's a bit late to try to rename the Computer > > Science discipline now. > The best I've heard is "Informatics" -- I have a vague impression > that this is a more European name for the field. It's the reverse-translation from the French "Informatique". -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From sameer_deshpande at hotmail.com Thu Jun 23 16:52:21 2005 From: sameer_deshpande at hotmail.com (sameer_deshpande) Date: 23 Jun 2005 13:52:21 -0700 Subject: key - key pairs In-Reply-To: References: Message-ID: <1119559941.884716.273690@f14g2000cwb.googlegroups.com> Just an example of dictionary object in python. PythonWin 2.4.1 (#65, Mar 30 2005, 09:33:37) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> d = {} >>> d["key1"] = "value1" >>> d["key2"] = "value2" >>> d["key3"] = "value3" >>> d["key3"] = "value3" >>> >>> for i, j in d.items(): ... print i, j ... key3 value3 key2 value2 key1 value1 >>> if d.has_key("key1"): ... print d["key1"] ... else: ... print "no key" ... value1 >>> if d.has_key("not in dict"): ... print d["key1"] ... else: ... print "no key" ... no key >>> HTH Sameer From reder at ieee.org Sat Jun 18 02:00:56 2005 From: reder at ieee.org (Leonard J. Reder) Date: Sat, 18 Jun 2005 06:00:56 GMT Subject: Multithreaded Python FSM (Harel State Machines) In-Reply-To: <42b19477$0$19556$626a14ce@news.free.fr> References: <42b19477$0$19556$626a14ce@news.free.fr> Message-ID: WOW! Thanks, this looks remarkabley close to what I was talking about. Len fraca7 wrote: > Leonard J. Reder a ?crit : > >> [snip] > > > http://smc.sourceforge.net/ > > It's probably not what you're looking for, but it's the closest I can > think of. From wuwei23 at gmail.com Sun Jun 5 20:53:07 2005 From: wuwei23 at gmail.com (alex23) Date: 5 Jun 2005 17:53:07 -0700 Subject: Pythonic Gotchas In-Reply-To: References: Message-ID: <1118019187.206625.96800@g49g2000cwa.googlegroups.com> Ivan Van Laningham wrote: > This little gotcha ought to be number one on "The Official List of > Pythonic Gotchas," which should be required reading for everyone. > > What? There isn't one? Why not? There's at least one active "Python Gotchas" page out there: http://www.ferg.org/projects/python_gotchas.html The last update was in April. -alex23 From usenet.20.evilspam at spamgourmet.com Sun Jun 12 17:00:25 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 21:00:25 GMT Subject: How to get/set class attributes in Python In-Reply-To: <42ac9250$0$4934$636a15ce@news.free.fr> References: <42ac6b5b$0$27173$626a14ce@news.free.fr> <42ac9250$0$4934$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Chris Spencer a ?crit : > >> I was providing the original poster with a simple way to ensure >> appropriate type. > > > s/appropriate type/specific implementation/ > > Hint : the appropriate type for print >> XXX is "whatever has a > 'write(anything_that_can_be_coerced_to_a_string)' method". Certainly, although now I think you're splitting hairs over my terminology. Let's synchronize our wording with a point made in the Python docs. Section 2.1 of the Library Reference recommends that the builtin function isinstance() be used for testing the object type. Does this then mean that "type" refers to the class of an object? In which case, wouldn't "interface" refer to a collection of methods, that when present in a class create an implementation? Chris From kent37 at tds.net Wed Jun 8 08:35:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Jun 2005 08:35:39 -0400 Subject: Knowing the signature of a function In-Reply-To: References: Message-ID: <42a6e5cc$1_3@newspeer2.tds.net> Xavier D?coret wrote: > Hello, > > I have the following code: > > def foo(x,y): > pass > > How can I query the function object foo to know the number of parameters > it expects. I can find it is a function using callable(f), I can find > some information (listed by dir(foo)) such as the name of the > function,etc.. but nowhere I can find the number of arguments. > > I would like to know wether the function expects one or zero arguments. foo.func_code.co_argcount gives the count of named args. len(foo.func_code.co_varnames) gives the total number of arguments including *args and **kwds args. inspect.getargspec() might also be helpful. Kent From gregpinero at gmail.com Wed Jun 22 11:37:54 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 22 Jun 2005 11:37:54 -0400 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: <312cfe2b05062208376a966af4@mail.gmail.com> I always figured a problem with using MySQL was distribution. Would you have to tell your users to install MySQL and then to leave the service running? I've never found an easy way to embed MySQL into a python app, and even if you could, would you then have to pay for it? -Greg On 6/22/05, Thomas Bartkus wrote: > "Will McGugan" wrote in message > news:42b97240$0$24467$da0feed9 at news.zen.co.uk... > > Hi, > > > > I'd like to write a windows app that accesses a locally stored database. > > There are a number of tables, the largest of which has 455,905 records. > > > > Can anyone recommend a database that runs on Windows, is fast / > > efficient and can be shipped without restrictions or extra downloads? > > > > I have googled and found plenty of information on databases, its just > > that I dont have enough experience with databases to know which one is > > best for my task! > > If you are writing strictly for the MS Windows platform > And > If the database is running single user with a "locally stored database" on a > Windows workstation. > Then > The MS Access file based (.mdb) system is hard to argue with. > You wouldn't have to distribute the (rather expensive) Access application > since this is little more than a front for the underlying DAO/ADO database > libraries that are built into the warp and woof of MS Windows. Your Python > application can address the DAO or ADO directly as these will libraries will > be pre-installed and/or freely available for MS Windows. Fast, freely > available, no license restrictions, and no need for extra downloads for a > reasonably recent (Win2000, XP) operating system. > > On the other hand, if operating system portability were a concern (as it > should be!), I might suggest MySQL. > A Python/MySQL application can jump between Windows to Linux (all flavors!) > to Unix to BSD without need to alter a single line of code. > > You were writing a Python app, weren't you :-) > Thomas Bartkus > > > -- > http://mail.python.org/mailman/listinfo/python-list > From lycka at carmen.se Wed Jun 22 11:15:28 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 22 Jun 2005 17:15:28 +0200 Subject: Database recommendations for Windows app In-Reply-To: <42b97240$0$24467$da0feed9@news.zen.co.uk> References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Hi, > > I'd like to write a windows app that accesses a locally stored database. > There are a number of tables, the largest of which has 455,905 records. > > Can anyone recommend a database that runs on Windows, is fast / > efficient and can be shipped without restrictions or extra downloads? > > I have googled and found plenty of information on databases, its just > that I dont have enough experience with databases to know which one is > best for my task! Neither do we, considering that brief description. Will there be multiple simultaneous users? Multiple simultaneous writers? Do you require proper transaction management? (Or is it a pure read-only database, since you know exactly how many records the largest table has?) Do you need to make ad-hoc queries? What will your code look like? * Is it object-oriented? * Are there a lot of fixed relations between objects? Are there other requirements such as need for undo or change history management? Does the application work with small chunks of data at a time (such as in a ticket ordering system) or with larger chunks (such as in a web site CMS)? What size is it? It's a big difference between 455,905 integers and 455,905 mp3 files for instance... "A number of tables" tells us very little, more than suggesting that it's more than one... Ten and 200 makes a big difference. From renting at astron.nl Thu Jun 30 04:51:22 2005 From: renting at astron.nl (Adriaan Renting) Date: Thu, 30 Jun 2005 10:51:22 +0200 Subject: No subject Message-ID: I do fundamentally not agree with you that IDE's and GUI design tools are a waste of time. I think that with a good IDE (graphical or not) the synergy between editor, debugger, documentation, refactoring, translations/internationalization, version control, software modelling, profiling, metrics, can be very valuable. Example: At my first employer we could do the same projects in 60% of the time with Borland C++Builder, compared to MS VisualC++ 6. We would put this into offerings to customers, esp. if they had a corporate policy prefering VS 5 or 6. Some features I realy line about some IDE's I've used: - Automatic generation of UML diagrams from project code. - Runtime expression evaluation/data inspection/editing. - Pressing F1 will bring up the documentation of the class and method your cursor is on. - The debugger detects if an object is never deleted in C++, and put me on the right line in the editor where it is created. - Include trees. - Code completion. - Automatic management of versions in different languages. - Comparison with older versions of the code. - Wizards to generate often used dialogs. If you have never tried Java with Eclipse, C++ with C++Builder or VisualStudio.Net 2003, or even Python with the less elaborate Eric3+QtDesigner, then I suggest you do. Of all the Widget sets I've used (MFC, VCL, wxWindows, TVision, Athena, Qt) I consider Qt the easiest, it's even available for free on Windows now! There is one danger in using IDE's to design GUI's, which is that you do not properly separate your GUI code from the mechanics of the program. I think that the natural way to design a GUI is with a WYSIWYG tool. You have a valid point that you have to conform to the IDE generated code to some extent. A good IDE will have a nonobtrusive way of handling this. ----------- Everything below here is Harry George's mail. ---------------------------------------------- ----------- No the e-mail program I am forced to use does not support quoting. ----------------- >>> 06/28/05 9:15 PM >>> #! rnews 2994 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 57 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1119898281.201400.85040 at o13g2000cwo.googlegroups.com> <1119956464.362328.290370 at o13g2000cwo.googlegroups.com> Mime-Version: 1.0 Date: Tue, 28 Jun 2005 18:58:08 GMT Xref: news.xs4all.nl comp.lang.python:383798 phil writes: > > > > You are quite correct to point out how much better it is to know what is > > going on behind the scenes. But heck, once you know how to extract square > > roots - you need to let the computer do it! > > GUI interfaces should be the same deal! > > Thomas Bartkus > > > I think I pretty much agree. I essentially code my own gui builder > > but in text files. > > I just think it is really important to emphasise the operative > "but once you know how" in your comments. > > Then some would counter with "oh, so we should code everthing > in assembler?" Ouch. No, I will admit there is judgement > required. Everything should be done the easiest way, with the > qualification that you need to understand how using someone > else's shortcut leaves you vulnerable. I agree with your comments on Python and java and IDEs. I'd like to expand on the "code in assy" complaint. Compiled-to-assy-to-machine-to-execution is understood and algorithmic. Any one person may no know it al,l but every step of the way has been thought out and optimized by someone who knew what he/she was doing. There are very few places where anyone has to dive down into assy, much less microcode or VLSI layouts. Therefore, we can trust the abstract model provided by the programming language, and can stay in that model. This is not the case for GUIs. We can't safely stay in the abstract GUI IDE. In fact, most require you to dive into the generated code to finish the task. Bouncing up and down the abstraction ladder is hard and made harder by being forced to live in the IDE's idea of generated code. Given that, GUI IDEs are still helpful if your base langauge is a pain to write and debug (e.g., C++, Java). But if your language is actually easier to use than the GUI IDEs, then the equation shifts. With Python, the clarity of thought and the opportunities for higher-level programming (dynamic code genration et al) make GUI IDEs just a waste of time or worse. I also have moved to text-based inputs to my own GUI builders. Maybe there is a sourceforge project waiting to be borne here :-) [snip] -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 -- http://mail.python.org/mailman/listinfo/python-list From duncan.booth at invalid.invalid Wed Jun 1 06:41:03 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2005 10:41:03 GMT Subject: working with pointers References: Message-ID: Shane Hathaway wrote: > Michael wrote: >> sorry, I'm used to working in c++ :-p >> >> if i do >> a=2 >> b=a >> b=0 >> then a is still 2!? >> >> so when do = mean a reference to the same object and when does it >> mean make a copy of the object?? > > To understand this in C++ terms, you have to treat everything, > including simple integers, as a class instance, and every variable is > a reference (or "smart pointer".) The literals '0' and '2' produce > integer class instances rather than primitive integers. Here's a > reasonable C++ translation of that code, omitting destruction issues: > > class Integer > { > private: > int value; > public: > Integer(int v) { value = v; } > int asInt() { return value; } > } > > void test() > { > Integer *a, *b; > a = new Integer(2); > b = a; > b = new Integer(0); > } > A closer translation would be: const Integer CONST0(0); const Integer CONST2(2); void test() { const Integer *a, *b; a = &CONST0; b = a; b = &CONST2; } The constant integers are created in advance, not when you do the assignment. Arithmetic may create new Integer objects, but when the result is a small integer it simply reuses an existing object. From danricofer at gmail.com Wed Jun 8 09:03:03 2005 From: danricofer at gmail.com (Daniel) Date: 8 Jun 2005 06:03:03 -0700 Subject: Changing entities Message-ID: <1118235783.224018.281490@g44g2000cwa.googlegroups.com> Hello all I need to build a program that check the sintax in a line: SIZE (1 BYTE) and change the correct number of bytes to the following format: SIZE(1) without the "BYTE" word. But, the number of bytes can be over 3 digits, and the entitie can't have spaces but the correct number of bytes in parentheses, like "SIZE (1024 BYTE)" to "SIZE(1024)". Does anyone already done this or similar sintax using re? Thank you From sjmachin at lexicon.net Wed Jun 1 17:20:59 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 07:20:59 +1000 Subject: creating a hex value In-Reply-To: <1117652142.697576.85300@o13g2000cwo.googlegroups.com> References: <1285743.rKB6TKaXDy@teancum> <1117652142.697576.85300@o13g2000cwo.googlegroups.com> Message-ID: <429e26ba@news.eftel.com> wittempj at hotmail.com wrote: > What about > > martin at lijnbaansgracht:~$ python > Python 2.3.5 (#2, May 4 2005, 08:51:39) > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>hex(21) > > '0x15' > > >>> len('0x15') 4 Quadruple sheeeeeeeeeeeeeesh. From fredrik at pythonware.com Tue Jun 14 15:34:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 21:34:41 +0200 Subject: Tiff Image Reader/writer References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com><1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118751946.686069.295910@g44g2000cwa.googlegroups.com> Message-ID: "PyPK" wrote: > I get a decoder error when i do a get pixel on the Image > > >>> im.getpixel((12,34)) > > Traceback (most recent call last): > File "", line 1, in ? > File "Image.py", line 858, in getpixel > self.load() > File "/usr/local/lib/python2.4/site-packages/PIL/ImageFile.py", line > 180, in load > d = Image._getdecoder(self.mode, d, a, self.decoderconfig) > File "Image.py", line 328, in _getdecoder > raise IOError("decoder %s not available" % decoder_name) > IOError: decoder group4 not available PIL doesn't support CCITT encodings out of the box. the following patch might help: http://mail.python.org/pipermail/image-sig/2003-July/002354.html (unfortunately, this currently depends on libtiff internals, which is why it wasn't added to 1.1.5) an alternative solution is to pipe your files through tiffcp (see James mail for details). From paschott at no.yahoo.spamm.com Fri Jun 17 19:06:12 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Fri, 17 Jun 2005 23:06:12 GMT Subject: Alternative Ways to install Python 2.4? References: <41F43373.4020003@v.loewis.de> <1118954386.789156.271950@f14g2000cwb.googlegroups.com> Message-ID: Only thing I know to watch out for is they don't include SSL support - something the Python 2.4.1 msi file does include. I needed that for something I'm working on and had to install 2.4.1 over ActivePython to get the SSL support. -Pete David Van Mosselbeen wrote: > James wrote: > > I have also some troubleshouting when i will work on mapped drives. > Let's take a example : > A Word doc on a mapped drive. Double click on it (i try to open it). > And waiting ... > waiting... > nothing do > > > If this is a bug with the standard distribution alone, maybe he can try > > ActiveState's distribution (ActivePython) instead. > > When i work on Windows XP i use Python distributed by the ActiveState's and > find that ActiveState's included really good stuff into this package. It's > a really good when you plan to use it on a Windows box. From aahz at pythoncraft.com Mon Jun 27 13:57:08 2005 From: aahz at pythoncraft.com (Aahz) Date: 27 Jun 2005 10:57:08 -0700 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: In article <11bs1bc5jotvg9c at news.supernews.com>, John Roth wrote: > >What's being ignored is that type information is useful for other >things than compile type checking. The major case in point is the >way IDEs such as IntelliJ and Eclipse use type information to do >refactoring, code completion and eventually numerous other things. A >Java programmer using IntelliJ or Eclipse can eliminate the advantage >that Python used to have, and possibly even pull ahead. Perhaps. But adding the time to learn those IDEs in addition to the time to learn Java is ridiculous. I've been forced to use Java a bit to support credit cards for our web application; I've got a friend whose Java-vs-Python argument hinges on the use of Eclipse; I was unable to make use of Eclipse in the time I had available for the project. Meanwhile, I'm busy with a code base that I doubt any IDE could handle... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From daniel.dittmar at sap.corp Wed Jun 22 04:39:45 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 22 Jun 2005 10:39:45 +0200 Subject: *Python* Power Tools In-Reply-To: References: Message-ID: Micah wrote: > Anyone know if there is any organized effort underway to implement the > Python equivalent of "Perl Power Tools" ? > > If not, would starting this be a waste of effort since: > > - it's already being done in Perl? > - cygwin thrives? > - UNIX is already pervasive :-) ? > > Or would people really like to claim a pure Python set of UNIX > utilities? There would be some use for a Python library that implements the functionality of these tools. Some of it already exists (difflib, shutil). Some is probably more difficult and less flexible to use from a lib that from straight python (cut). Perhaps that could be started either in the Python Cookbook (http://aspn.activestate.com/ASPN/Python/Cookbook/) or the Python Wiki (http://wiki.python.org/moin/). Just short explanations of how you would implement the functionality of various Unix utilities in Python. Daniel From ncoghlan at gmail.com Thu Jun 30 05:21:41 2005 From: ncoghlan at gmail.com (NickC) Date: 30 Jun 2005 02:21:41 -0700 Subject: Favorite non-python language trick? References: Message-ID: <1120123301.008765.134700@g14g2000cwa.googlegroups.com> Steven D'Aprano wrote: > with colour do begin > red := 0; blue := 255; green := 0; > end; > > instead of: > > colour.red := 0; colour.blue := 255; colour.green := 0; c = colour c.red = 0; c.blue = 255; c.green = 0 del c # Not strictly needed, but limits the scope of c When everything's a reference, the Pascal 'with' syntax doesn't gain you anything over a single-letter variable name. As I recall, it's handy in Pascal because record assignment has value semantics rather than reference semantics. Cheers, Nick. From hancock at anansispaceworks.com Wed Jun 1 15:04:39 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Jun 2005 14:04:39 -0500 Subject: Software licenses and releasing Python programs for review In-Reply-To: <1117392779.263376.236200@o13g2000cwo.googlegroups.com> References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> Message-ID: <200506011404.39906.hancock@anansispaceworks.com> On Sunday 29 May 2005 01:52 pm, poisondart wrote: > With the exception of the example with neighbour Bobby (which directly > utilizes my code for profit, in which case is a definite no), I don't > see why your other examples should make me reconsider releasing my > software for free--in all the cases you've described, the answer should > be no. > [...] You have an awfully possessive attitude for someone who's asking for free help. What are you planning to pay us for the consulting? "Go get a lawyer and pay them for their time, just like any other proprietary code-horder." :-P Only half tongue-in-cheek. ;-) Seriously though, you are violating the community principles that make Python and this newsgroup function. That's a selfish and thoughtless thing to do if you will but think about it for a moment. I have no interest in your software and it pollutes my environment if it is going to spew legal landmines into my life! I'd rather you just charged a license fee so that people would more quickly realize that it is a hazard. That will encourage a truly free replacement to be made, which would actually be of some benefit to the community and (ironically and incidentally) to you as well. The fact is, people who distribute your code for you are doing you a favor which it is not unreasonable for them to receive a remuneration for. The pitiful small cost that the market drives things like CD collections of free software to makes the practical impact of allowing such sales virtually nil. Certainly it has no effect on you. No one I know misrepresents that as "ownership" of the software --- it's just a copying/convenience or review service, and that's what the prices represent. Heck, I can review MS Windows in a magazine, and you'd call it profiteering freely without paying them a license fee. God help us all if the courts were ever to accept such interpretations. And the "principle of the thing" is nonsense: you are asking for something for nothing. If you want the advantages of free software (peer review, easy distribution, etc) you need to embrace the whole package, which includes the most basic user freedoms. *That* would be the principled thing to do. Mind you, "academic use" is also commercial, by your ridiculously broad interpretation of commercial use: Surely other scholars, if they make use of your software will be using it to justify their salaries, won't they? Of course, you're *entitled* to use any twisted, snare-throwing license you like, but don't expect to be respected for it. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ajikoe at gmail.com Wed Jun 8 09:44:40 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 8 Jun 2005 06:44:40 -0700 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> Message-ID: <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Hello thanks everyone, It means in windows we should use 'wb' to write and 'rb' to read ? Am I right? pujo From philippe at philippecmartin.com Tue Jun 28 18:26:47 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 22:26:47 GMT Subject: Embedding python in C - newbie References: <3Qfwe.519$Ox3.92@newssvr12.news.prodigy.com> Message-ID: Just to make sure i'm clear as I've been told about swig and pyrex: I don't want to eventually have a python script call C modules, but rather a main.c make calls to python functionnalities. I did add newbie in the title :-) Regards, Philippe Philippe C. Martin wrote: > Hi, > > Is there a program out there that would generate the C code to instantiate > objects and call them: > > ex: miracle.exe -i mymodule.py -o module_internface.c ? > > I seem to recall a _yes_ to that but I got a memory overflow :-) > > Thanks, > > Philippe From Gerald.Klix at klix.ch Fri Jun 17 08:10:27 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Fri, 17 Jun 2005 14:10:27 +0200 Subject: strxfrm works with unicode string ? In-Reply-To: <1119003766.658567.228590@g14g2000cwa.googlegroups.com> References: <1118997804.678723.170070@g44g2000cwa.googlegroups.com> <1119003766.658567.228590@g14g2000cwa.googlegroups.com> Message-ID: <42B2BDB3.6070303@klix.ch> Sali Nicolas :)), please see below for my answers. nicolas.riesch at genevoise.ch schrieb: > Gru?zi, Gerald ;-) > > Well, ok, but I don't understand why I should first convert a pure > unicode string into a byte string. > The encoding ( here, latin-1) seems an arbitrary choice. Well "latin-1" is only encoding, about which I know that it works on my xterm and which I can type without spelling errors :) > > Your solution works, but is it a workaround or the real way to use > strxfrm ? > It seems a little artificial to me, but perhaps I haven't understood > something ... In Python 2.3.4 I had some strange encounters with the locale module, In the end I considered it broken, at least when it came to currency formating. > > Does this mean that you cannot pass a unicode string to strxfrm ? This works here for my home-grown python 2.4 on Jurrasic Debian Woody: import locale s=u'\u00e9' print s print locale.setlocale(locale.LC_ALL, '') print repr( locale.strxfrm( s.encode( "latin-1" ) ) ) print repr( locale.strxfrm( s.encode( "utf-8" ) ) ) The output is rather strange: ? de_DE "\x10\x01\x05\x01\x02\x01'@/locale" "\x0c\x01\x0c\x01\x04\x01'@/locale" Another (not so) weird thing happens when I unset LANG. bear at special:~ > unset LANG bear at special:~ > python2.4 ttt.py Traceback (most recent call last): File "ttt.py", line 3, in ? print s UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) Acually it's more weird, that printing works with LANG=de_DE. Back to your question. A quick glance at the C-sources of the _localemodule.c reveals: if (!PyArg_ParseTuple(args, "s:strxfrm", &s)) So yes, strxfrm does not accept unicode! I am inclined to consider this a bug. A least it is not consistent with strcoll. Strcoll accepts either 2 strings or 2 unicode strings, at least when HAVE_WCSCOLL was defined when python was compiled on your plattform. BTW: Which platform do you use? HTH, Gerald PS: If you have access to irc, you can also ask at irc://irc.freenode.net#python.de. -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From sjmachin at lexicon.net Wed Jun 1 21:31:42 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 11:31:42 +1000 Subject: Performance Issues please help In-Reply-To: <1117675259.678036.18340@f14g2000cwb.googlegroups.com> References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> <429E59C2.8010405@lexicon.net> <1117675259.678036.18340@f14g2000cwb.googlegroups.com> Message-ID: <429E617E.80503@lexicon.net> PyPK wrote: > > I am suspecious abput dictionary approach here. Is this slower than if > i do it with arrays or lists with index of array as my key ? > "with index of array as my key" is either redundant -- indicating that your answer to my question about "e" should have included something like "e is an integer that can range from blah0 to blah_max" -- or not understandable. In any case, seeing that the code in question is only a few lines, why don't *you* write an alternative version and see how fast it runs? And let us know? From martin.witte at gmail.com Wed Jun 22 08:59:14 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 22 Jun 2005 05:59:14 -0700 Subject: Reading registry export files In-Reply-To: <42b92291$0$1334$5fc3050@dreader2.news.tiscali.nl> References: <42b92291$0$1334$5fc3050@dreader2.news.tiscali.nl> Message-ID: <1119445154.541756.274030@g43g2000cwa.googlegroups.com> It works fine for me on NT. I think it has nothing to do with Python but with the way the file is created - what windows version are you on? Also note the possibility the '/' - I prefer a noatation like below to avoid ambiguity. Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> f = open(r"d:\test.reg") py> r = f.read() py> print r REGEDIT4 I would do it like this however, then join all lists from various .reg files: py> f = open(r'd:\test.reg') py> r = f.readlines() py> print r ['REGEDIT4\n', '\n', '[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Ole]\n', '"Enabl eDCOM"="Y"\n', '"DefaultLaunchPermission"=hex:01,00,04,80,64,00,00,00,80,00,00,0 0,00,00,00,00,\\\n', ' 14,00,00,00,02,00,50,00,03,00,00,00,00,00,18,00,01,00,00 ,00,01,01,00,00,00,\\\n', ' 00,00,05,12,00,00,00,00,00,00,00,00,00,18,00,01,00, 00,00,01,01,00,00,00,00,\\\n', ' 00,05,04,00,00,00,00,00,00,00,00,00,18,00,01,0 0,00,00,01,02,00,00,00,00,00,\\\n', ' 05,20,00,00,00,20,02,00,00,01,05,00,00,00 ,00,00,05,15,00,00,00,a0,5f,84,1f,\\\n', ' 5e,2e,6b,49,ce,12,03,03,f4,01,00,00, 01,05,00,00,00,00,00,05,15,00,00,00,a0,\\\n', ' 5f,84,1f,5e,2e,6b,49,ce,12,03,0 3,f4,01,00,00\n', '\n'] >>> [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Ole] "EnableDCOM"="Y" "DefaultLaunchPermission"=hex:01,00,04,80,64,00,00,00,80,00,00,00,00,00,00,00, 14,00,00,00,02,00,50,00,03,00,00,00,00,00,18,00,01,00,00,00,01,01,00,00,00,\ 00,00,05,12,00,00,00,00,00,00,00,00,00,18,00,01,00,00,00,01,01,00,00,00,00,\ 00,05,04,00,00,00,00,00,00,00,00,00,18,00,01,00,00,00,01,02,00,00,00,00,00,\ 05,20,00,00,00,20,02,00,00,01,05,00,00,00,00,00,05,15,00,00,00,a0,5f,84,1f,\ 5e,2e,6b,49,ce,12,03,03,f4,01,00,00,01,05,00,00,00,00,00,05,15,00,00,00,a0,\ 5f,84,1f,5e,2e,6b,49,ce,12,03,03,f4,01,00,00 From tiissa at nonfree.fr Sat Jun 11 04:18:58 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 11 Jun 2005 10:18:58 +0200 Subject: If - Or statements In-Reply-To: <1118157507.942274.45410@g43g2000cwa.googlegroups.com> References: <1118157507.942274.45410@g43g2000cwa.googlegroups.com> Message-ID: <42aa9e72$0$6109$636a15ce@news.free.fr> Patrick Down wrote: > What about: > > if True in [thefile.endswith(x) for x in > ('mp3','mp4','ogg','aac','wma')]: That will catch (widely used) file names such as 'tmp3' or 'i_cant_spell_frogg'. ;) From philippe at philippecmartin.com Thu Jun 9 09:04:02 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 09 Jun 2005 13:04:02 GMT Subject: Generating HTML from python References: Message-ID: <67Xpe.2446$%j7.824@newssvr11.news.prodigy.com> PS: I am looking at the formatter module which seems to be related to HTML somehow, but without any code sample I'm a bit lost Philippe C. Martin wrote: > Hi, > > I wish to use an easy way to generate reports from wxPython and feel > wxHtmlEasyPrinting could be a good solution. > > I now need to generate the HTML wxHtmlEasyPrinting can print: I need to > have a title followed by lines of text that do not look too ugly. If > possible I would like to use an existing module. > > Q1) Is there such a module ? > Q2) Is my approach fairly good ? > > Regards, > > Philippe From d at e.f Sun Jun 26 00:49:57 2005 From: d at e.f (D H) Date: Sat, 25 Jun 2005 23:49:57 -0500 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: Message-ID: Dave Benjamin wrote: > One thing Guido mentions in his comparison of ABC (Python's predecessor) and > Python is how ABC was inextricably tied to its environment (a la Smalltalk), What surprised me was that this was the only thing he really mentioned. He didn't mention anything about the theoretical underpinnings of ABC, he was only involved in the implementation of ABC, and others did all the language design. And his main criticism is a pragmatic issue with using the ABC in real tasks like reading external files. It explains why sometimes Python's features seem to be more implementation-driven rather than design-driven. Such as perhaps the use of self, but a counter-example is slicing syntax, borrowed from the language Icon apparently. I think when you borrow some features from a language but not all, you have to re-evaluate every part of the language design. Colons at the end of lines for example help readability in the ABC language because keywords are all uppercase (unlike python). So the colons in effect counteract some of the negative impact uppercase words place on readability. In Python however, I don't see how colons really are needed to help readability at all. And there are other issues too such as changing python to be case-insensitive or making 7/4 == 1.75 instead of 1 which even Guido wanted at one point ( http://www.linuxjournal.com/article/5028 ), but only the latter was implemented (yet not enabled by default yet). > I find that a similar comparison can be made between Python and Java. Java's > startup time is so long that it is not practical for writing small tools for > use in command-line scripts, and the propensity toward application servers > and integrated development environments suggests a strong preference for a > monolithic, self-contained, single-language environments. That's a very good point. Yeah you never hear of people using java for making quick little scripts, which python and php are really great for (among other things). > Guido makes a funny jab at Paul Graham about Graham's nine things that make > Lisp Lisp (available here: http://www.paulgraham.com/icad.html) - I had read > this essay many times but never saw the subtle irony behind claims of > "Greenspunning": in order to claim that a language is approaching Lisp, you > have to define what it is about Lisp that other languages are purportedly > emulating, and this begs the question of why you have the authority to > declare which 9 (or n) attributes of Lisp are most important. I like Paul > Graham and his essays a lot, but I must admit I had to laugh too when I > heard the way Guido framed this argument. I'm not so sure that Python has 8 > out of 9, though: the statement/expression dichotomy rules out #6, and the > lack of macros rules out #9. These are arguable, depending on how you define > things, but I think the most obvious thing that Python lacks compared with > Lisp and Scheme (and also Ruby) is a symbol type (#7). I'm in the process of > trying to understand what symbols are good for, outside the context of Lisp > and its nested lists of symbols as executable code. Ruby seems to have come > up with some creative uses for symbols within Python-like syntax, though I > haven't seen anything terribly compelling so far. Other python extensions and descendants I mentioned in this note are exploring the two main things lisp has but python doesn't - #6 eliminating the expression/statement distinction (at least in some cases like assignments), and #9 macros: http://groups-beta.google.com/group/comp.lang.python/msg/360c99b7ab7b839c?dmode=print&hl=en > - Java: the usual static vs. dynamic, static analysis vs. unit testing > arguments. Guido says that there's such a small amount of problems that > can be caught at compile time, and even the smallest amount of unit > testing would also catch these problems. "The blindness of that [static] > position... escapes me." As pointed out elsewhere, type declarations also help with documenting your code, as well as dramatically speeding up your program. > I think Python's decision to use reference counting was an instance of > worse-is-better: at the time, reference counting was already known not to be > "the right thing", but it worked, and the implementation was simple. > Likewise with dynamic typing versus type inference. It seems that Guido > shares Alan Kay's viewpoint that type inference is really "the right thing", > but modern language technology is really not ready to make it mainstream, > whereas dynamic typing works today, and is arguably a better "worse" > solution than explicit/manifest static typing due to its verbosity. That's very interesting. Type inference isn't always perfect though. There are some cases where it can't infer the type, or it infers the wrong type that you really want. Type inference + dynamic typing is a good combination that can speed up your code without slowing down your coding. > Type inferencing is especially difficult to add to a dynamically typed > language, and in general I think results are much better if you have type > inference from the very beginning (like ML and Haskell) rather than trying > to retrofit it later. It's easier to add dynamic typing to a type inferenced, statically typed language. > Someone in the audience mentioned that the CPython VM is so solid they're > surprised nobody's implemented a Java program on top of the Python VM (as > opposed to the other way around, as in Jython). The CPython VM is really geared specifically for the Python alone, and Python's dynamic typing. It's no wonder other languages haven't been built upon it unlike the java VM or the .NET/Mono CLR. Someone in the audience > surprised everyone by mentioning an actual project attempting this, called > javaclass: Sounds like it really is converting java classes to python classes, which are very different things. Lot of limitations mentioned such as: "It runs on the Python runtime which does not have the security, threading and just-in-time compiler features that people enjoy about Java runtimes" From tjreedy at udel.edu Wed Jun 1 19:23:40 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 19:23:40 -0400 Subject: bug with isinstance() ? References: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> <1117664364.603412.73230@g49g2000cwa.googlegroups.com> Message-ID: "Mac" wrote in message news:1117664364.603412.73230 at g49g2000cwa.googlegroups.com... >I see, interesting. OK, I understand that recursive importing can be > problematic (having to "hide" the test2 import should have been a tip > off; it's just that in my original app this relationship is not as > clear), but what is the lesson I should take away from this? I suspect that the import hiding was needed to avoid infinite recursion but is not essential in itself to getting duplicate class Foo objects. > I mean, I > was under the impression that "once a Foo, always a Foo", while from > the above I'm starting to see that a single class definition can give > rise to a multiple number of classes, Unless you intend this, it is probably a programming error on your part. > and that the classes are > parametrized by the module they come from (I guess that makes sense... > else class names would have to be unique throughout all the source for > a single program) There is nothing special about classes here. >... I guess the problem is I'm thinking of "classes" > as these abstract concepts, sort of like Platonian "forms", whereas I > should be thinking of classes as "class objects", Definitely. In Python, 'everything' is an object. Understanding this is a key to understanding Python programming. > Someone help me wrap my head around this, please. :) Here is the source of your particular problem. Running 'python somefile.py' is more or less equivalent to a hidden single-line program: 'import somefile.py as __main__'. The code in somefile is used to populate the main module, named '__main__'. If the code in somefile.py (or .pyc) leads, directly or indirectly, to execution of 'import somefile', the import function looks for an existing module named (bound to, in sys.modules, for CPython) 'somefile'. Not finding one, it create a new module, names it 'somefile', and populates it from somefile.py. Now there are duplicate modules and probably a program bug. This is not the only way to get two modules from one file. One can give import different access paths to a file such that it will not recognize that it has already imported the file. But this too is almost certainly an error. One way people avoid importing the main module file after startup is to limit it to top-level code with no class or function definitions that might need to be imported elsewhere. But when a module of definitions, intended for import, has an "if __name__ == '__main__': test()" section for testing purposes, then more care may be needed. Terry J. Reedy From hancock at anansispaceworks.com Fri Jun 17 00:39:02 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 16 Jun 2005 23:39:02 -0500 Subject: dir() with string as argument In-Reply-To: <1d1bb26a6f8fea4d04682e0d89daf9e6@upf.edu> References: <47d5f088340cd.42b193c4@Princeton.EDU> <1d1bb26a6f8fea4d04682e0d89daf9e6@upf.edu> Message-ID: <200506162339.02773.hancock@anansispaceworks.com> On Thursday 16 June 2005 02:19 pm, harold fellermann wrote: > On 16.06.2005, at 20:59, Shankar Iyer (siyer at Princeton.EDU) wrote: > > Suppose I have a string, sModuleName, that contains the name of a > > module. I now want to see what functions are in that module, but if I > > call dir(sModuleName), I instead get the list of operations that can > > be done on a string. Is there any way to convert the string into a > > format that I could feed to dir to cause the desired effect? I think > > I could modify the string a bit and then use the exec command, but I > > was advised against that on this board last week. > > you have to import the module: > > name = "sys" > mod = __import__(name) > dir(mod) Note that if the module is already imported, this costs you almost nothing --- __import__() will just return the already-loaded module. That is to say: import sys dir(__import__('sys')) is not going to take (noticeably) longer than: mod = __import__('sys') dir(mod) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From dirgesh at gmail.com Tue Jun 7 16:34:01 2005 From: dirgesh at gmail.com (GujuBoy) Date: 7 Jun 2005 13:34:01 -0700 Subject: import error using BOOST in linux Message-ID: <1118176441.221162.298660@o13g2000cwo.googlegroups.com> i am using BOOST in linux with python and i can compile my CPP file just fine to make a .so but everytime i do a import i get this error >>> import dirgesh Traceback (most recent call last): File "", line 1, in ? ImportError: libboost_python.so.1.32.0: cannot open shared object file: No such file or directory >>> i also tried putting the libboost_python.so.1.32.0 file in the /usr/lib/python2.3 dir. please help From chinook.nr at tds.net Wed Jun 29 10:39:31 2005 From: chinook.nr at tds.net (Chinook) Date: Wed, 29 Jun 2005 10:39:31 -0400 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119956464.362328.290370@o13g2000cwo.googlegroups.com> <87ekala2xf.fsf@titan.staselog.com> <42C28FFF.7010303@anvilcom.com> Message-ID: <0001HW.BEE82AE300082A2AF0284550@news.gmane.org> On Wed, 29 Jun 2005 08:11:43 -0400, phil wrote (in article <42C28FFF.7010303 at anvilcom.com>): > > Comes down to preference. Isn't it absolutely amazing how many > choices we have. Remember the 70's - Cobol, ASM, C, Basic.CICS(shudder) > And please, no eulogies (especially for CICS) - being reminded of them is bad for my heart :~) I once did a engineering modeling system in IBM 1130 assembler that ran with overlays in 32K memory, because FORTRAN was too hoggish. Input was the console keyboard and output was a CalComp plotter. > > Python reminds me more of Linux. Incredible no of packages, > kinda disjointed, docs pretty bad, not integrated. > But amazing stuff if you have the stomach for it. > (seen pygame?) > Maybe Python will get a daddy someday. > Seriously, having been involved in several (so called) high-level productivity languages over the years on both IBM and HP (3000 series), I am really enamored with Python (not to mention being on the user end :~). However, as you say ("needs a daddy") it is still for the most part in hackerdom evolution, and will not be a "mainstream" development platform until a Sun/IBM/whatever takes it under-wing with that intention in an open environment (the "suits" have to be convinced they can gain big time otherwise). Can that happen in the Open-Source arena - I'm not convinced it can because such is more akin to a staging ground at present. And what would be really cool is that if the same thing happened with Linux - it evolved to an elegant OS X like GUI without losing the intuitive underbelly. Just any "daddy" won't do though. The least beneficial would be the path of DOS (sorry, I'm not a MS fan :~)). A major problem is that business thinking (i.e. the "suits") is overly monopolistic to the point of counter-productivity. Rather than an evolving open mainstream development platform (i.e. technical productivity competition) and commercial products emanating from such, the "suits" are focused on milking anything they can get their hands on with only short-term bonuses in mind. I guess it all gets down to human nature (or as Pogo said ...). Enough, before I really get carried away. Lee C From jchiang at slac.stanford.edu Sun Jun 19 00:06:18 2005 From: jchiang at slac.stanford.edu (jchiang at slac.stanford.edu) Date: 18 Jun 2005 21:06:18 -0700 Subject: Extensions on Linux: import without underscore? References: Message-ID: <1119153978.571251.252510@f14g2000cwb.googlegroups.com> Try SharedLibrary("bright.so", SHLIBPREFIX="", ...) The prefix option is documented here http://www.scons.org/doc/HTML/scons-man.html From hancock at anansispaceworks.com Thu Jun 9 11:15:38 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 9 Jun 2005 10:15:38 -0500 Subject: No subject In-Reply-To: <1118040170.42a3f06aad73e@mailbox.textualanalytics.com> References: <1117875121.42a16bb150ac2@mailbox.textualanalytics.com> <1118040170.42a3f06aad73e@mailbox.textualanalytics.com> Message-ID: <200506091015.38746.hancock@anansispaceworks.com> On Monday 06 June 2005 01:42 am, Jatinder Singh wrote: > B and C are subdirectories of Parent Directory A. > I am executing a file in Directory C which is importing a file f' in directory > B. > Now while running python file m getting an error of can't open f'. If I copy f' > in > current directory B. then It is running. I want to get rid of that and run the > programme without copying the other f' files( even .txt also) in the current > directory. and I have so many files in directory B,otherwise I wou;ld have > wppended the path while opening the file. I don't want to do it for each file > and also If i need to change directory structure then also I should change one > path and able to run the Programme. So you want to use a relative path then? Have you tried this: filepath = os.path.join(os.getcwd(), '..', 'C', filename) f = open(filepath, 'r') etc.? It's really quite straightforward to walk up and down directory trees, please take a closer look at the documentation for os and os.path modules (see http://www.python.org to find documentation for your version). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steven.bethard at gmail.com Wed Jun 1 11:01:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Jun 2005 09:01:48 -0600 Subject: xml processing In-Reply-To: References: Message-ID: Jeff Elkins wrote: > I've like to use python to maintain a small addressbook which lives on a Sharp > Zaurus. This list will never grow beyond 200 or so entries. I've installed > pyxml. If you're not committed to pyxml, you might consider using ElementTree: http://effbot.org/zone/element-index.htm I find it *way* easier to work with. > > Speaking generally, given a wxpython app to do data entry, > I'm planning to: > > 1. parse the addressbook file, loading its data into an array. > 2. Perform any edit operations within the array. > 3. Write out a finished xml file from the array when I'm done. > > Is this reasonable? Better, smarter ways to accomplish this? Seems pretty reasonable. Another option might be to parse the addressbook file into an XML object and then modify the XML object itself. E.g.: tree = ElementTree(file="...") elem = tree.getroot() for node in elem.findall("..."): node.text = "..." STeVe From grahamd at dscpl.com.au Fri Jun 3 21:43:23 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 3 Jun 2005 18:43:23 -0700 Subject: mod_python config problem References: <42A0AC81.2030901@galileo.edu> Message-ID: <1117849403.252779.254090@g44g2000cwa.googlegroups.com> David Stanek wrote: > On Fri, Jun 03, 2005 at 01:16:17PM -0600, Manuel Pellecer wrote: > > i want to use mod_python with Apache2 and i made a .htaccess in the > > subdirectory where i have all my scripts: > > > > The .htacces goes like this: > > > > AddHandler mod_python .py > > PythonHandler mptest > > PythonDebug On > > Try adding the following line to your .htaccess file: > PythonPath "sys.path + ['/your/path']" > Where '/your/path' is the path in which mptest.py resides. Explicitly overriding PythonPath when using mod_python is not recommended as it causes more problems than good usually. It certainly should not be required to get this working when everything is setup correctly. Suggested that the original poster read: http://www.dscpl.com.au/projects/vampire/articles/modpython-001.html That article is specifically written to help out people with their first mptest example, listing what can go wrong and how to go about working it out. Suggest anything after that is better asked on mod_python mailing list. Graham From P.Schnizer at nospam.gsi.de Thu Jun 2 05:31:56 2005 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 02 Jun 2005 11:31:56 +0200 Subject: wxpython or PyQT to make a simulink clone ? References: <1117699017.376196.37930@f14g2000cwb.googlegroups.com> <873bs1xgot.fsf@smtp.gsi.de> Message-ID: <87wtpdw1df.fsf@smtp.gsi.de> Pierre Schnizer writes: There was an old discussion on comp.lang.python: http://groups.google.de/group/comp.lang.python/browse_thread/thread/9ce44f40011016ec/a2e52b824de9bfb1?q=simulink&rnum=6&hl=de#a2e52b824de9bfb1 I have seen the later code of Eric Lechak looked very interesting, but the link above is not active any more. Unfortunately I have no copy any longer ... Pierre From ajikoe at gmail.com Tue Jun 14 04:39:51 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 14 Jun 2005 01:39:51 -0700 Subject: gobal var inside class without notice??? Message-ID: <1118738391.216206.142280@g47g2000cwa.googlegroups.com> I have code like this: class A: def __init__(self,j): self.j = j def something(self): print self.j print i # PROBLEM is here there is no var i in class A but it works ??? if __name__ == '__main__': i = 10 a = A(5) a.something() I don't define global i but it will takes var i from outside of class A. Can somebody explain this ??? pujo From renato.ramonda at gmail.com Fri Jun 24 15:52:29 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Fri, 24 Jun 2005 21:52:29 +0200 Subject: help! In-Reply-To: References: <03FB1C8A0749414494FE4726AADD7D4302A8C5B4@vkomexch1.zh.corp> <20050624121401.GA7890@heaven.kostyrka.org> Message-ID: <2wZue.21449$TR5.19296@news.edisontel.com> Johannes Findeisen ha scritto: > some filesystems do support that. From the ext2 specification > ( http://e2fsprogs.sourceforge.net/ext2intro.html ): > > "As a response to these problems, two new filesytems were released in > Alpha version in January 1993: the Xia filesystem and the Second > Extended File System. The Xia filesystem was heavily based on the Minix > filesystem kernel code and only added a few improvements over this > filesystem. Basically, it provided long file names, support for bigger > partitions and support for the three timestamps." That is, if it is mounted do do so. Just pass a "noatime" parameter to the mount command (or fstab line) and the atime (access time) will not be written. Common when using very slow storage devices, or devices with somewhat limited read/write cycles (like old compactflash memories). -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From skip at pobox.com Sat Jun 25 15:56:41 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 25 Jun 2005 14:56:41 -0500 Subject: Excellent Site for Developers In-Reply-To: References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: <17085.46841.360432.772178@montanaro.dyndns.org> Philippe> Not being from anglo-saxon heritage, I keep wondering why Philippe> spammers always (or very often) get called 'trolls' ? Fishing from a boat that is moving slowly is called "trolling". You're slowly dragging bait or a lure through the water to entice a fish to bite your hook. Similarly, when someone posts a provocative message to a mailing list or Usenet newsgroup (or other discussion forum, I suppose) they are often trying to get someone else to "take their bait". See also: http://www.answers.com/troll Skip From passion_to_be_free at hotmail.com Mon Jun 20 09:31:38 2005 From: passion_to_be_free at hotmail.com (passion_to_be_free at hotmail.com) Date: 20 Jun 2005 06:31:38 -0700 Subject: import via pathname Message-ID: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> Okay, so in my li'l python script I'm importing a few 3rd party modules that I have installed on my comp. I need to distribute this script to several other people, but I won't have access to install the modules on their comp's. I'm thinking I'll include these modules with my script and deliver them as a bundle. When I write my script, is there a way to declare the import statements and specify a relative path to where the modules are located? I know this is wrong syntax, but I think it demonstrates what I'm trying to do: import myModule path = /modules/myModule import myModule2 path = /modules/myModule2 Something like that. Is it possible? -Thx From sjmachin at lexicon.net Wed Jun 1 19:28:23 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 09:28:23 +1000 Subject: bug with isinstance() ? In-Reply-To: <1117664364.603412.73230@g49g2000cwa.googlegroups.com> References: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> <1117664364.603412.73230@g49g2000cwa.googlegroups.com> Message-ID: <429e4497@news.eftel.com> Mac wrote: [snip] > I guess the problem is I'm thinking of "classes" > as these abstract concepts, sort of like Platonian "forms", whereas I > should be thinking of classes as "class objects", object instances, > each coming from some module's namespace... is this sort of the idea? > Someone help me wrap my head around this, please. :) > Yes, you're getting it; Python is a dynamic language. Even classes can be created on the fly. I have a kit for reading/writing boring old legacy mainframe-style files containg multiple record types with fixed-length fields. The record definitions are stored as data, not as code. A skeleton class's source is actually *local* to the class-making function. This means the class statement is executed each time the function is called. The function takes the current class instance like a shopping trolley and fills it up with more methods and attributes, before parking it in a dictionary keyed on the record name. Taxpayer = file_dict['TXPYR'] taxpayer = Taxpayer() taxpayer.name = 'John Q Doe' taxpayer.date_of_birth = datetime.date(1970, 12, 31) taxpayer.reportable_income = 1234.56 outfile.write(taxpayer.as_fixed_string()) Cheers, John From tdelaney at avaya.com Mon Jun 13 18:36:02 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 14 Jun 2005 08:36:02 +1000 Subject: Controlling a generator the pythonic way Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025205A5@au3010avexu1.global.avaya.com> Steve Holden wrote: > Sigh indeed. But if you allow next() calls to take arguments you are > effectively arguing for the introduction of full coroutines into the > language, and I suspect there would be pretty limited support for > that. You mean `PEP 342`_ which I posted earlier and is considered pretty non-controversial? I think I may suggest that the name of the PEP be changed to "Coroutines using advanced iterators". .. _`PEP 342`: http://www.python.org/peps/pep-0342.html Tim Delaney From peter at engcorp.com Sat Jun 18 12:24:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:24:50 -0400 Subject: case/switch statement? In-Reply-To: References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Message-ID: D H wrote: > Peter Hansen wrote: [some stuff Doug didn't like] > I don't think you could have misread my simple suggestion to you any > more completely than you did. Sorry, I'll try harder next time. -Peter From idontneednostinkinid at yahoo.com Wed Jun 1 20:35:47 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 17:35:47 -0700 Subject: bug with isinstance() ? References: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> <1117664364.603412.73230@g49g2000cwa.googlegroups.com> <429e4497@news.eftel.com> Message-ID: <1117672547.329530.121620@f14g2000cwb.googlegroups.com> OK, it's alllll coming together now, thx. Grrr... all this misconception, again, due to the evil, evil, EVIL influence of having worked a lot before with an inferior language (C/C++)... :) From steve at REMOVETHIScyber.com.au Sat Jun 25 22:18:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 12:18:29 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1119730516.936848.195640@f14g2000cwb.googlegroups.com> Message-ID: On Sat, 25 Jun 2005 23:19:48 +0200, Peter Otten wrote: > Python is more about readability than raw speed, and I prefer a for-loop > over reduce() in that respect, too. Fascinating. I prefer reduce for readability. "Reduce this list to one value, using this known behaviour" seems to work for me better than: "Oh look, here is a new name being defined. What is it for I wonder? Now it is being used in a for loop. Ah, the loop appears to be implementing the well-known reduce behaviour from Lisp. I bet that means that the name is a temporary placeholder just being used to hold the intermediate results of from the for loop. Yes, that seems to be the case." Funny how people differ in what they find readable :-) -- Steven. From steve at REMOVEMEcyber.com.au Thu Jun 2 23:59:25 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 03 Jun 2005 13:59:25 +1000 Subject: (OT) lincense protection generator References: Message-ID: <429FD59D.3020201@REMOVEMEcyber.com.au> flupke wrote: > Jarek Zgoda wrote: > >> flupke napisa?(a): >> >>> I'm thinking of a function that will generate such a code and put it >>> in a file. Then when the program starts it checks this file and >>> checks the code in there with a code that it generates at that time >>> again based for instance on the current directory and other >>> components unique to that computer. It could be a long string (but >>> what info?) and then take a hash from it and store the hash value. >> >> >> >> Better, generate sha1 sum of general machine configuration (i.e. what >> "set" command returns) and store it on random internet node. You can >> be sure nobody would get it. >> >> Anyway, it's bad idea. Restrict program usage in license) or any other >> contract), but don't do such a mess to people who pay your bills. >> > > Well as i said it's more to see when they tampered with the config or > the program. It's not a commercial application but it's for inhouse use > in the hospital where i work. These people are, to put it mildly, not > the most computer savant people around. > It could be handy to avoid me searching for a solution to a problem that > arises because of messing with the setup rather than a bug in the code. Log the program's errors. If a config file isn't found, it will log that fact. If they edit a config file and change (say) num_widgets = 5 to num_widgets = -88888, then when the program raises an exception it will log something like ValueError("Num widgets is less than zero"). This will also help catch your errors as well as their errors. Alternatively, put a lot of error checking in one module which you import and run at startup. Something like: try: import mymodule import databasemodule except: print "PEBCAK error, call tech support" sys.exit(99) and you will know they have moved things around. -- Steven. From listserver at tdw.net Thu Jun 9 12:46:14 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 9 Jun 2005 17:46:14 +0100 Subject: help with sending mail in Program References: Message-ID: <009301c56d12$c00ca420$ccbefea9@twilliams> ----- Original Message ----- From: "Ivan Shevanski" To: Cc: Sent: Thursday, June 09, 2005 5:33 PM Subject: Re: help with sending mail in Program > > > > >#!/usr/local/bin/python > > > >''' Send mail to me ''' > > > >from smtplib import SMTP > > > >def sendToMe(subject, body): > > me = '"Ivan Shevanski" ' > > send(me, me, subject, body) > > > > > >def send(frm, to, subject, body): > > s = SMTP() > >#///On or off for test\\\ #s.set_debuglevel(1) > > s.connect('mail.hotmail.com',) > > s.ehlo('69.137.27.32') # IP address of my computer, I don't > > > >remember why I needed this > > msg = '''From: %s > >Subject: %s > >To: %s > > > >%s > >''' % (frm, subject, to, body) > > > > s.sendmail(frm, to, msg) > > > > s.sendmail(frm, [to], msg) > > > > s.quit() > > > > > >if __name__ == '__main__': > > sendToMe('test', 'test') > > > > > >It says it sends it but I get nothing in my inbox or anywhere! This is > >really frustrating me. > > > >_________________________________________________________________ > > > >[tim williams]> No it definitely works, but Hotmail will blackhole your > >constructed email as it is obviously fake. It has no headers, dates, > >msg-id etc. > > > >[tim williams]> View the source of a real email in your mail client, > >then > >cut & paste the whole thing into your message variable like this > > > > msg = ''' ''' > > > >[tim williams]> you should remove the " % (frm, subject, to, body) " at > >the end of the msg string > > > >[tim williams]> for correctness, you also need an " s.rset() " in > >between > >each " s.sendmail " (but the script does work in its current form) > > > >[tim williams]> HTH :) > > > > > Im good with everything except viewing the source. . .Do you mean the html > source? Because I use hotmail, and not outlook or thunderbird or something > like that. Sorry, i'm a noob. Supplied a text version of an email to Ivan off-list :) From cf_1957 at hotmail.com Sun Jun 5 09:41:35 2005 From: cf_1957 at hotmail.com (chris) Date: Sun, 05 Jun 2005 13:41:35 GMT Subject: XML help Message-ID: I'm 4 months new to python and 4 hours new to XML. I've been trying to understand and use the DOM tree walk sample shown at this site: http://www.rexx.com/~dkuhlman/pyxmlfaq.html to walk through an xml file from which I need to extract data for subsequent plotting. I've repeated the functions from the site that I'm using here: import sys, string from xml.dom import minidom, Node def walkTree(node): if node.nodeType == Node.ELEMENT_NODE: yield node for child in node.childNodes: for n1 in walkTree(child): yield n1 def test(inFileName): outFile = sys.stdout doc = minidom.parse(inFileName) rootNode = doc.documentElement level = 0 for node in walkTree(rootNode): my_processing(node, outFile) A piece of the XML file I want to process is here:

Simulation Results XML Writer 1.00
ELDT(Element data) 1 2 231 32 1.5098e+000 1.4991e+000 1.4744e+000 ...... .... As can be seen data is represented by blocks within which a datapoint exists for finite element IDs. Number of entries in each block vary and Element IDs are not necessarily contiguous. I've managed to test for specific elements and extract values. I want to place the reults in arrays with array index equal to element ID. So as I walk the tree I temporarily store IDs and DeptValues in lists. I'm ok so far. I then intend to create an array of size determined by the maximum value of ID. So in the sample above the array size will be 8 even though only three entries exist. At this point I'm stuck because I want to do this latter array creation and processing when I "see" the /Block end of block tag. However I can't figure out how to do that. Obviously I'm not understanding something about XML DOM trees and Elements because when I try to print all elements I never see an end tag for any. I'm obviously approaching this from a readline and process point of view which is probably half the problem. So how can I initiate array processing at the end of each block prior to reaching the next block. Of course I'm open to simpler ways too ;) tia for any advice. From tvansteenburgh at gmail.com Wed Jun 29 08:11:18 2005 From: tvansteenburgh at gmail.com (Tim) Date: 29 Jun 2005 05:11:18 -0700 Subject: Creating Python wrapper for DLL In-Reply-To: <1119992447.220001.258210@g49g2000cwa.googlegroups.com> References: <1119990428.163115.152440@g49g2000cwa.googlegroups.com> <1119992447.220001.258210@g49g2000cwa.googlegroups.com> Message-ID: <1120047078.143965.41540@o13g2000cwo.googlegroups.com> Thanks guys, I'll take a look! From bvande at po-box.mcgill.ca Wed Jun 29 03:59:06 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 29 Jun 2005 03:59:06 -0400 Subject: Newbie: Explain My Problem In-Reply-To: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> References: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> Message-ID: <42C254CA.7030005@po-box.mcgill.ca> ChuckDubya at gmail.com said unto the world upon 29/06/2005 03:11: > Code: > > #The Guess My Number Game > > import random > num = "" > guess = "" > counter = 7 > num = random.randrange(1, 100) > print "I'm thinking of a whole number from 1 to 100." > print "You have ", counter, " chances left to guess the number." > print > guess = int(raw_input("Your guess is: ")) > while counter != 0: > if guess == num: > print "You guessed the number, ", num, " in ", counter-6, " > guesses!" > elif guess > num: > counter = counter - 1 > print > print "The number is less than your guess." > print "You have ", counter, " chances left to guess the > number." > guess = int(raw_input("Your guess is: ")) > else: > counter = counter - 1 > print > print "The number is greater than your guess." > print "You have", counter, " chances left to guess the number." > guess = (raw_input("Your guess is ")) > if counter == 0: > print "You idiot, my number was", num,"!" > print "YOU LOSE!" > raw_input("Hit the enter key to exit.") > > > Two things wrong happen: > - Dialogue switches from saying "number is greater" to "number is > less", regardless of guess > - Lets user guess when user has no more guesses left in "counter" > variable. > > Please explain to me what's wrong with my program. > Well, you have some logic problems, and they are harder to see because of some structural problems. Notice that in your elif and else branches you repeat logic? Or rather, almost repeat logic :-) (You left of the conversion to int on one of the calls to raw_input.) You also had the problem that if the user was right, they'd be told so quite a few times ;-) And, you weren't keeping track of the guesses properly. Compare yours with the code below. I've moved things around, eliminated the duplication (and near duplication), removed the pointless initial assignments to num and guess, closed the infinite loop, and built the strings differently. import random counter = 7 num = random.randrange(1, 100) print "I'm thinking of a whole number from 1 to 100." while counter != 0: print "You have %s chances left to guess the number." %counter guess = int(raw_input("Your guess is: ")) counter = counter - 1 if guess == num: print "You guessed the number, %s in %s guesses!" %(num, 7-counter) break # else it will print success msg forever elif guess > num: print "\nThe number is less than your guess." else: print "\nThe number is greater than your guess." if counter == 0: print "You idiot, my number was %s!" %num print "YOU LOSE!" raw_input("Hit the enter key to exit.") This still assumes a co-operative user. (Try entering "one" and see what happens.) "1 chances" looks goofy, too. You might want to think about fixing that. Best, Brian vdB From wookiz at hotmail.com Thu Jun 9 23:03:16 2005 From: wookiz at hotmail.com (wooks) Date: 9 Jun 2005 20:03:16 -0700 Subject: Python Developers Handbook In-Reply-To: <7xk6l33r2j.fsf@ruckus.brouhaha.com> References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> Message-ID: <1118372596.003161.290690@g49g2000cwa.googlegroups.com> I thought that posting a link that contained the word ebay and a subject title of Python Developers Handbook conveyed all the relevant information and didn't want to patronise the NG. I have had 110 hits on the item but seem to have upset 3 people. I am sorry. I don't have any other Python books to sell so it won't happen again. From flyingfred0 at gmail.com Thu Jun 9 23:05:12 2005 From: flyingfred0 at gmail.com (flyingfred0) Date: Fri, 10 Jun 2005 03:05:12 GMT Subject: Saving/retrieving user preferences In-Reply-To: <42a78012@dnews.tpgi.com.au> References: <42a78012@dnews.tpgi.com.au> Message-ID: If you're creating your GUI with wxPython, you might be able to use wx.Config and related classes. http://wxpython.org/docs/api/wx.ConfigBase-class.html Brian Wallis wrote: > This may be a FAQ,but I cannot find it. > > I want to save user preferences, window sizes, recently opened file names, > etc for a python application and I am looking for a package that does this > in a way that is portable across unix/linux and windows (and mac would be > nice as well). > > Is there a 'standard' package for doing this in python? > > thanks, From jzgoda at gazeta.usun.pl Sun Jun 12 14:58:37 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sun, 12 Jun 2005 20:58:37 +0200 Subject: ElementTree Namespace Prefixes In-Reply-To: References: Message-ID: Chris Spencer napisa?(a): > Given xml with no namespaces, Elementtree works perfectly. However, if > you give the root tag an xmlns attribute, Elementtree relabels all child > nodes with it's own prefix, completely defeating the purpose of the > default namespace. In my opinion, this is unacceptable behavior. There is no functional difference between default namespace and "normal" namespace. Replacing "default" with "normal" has no effect for document processing (namespace doesn't change, only prefix), although it looks differently for humans. Anyway, XML is for machines, not for humans. > If an XML parser reads in and then writes out a document without having > altered it, then the new document should be the same as the original. > With Elementtree this isn't so. Lundh apparently believes he knows > better than you and I on how our namespaces should be represented. No, this is perfectly valid behaviour. Go, see spec. > It's a shame the default ns behavior in Elementtree is in such a poort > staten. I'm surprised no one's forked Elementtree solely to fix this issue. There is at least one ElementTree API implementation that retains prefixes, lxml.ETree. Go google for it. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From rbt at athop1.ath.vt.edu Thu Jun 16 09:15:21 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 16 Jun 2005 09:15:21 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <42af1b28$0$10131$626a14ce@news.free.fr> References: <42af1b28$0$10131$626a14ce@news.free.fr> Message-ID: <1118927721.18452.4.camel@athop1.ath.vt.edu> On Tue, 2005-06-14 at 19:51 +0200, Gilles Lenfant wrote: > rbt a ?crit : > > Here's the scenario: > > > > You have many hundred gigabytes of data... possible even a terabyte or > > two. Within this data, you have private, sensitive information (US > > social security numbers) about your company's clients. Your company has > > generated its own unique ID numbers to replace the social security numbers. > > > > Now, management would like the IT guys to go thru the old data and > > replace as many SSNs with the new ID numbers as possible. You have a tab > > delimited txt file that maps the SSNs to the new ID numbers. There are > > 500,000 of these number pairs. What is the most efficient way to > > approach this? I have done small-scale find and replace programs before, > > but the scale of this is larger than what I'm accustomed to. > > > > Any suggestions on how to approach this are much appreciated. > > Are this huge amount of data to rearch/replace stored in an RDBMS or in > flat file(s) with markup (XML, CSV, ...) ? > > -- > Gilles I apologize that it has taken me so long to respond. I had a hdd crash which I am in the process of recovering from. If emails to rbt at athop1.ath.vt.edu bounced, that is the reason why. The data is in files. Mostly Word documents and excel spreadsheets. The SSN map I have is a plain text file that has a format like this: ssn-xx-xxxx new-id-xxxx ssn-xx-xxxx new-id-xxxx etc. There are a bit more than 500K of these pairs. Thank you, rbt From no at spam.com Sun Jun 12 15:26:54 2005 From: no at spam.com (Rob) Date: Sun, 12 Jun 2005 19:26:54 GMT Subject: searching for IDE References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: <200re.27253$J12.6650@newssvr14.news.prodigy.com> Try ActiveState Komodo. It costs $30 for a personal license, and is well worth it. If you like visual studio you will like it. Like many other people, I have looked far and wide for a Python IDE and this is what I've found. The free solutions don't cut it, at least without spending many many hours of work, more than $30 worth. R "alexrait1" wrote in message news:1118602945.370653.226760 at f14g2000cwb.googlegroups.com... >I need an IDE for python that has the ability to show the filds of a > class when I write "." > Just the way it works in eclipse/JBuilder with java or visual studio > with c++ > For now I treid eric3 and IDLE they don't do this... > From fredrik at pythonware.com Wed Jun 22 03:54:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Jun 2005 09:54:44 +0200 Subject: Loop until condition is true References: Message-ID: Remi Villatel wrote: > >>while True: > >> some(code) > >> if final_condition is True: > >> break > >> # > >># > > > checking if a logical expression is true by comparing it to True is bad > > style, and comparing values using "is" is also bad style. > > Erm... You totally missed the point. I wrote it this way because, first, > it's perfectly valid Python code and, second and most important, it's also a > valid english sentence. I suggest looking up "is" in the Python manual instead of looking it up in a dictionary. (hint: it doesn't do what you think it does, and code using your "perfectly valid" pattern doesn't always work.) > [CENSORED] I keep for myself how stupid I found your post. so let's see if everyone who understands how embarrassingly stupid your post is will keep that to themselves... From timr at probo.com Sun Jun 5 02:30:30 2005 From: timr at probo.com (Tim Roberts) Date: Sat, 04 Jun 2005 23:30:30 -0700 Subject: Help with pythonpath References: Message-ID: <8s65a1lbfrns7g6ecrqghtvkfh1lps30vg@4ax.com> Observer wrote: > >Hi, im a newbie both to python and this list. >I hope someone can help me whith this: > >I have a directory structure like this: >. >|-- src >| `-- pkg >| |-- __init__.py >| |-- main.py >| `-- spkg1 >| |-- __init__.py >| `-- config.py >`-- src2 > `-- pkg > |-- __init__.py > `-- spkg2 > |-- __init__.py > `-- config2.py > >and main.py is a python script that contains this imports: > >from pkg.spkg1 import config >from pkg.spkg2 import config2 > >executed in linux whith this: > >env PYTHONPATH=src:src2 src/pkg/main.py >Traceback (most recent call last): > File "src/pkg/main.py", line 4, in ? > from pkg.spkg2 import config2 >ImportError: No module named spkg2 > >changing the order of the python path only inverts the problem, is there >any way to solve this without changing the directory structure? Nope. When Python goes to look for a package called "pkg", it starts at the beginning of PYTHONPATH and stops as soon as it finds one. You either need to use different names for the two packages (pkg1, pkg2), or use a symbolic link to link spkg2 into the src directory. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From godfoca at gmail.com Mon Jun 27 14:22:35 2005 From: godfoca at gmail.com (GodFoca) Date: 27 Jun 2005 11:22:35 -0700 Subject: Favorite non-python language trick? In-Reply-To: <1119811097.681889.198790@f14g2000cwb.googlegroups.com> References: <1119810243.032890.95410@g43g2000cwa.googlegroups.com> <1119811097.681889.198790@f14g2000cwb.googlegroups.com> Message-ID: <1119896555.477156.156420@o13g2000cwo.googlegroups.com> > if a.value == True: > return a > if not database.connect == error: > database.query(q) Yeah, yeah, I know that :-) What I mean is that most of the time I find the code more "readable" (I know that more readable code ain't better code, but it helps when you work with other people...). > "unless" seems to become "while not", as opposed to "if not". Should be > more consistent. My mistake :-S The comment in the code was erroneous, I shouldn't write messages to the list while asleep ^_^ 'unless' works as 'if not', not as 'while not'. Sorry for that :-) Anyway, it does improve readability. I know that it doesn't necessarily makes code better, but it's a nice "trick" that I like :-) Other nice thing about ruby is declaring regexps as /regexp/ rather than having to re.compile("regexp"), and having a built-in operator to match against them (of course, as everything in ruby, overloadable in each class :-)) -NIcolas From ajikoe at gmail.com Wed Jun 8 09:24:05 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 8 Jun 2005 06:24:05 -0700 Subject: \r\n or \n notepad editor end line ??? Message-ID: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> Hello, I use windows notepad editor to write text. For example I write (in d:\myfile.txt): Helo World If I open it with python: FName = open(d:\myfile.txt,'r') h = FName.readlines() print h I get h : ['Helo\n', 'World'] I thought notepad use \r\n to to end the line. What's wrong with it? pujo From correiajREMOVECAPS at hotmail.com Wed Jun 1 14:46:26 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Wed, 01 Jun 2005 18:46:26 GMT Subject: Pressing A Webpage Button References: Message-ID: <6onne.27139$9A2.4091@edtnps89> "Elliot Temple" wrote in message news:mailman.335.1117645705.18027.python-list at python.org... > How do I make Python press a button on a webpage? I looked at > urllib, but I only see how to open a URL with that. I searched > google but no luck. > > For example, google has a button how would i make a script to press that button? > > Just for fun, is there any way to do the equivalent of typing into a > text field like the google search field before hitting the button? > (I don't actually need to do this.) You don't say which OS... if you're running IE on Windows you can use COM as follows... from win32com.client import Dispatch from time import sleep ie = Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.Navigate("http://www.google.com") while ie.ReadyState != 4: # Wait for browser to finish loading. sleep(1) doc = ie.Document doc.f.q.value = "qwerty" # form name is 'f'; search field name is 'q' doc.f.btnG.click() # click on button 'btnG' From michele.simionato at gmail.com Sat Jun 18 03:26:04 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 18 Jun 2005 00:26:04 -0700 Subject: What is different with Python ? In-Reply-To: References: <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> <3hg08rFh2tr3U1@individual.net> <1119015358.155954.92430@g47g2000cwa.googlegroups.com> <1119067837.776544.198870@g49g2000cwa.googlegroups.com> Message-ID: <1119079564.279641.150810@z14g2000cwz.googlegroups.com> Your position reminds me of this: http://www.pbm.com/~lindahl/real.programmers.html Michele Simionato From steven.bethard at gmail.com Mon Jun 20 11:38:34 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Jun 2005 09:38:34 -0600 Subject: Couple functions I need, assuming they exist? In-Reply-To: References: Message-ID: <8cadnbiar_RkfyvfRVn-3A@comcast.com> Charles Krug wrote: > myWords = split(aString, aChar) > > is depreciated but > > myWords = aString.split(aChgar) > > is not? Yes, that's basically correct. What's deprecated are the functions in the string module. So string.split(a_str, b_str) is deprecated in favor of a_str.split(b_str) > The target of the problems (my daughter) would prefer that the thousands > be delimited. Is there a string function that does this? I assume you mean translating something like '1000000' to '1,000,000'? I don't know of an existing function that does this, but here's a relatively simple implementation: py> import itertools as it py> def add_commas(s): ... rev_chars = it.chain(s[::-1], it.repeat('', 2)) ... return ','.join(''.join(three_digits) ... for three_digits ... in it.izip(*[rev_chars]*3))[::-1] ... py> add_commas('10') '10' py> add_commas('100') '100' py> add_commas('1000') '1,000' py> add_commas('1000000000') '1,000,000,000' In case you haven't seen it before, it.izip(*[itr]*N)) iterates over the 'itr' iterator in chunks of size N, discarding the last chunk if it is less than size N. To avoid losing any digits, I initially pad the sequence with two empty strings, guaranteeing that only empty strings are discarded. So basically, the function iterates over the string in reverse order, 3 characters at a time, and joins these chunks together with commas. HTH, STeVe From me at privacy.net Tue Jun 14 12:20:23 2005 From: me at privacy.net (Dan Sommers) Date: 14 Jun 2005 12:20:23 -0400 Subject: sudo open() ? (python newbee question) References: <42aea8cd$0$9912$636a15ce@news.free.fr> Message-ID: On Tue, 14 Jun 2005 16:18:19 +0300, Christos "TZOTZIOY" Georgiou wrote: > I believe that the suid bit on scripts (either *sh or python) is > completely ignored on most *nix systems. Most *modern* systems, yes. ;-) I must be getting old. :-( Regards, Dan -- Dan Sommers From phillip.watts at anvilcom.com Wed Jun 29 11:54:34 2005 From: phillip.watts at anvilcom.com (phil) Date: Wed, 29 Jun 2005 10:54:34 -0500 Subject: Boss wants me to program References: Message-ID: <42C2C43A.5080900@anvilcom.com> > About teaching in the exact sciences: I think we need a more hands-on > applied approach, to some extent this holds for the entire school > system. YES! As a geometry(& trig) teacher, I am going to have them build a shed, a kite, a sundial. I would love some doable ideas for hands on which would teach more principles without being major construction projects. From peter at engcorp.com Thu Jun 9 10:20:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 10:20:57 -0400 Subject: Another solution to How do I know when a thread quits? In-Reply-To: <1118325791.364271.96590@g14g2000cwa.googlegroups.com> References: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> <0umdnaKeMsKDOTjfRVn-gA@powergate.ca> <1118325791.364271.96590@g14g2000cwa.googlegroups.com> Message-ID: Prashanth Ellina wrote: > Thanks for the code sample. I will try it out. I guess there is no > reliable way to get away with just the "threads" module. As "threading" is built on top of "thread", that statement seems wrong, but the real question you should ask yourself is why you want to use the "thread" module at all when "threading" already exists. Also, I have to say I'm confused by Giovanni's "solution", as it seems to do nothing that isn't already provided by threading.Thread's isAlive() and join() methods (which I already mentioned in my previous posting). -Peter From pmaupin at gmail.com Sun Jun 12 23:04:45 2005 From: pmaupin at gmail.com (pmaupin at gmail.com) Date: 12 Jun 2005 20:04:45 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: <1118256283.485202.19780@o13g2000cwo.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: <1118631885.148536.169470@f14g2000cwb.googlegroups.com> If a behavior change is possible at all, I think a more reasonable behavior would be: if any rich comparison methods are defined, always use rich comparisons (and throw an exception if the required rich comparison method is not available). This would at least have the benefit of letting users know what code it had broken when they try to run it :) Regards, Pat From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Jun 4 05:16:15 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 04 Jun 2005 09:16:15 +0000 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: <42A1715F.5060101@jessikat.fsnet.co.uk> Ilpo Nyyss?nen wrote: ....... > > with locking(mutex), opening(readfile) as input: > ... .... with EXPR as x: BLOCK EXPR can be a tuple so the above would be ambiguous. -- Robin Becker From philippe at philippecmartin.com Sat Jun 25 16:26:57 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 20:26:57 GMT Subject: Big problem fetching members from dynamically loaded module References: Message-ID: I meant live, not leave ! (this is getting pretty bad) Philippe C. Martin wrote: > OK Peter, first of all thanks. > > You seem to be German and although I leave in the states, I'm French and > your english is clearly far more advanced than mine: I have yet to > understand a few of your comments ;-) > >> Care to provide the traceback? > > Traceback (most recent call last): > File "SC_Shell.py", line 1095, in ? > l_d = SC_Shell() > File "SC_Shell.py", line 326, in __init__ > self.__Make_Menu_Area() > File "SC_Shell.py", line 828, in __Make_Menu_Area > l = inspect.getmembers(eval(c)) > File "", line 0, in ? > NameError: name 'BC' is not defined > >> What happened in lines 1 through 22? My guess would be > just import inspect > > > and after that .... QUID ? > > Thanks and regards, > > Philippe > > > > > > Peter Otten wrote: > >> Philippe C. Martin wrote: >> >>> l?=?inspect.getmembers(eval('BC'))?#THIS?CRASHES?-?the?class?exists >> >> Care to provide the traceback? >> >>> In [23]:from SC.CARDS.BC import * >>> >>> In [24]:l = inspect.getmembers(eval('BC')) >> >> What happened in lines 1 through 22? My guess would be >> >> In [13]:from SC.CARDS import * >> >> Be that as is may, eval("BC") can be simplified to BC, >> >> from module import * >> >> is the last roadhouse en route to chaos and an unqualified >> >> try ... except >> >> shows you are willing to drive with defunct brakes. By introducing exec >> and eval() you are throwing the steering wheel out of the window. >> >> Seriously, try to make do with __import__() and getattr() to clean up >> your code a bit. >> >> Driving-analogies-well-beyond-the-abyss-ly yours >> Peter From sbassi at gmail.com Mon Jun 20 17:46:07 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Mon, 20 Jun 2005 18:46:07 -0300 Subject: Question about HTMLgen Message-ID: Hello, I am using HTMLgen. It is very nice. But I can't make it to generate an arbitrary command. For example I want to output this: Each time I put "<" it gets escaped from HTML, instead of being inserted inside. -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From ptmcg at austin.rr.com Mon Jun 13 11:12:43 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Jun 2005 08:12:43 -0700 Subject: ANN: pyparsing-1.3.1 released Message-ID: <1118675563.206703.263700@g14g2000cwa.googlegroups.com> (sorry if this is a double-post - I tried posting this last night but I think GoogleGroups ate it) Pyparsing is a pure-Python class library for quickly and easily constructing recursive-descent parsers. Pyparsing takes a "building-block" approach to parser construction, as opposed to code generation methods (such as lex/yacc) or pattern definition strings (such as regular expressions). Version 1.3.1 includes some minor enhancements, plus some performance improvements that can really improve parsing speed for grammars that use the Combine class (often used in specifying floating point numbers). The 1.3.1 change notes are listed below. Download pyparsing at http://pyparsing.sourceforge.n?et. -- Paul McGuire Version 1.3.1 - June 12, 2005 ----------------------------- - Added markInputline() method to ParseException, to display the input text line location of the parsing exception. (Thanks, Stefan Behnel!) - Added setDefaultKeywordChars(), so that Keyword definitions using a custom keyword character set do not all need to add the keywordChars constructor argument (similar to setDefaultWhitespaceChars()). (suggested by rzhanka on the SourceForge pyparsing forum.) - Simplified passing debug actions to setDebugAction(). You can now pass 'None' for a debug action if you want to take the default debug behavior. To suppress a particular debug action, you can pass the pyparsing method nullDebugAction. - Refactored parse exception classes, moved all behavior to ParseBaseException, and the former ParseException is now a subclass of ParseBaseException. Added a second subclass, ParseFatalException, as a subclass of ParseBaseException. User-defined parse actions can raise ParseFatalException if a data inconsistency is detected (such as a begin-tag/end-tag mismatch), and this will stop all parsing immediately. (Inspired by e-mail thread with Michele Petrazzo - thanks, Michelle!) - Added helper methods makeXMLTags and makeHTMLTags, that simplify the definition of XML or HTML tag parse expressions for a given tagname. Both functions return a pair of parse expressions, one for the opening tag (that is, '') and one for the closing tag (''). The opening tagame also recognizes any attribute definitions that have been included in the opening tag, as well as an empty tag (one with a trailing '/', as in '' which is equivalent to ''). makeXMLTags uses stricter XML syntax for attributes, requiring that they be enclosed in double quote characters - makeHTMLTags is more lenient, and accepts single-quoted strings or any contiguous string of characters up to the next whitespace character or '>' character. Attributes can be retrieved as dictionary or attribute values of the returned results from the opening tag. - Added example SimpleCalc.py, a refinement on fourFn.py that adds an interactive session and support for variables. (Thanks, Steven Siew!) - Added performance improvement, up to 20% reduction! (Found while working with Wolfgang Borgert on performance tuning of his TTCN3 parser.) - And another performance improvement, up to 25%, when using scanString! (Found while working with Henrik Westlund on his C header file scanner.) - Updated UML diagrams to reflect latest class/method changes. From steven.bethard at gmail.com Sun Jun 5 19:30:12 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 05 Jun 2005 17:30:12 -0600 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Nicolas Fleury wrote: > Since the current syntax would be there, the no-indentation syntax can > be explained in terms of the indentation syntax: > > """ > To avoid over-indentation, a with-statement can avoid defining a new > indentation block. In that case, the end of the with block is the end > of the current indentation block. > > with EXPR as VAR > REST OF BLOCK > > is equivalent to > > with EXPR as VAR: > BLOCK > """ > > What do you think? I fail to see the complexity... I guess my only real qualm about this is that I think it makes it harder to see where __exit__() methods are called. When I compare: def func(arg, baz): foo = bar(arg) with x as foo(baz) x.frobble() with y as x.bop() return frabble(x, y) with: def func(arg, baz): foo = bar(arg) with x as foo(baz): x.frobble() with y as x.bop(): return frabble(x, y) I find it much easier to identify in the second one that __exit__() methods will be called right before the function returns (after the return statement). YMMV. BTW, if you really like the optional-indentation idea, you should post it to the Wiki page (http://wiki.python.org/moin/WithStatement) -- Guido's been pretty quick to respond to any comments made there, so you could get some feedback much more useful than I can give you. ;) STeVe From chinook.nr at tds.net Mon Jun 13 21:11:44 2005 From: chinook.nr at tds.net (Chinook) Date: Mon, 13 Jun 2005 21:11:44 -0400 Subject: Going crazy... References: <42ae2729$1@griseus.its.uu.se> <42AE2A5B.7070206@islandtraining.com> Message-ID: <0001HW.BED3A710000A0D2CF0407550@news.gmane.org> On Mon, 13 Jun 2005 20:52:43 -0400, Gary Herron wrote (in article <42AE2A5B.7070206 at islandtraining.com>): > Jan Danielsson wrote: > >> Hello all, >> >> I'm 100% sure that I saw an example which looked something like this >> recently: >> >> >> >>>>> a=(1, 2, 3, 4, 5, 6) >>>>> b=(2, 3, 6) >>>>> a - b >>>>> >>>>> >> (1, 4, 5) >> >> The only new language I have been involved in lately is Python. Is my >> memory failing me, or have I seen such an Python-example somewhere? If >> so: Where; or more importantly: How does it work? >> >> I just tried typing the above in Python, and it - obviously - doesn't >> work, so it must be some other syntax. >> >> > Not with tuples, lists or dictionaries. However a more recent addition > to the language is Sets, and they support set differences: > > >>> from sets import Set > >>> Set([1,2,3,4,5,6]) - Set([2,3,6]) > Set([1, 4, 5]) > > > Gary Herron > > Looks like something that might be part of an example of class operator overloading??? But I'm not far enough along to quickly show a sample if such is possible. Lee C From peter at engcorp.com Tue Jun 14 08:15:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 08:15:23 -0400 Subject: collect data using threads In-Reply-To: References: Message-ID: Qiangning Hong wrote: > A class Collector, it spawns several threads to read from serial port. > Collector.get_data() will get all the data they have read since last > call. Who can tell me whether my implementation correct? [snip sample with a list] > I am not very sure about the get_data() method. Will it cause data lose > if there is a thread is appending data to self.data at the same time? That will not work, and you will get data loss, as Jeremy points out. Normally Python lists are safe, but your key problem (in this code) is that you are rebinding self.data to a new list! If another thread calls on_received() just after the line "x = self.data" executes, then the new data will never be seen. One option that would work safely** is to change get_data() to look like this: def get_data(self): count = len(self.data) result = self.data[:count] del self.data[count:] return result This does what yours was trying to do, but safely. Not that it doesn't reassign self.data, but rather uses a single operation (del) to remove all the "preserved" elements at once. It's possible that after the first or second line a call to on_received() will add data, but it simply won't be seen until the next call to get_data(), rather than being lost. ** I'm showing you this to help you understand why your own approach was wrong, not to give you code that you should use. The key problem with even my approach is that it *assumes things about the implementation*. Specifically, there are no guarantees in Python the Language (as opposed to CPython, the implementation) about the thread-safety of working with lists like this. In fact, in Jython (and possibly other Python implementations) this would definitely have problems. Unless you are certain your code will run only under CPython, and you're willing to put comments in the code about potential thread safety issues, you should probably just follow Jeremy's advice and use Queue. As a side benefit, Queues are much easier to work with! -Peter From darkpaladin79 at hotmail.com Mon Jun 6 21:18:25 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 21:18:25 -0400 Subject: SMTP help please Message-ID: I really can't figure out anything about the SMTP module. . .I think I'm in over my head( Im pretty new to python). Can someone show me a really(and I mean REALLY) basic tutorial for smtp or explain it? program: I want to make my program have a feedback form attached to it at the end which sends me the form when they're done. I don't especially want them to have to input all the needed details though. . .Just thought I'd put this in so you'd know what its for. -Ivan _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From steve at holdenweb.com Wed Jun 1 08:33:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Jun 2005 08:33:07 -0400 Subject: Stupid Newbie Question Concerning CGI and Reading Forward Slashes In-Reply-To: <1117567041.941039.103380@g14g2000cwa.googlegroups.com> References: <1117533288.097148.134270@g14g2000cwa.googlegroups.com> <1117567041.941039.103380@g14g2000cwa.googlegroups.com> Message-ID: Joey C. wrote: > Steve Holden wrote: > >>It's not a common question, but it's relatively easily answered. You are >>splitting everything but the filename off with os.path.split and then >>complaining about the result! Once you stop doing that your problem is >>solved. > > > Thus, it's a stupid newbie question. Thanks a lot for your help. It > seems I was just being plain stupid. > Well that's not stupidity, just "over-programming" ;-) Glad you are moving forward. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From zanesdad at bellsouth.net Thu Jun 30 11:55:21 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 30 Jun 2005 11:55:21 -0400 Subject: I have a question. In-Reply-To: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> References: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Message-ID: <42C415E9.3010707@bellsouth.net> Nathan Pinno wrote: > Hi all, > > Does Python have a random function? If so, can you show me an example >using it? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > > > > > Take your pick: In [5]: import random In [6]: random.choice(range(10)) Out[6]: 2 In [7]: random.choice(range(10)) Out[7]: 7 In [8]: random.choice(range(10)) Out[8]: 8 In [9]: random.choice(range(10)) Out[9]: 8 In [14]: random.random() Out[14]: 0.56386154889489271 In [15]: random.random() Out[15]: 0.47322827346926843 In [16]: random.random() Out[16]: 0.39921336622176518 In [17]: random.random() Out[17]: 0.65521407248459007 In [18]: random.random() Out[18]: 0.74525381787627598 In [20]: r = range(10) In [21]: random.shuffle(r) In [22]: r Out[22]: [6, 4, 9, 7, 2, 0, 8, 3, 5, 1] Jeremy Jones From cpunerd4 at gmail.com Sat Jun 18 10:48:13 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 07:48:13 -0700 Subject: extreme newbie In-Reply-To: <3hiq3lFh0dsfU1@uni-berlin.de> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> Message-ID: <1119106093.097295.320940@g44g2000cwa.googlegroups.com> even so, crackers have a harder time getting into compiled programs rather than intepreted languages. I know hiding the code won't stop all crackers but it will stop some of the casual theifs won't it? It's not so much that they could steal code, it's that they could alter it and release it somewere else and make their own money off it. cpunerd4 From mailing at Filetoad.com Tue Jun 14 23:53:15 2005 From: mailing at Filetoad.com (Filetoad.com) Date: Wed, 15 Jun 2005 03:53:15 GMT Subject: Filetoad.com Latest Software Virus and spyware Message-ID: An HTML attachment was scrubbed... URL: From deets at web.de Sun Jun 19 19:01:56 2005 From: deets at web.de (Diez B. Roggisch) Date: Mon, 20 Jun 2005 01:01:56 +0200 Subject: functions with unlimeted variable arguments... In-Reply-To: <1119218400.989803.230410@g47g2000cwa.googlegroups.com> References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> <7xr7f0yv0c.fsf@ruckus.brouhaha.com> <1119218400.989803.230410@g47g2000cwa.googlegroups.com> Message-ID: <3hmbr5FhrifcU1@uni-berlin.de> Xah Lee wrote: > oops... it is in the tutorial... sorry. > > though, where would one find it in the python reference? > i.e. the function def with variable/default parameters. > > This is not a rhetorical question, but where would one start to look > for it in the python ref? > a language is used by programers. Subroutine definition with > variable/default parameters is a basic issue a programer wants to know, > and different languages differs very much in how they handle this. This > is what i mean that the language doc should be programing oriented, as > opposed to computer-sciency or implementation oriented... Basically this boils down to you being to stupid to know the difference between a library reference and a language reference. And still you consider yourself to be above reading the tutorial in the first place to grasp even the simplest aspects about python? Gosh, this certainly isn't the first, but certainly one of the most enjoyable moronities you've been presenting to us. When does it occur to you that that type of moron-centric documentation you're bragging about is not needed by anybody else than you? So start writing "An introduction to Python for morons, by a moron - the Xah Lee Files" yourself - take your time, apart from you nobody needs it. Really. And stop annoying people who are willing to help others seeking advice who do show the will and abilities to actually dig into something and learn instead of crying out in rage all the time because python (or it's docs for that matter) doesn't seem to fit what your obviously severely limited understanding of concepts behind programming and computers in general tells you it should be. But I have the feeling you won't restrain yourself from blathering away in this NG - so thank god to killfiles... Diez From lars at gustaebel.de Thu Jun 30 12:24:49 2005 From: lars at gustaebel.de (=?iso-8859-1?q?Lars_Gust=E4bel?=) Date: Thu, 30 Jun 2005 18:24:49 +0200 Subject: python 2.4: tarfile tell() and seek() seem to be broeken References: Message-ID: On Thu, 02 Jun 2005 19:52:24 +0200, N. Volbers wrote: > Thanks for taking care of it ;-) I submitted patch #1230446 today which ought to fix the problem. -- Lars Gust?bel lars at gustaebel.de From onurb at xiludom.gro Mon Jun 27 09:00:29 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 27 Jun 2005 15:00:29 +0200 Subject: noob question In-Reply-To: <1119781728.934326.99600@g14g2000cwa.googlegroups.com> References: <1119781728.934326.99600@g14g2000cwa.googlegroups.com> Message-ID: <42bff873$0$7675$636a15ce@news.free.fr> qwweeeit at yahoo.it wrote: > Hi Matt, > I also am almost a newbie (in Python) and my approach to variable > naming > follows more or less the Hungarian Type Notation Defined. which is seen as a bad practice anywhere outside Win32... http://mindprod.com/jgloss/unmainnaming.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steve at REMOVETHIScyber.com.au Fri Jun 10 10:05:46 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Jun 2005 00:05:46 +1000 Subject: without shell References: Message-ID: On Sun, 12 Jun 2005 23:16:35 +0530, km wrote: > hi all, > > can any linux command be invoked/ executed without using shell (bash) ? py> import os py> status = os.system("ls") Prints the output of ls and stores the exit code into status. py> file_list = os.popen("ls").read() Stores the output of ls into file_list. Or see the module "commands". > what abt security concerns ? Yes, there are serious security concerns. You should be *very* careful about executing strings generated by users. You probably don't want your program executing something like os.system("rm -rf /"). -- Steven. From jeff.maitland at gmail.com Wed Jun 29 09:34:29 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Wed, 29 Jun 2005 09:34:29 -0400 Subject: Got an interesting problem. (platform ruuning issue) Message-ID: <6829832e05062906341c3a8999@mail.gmail.com> when running scripts they seem to work fine on ia-32 but I get segfault on ia-64 what the heck should I be looking for? I did notice that it seems to work ok only for certain scripts but any script that imports MySQLdb or glob seems to make this occur. Thanks Jeff From chinook.nr at tds.net Tue Jun 14 22:16:20 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 14 Jun 2005 22:16:20 -0400 Subject: Dynamic class inheritance && something else References: <20050614163909.19881.qmail@web61025.mail.yahoo.com> Message-ID: <0001HW.BED507B4000EADB3F0407550@news.gmane.org> On Tue, 14 Jun 2005 12:39:09 -0400, Vero wrote (in article <20050614163909.19881.qmail at web61025.mail.yahoo.com>): > Hi. My name is Veronica, I am a master student at UNAM. I am working on > something related to Artificial Inteligence and I have been looking for the > most appropriated programming language to implement my algorithms. I found > python to be very close to what I need, but there are still a couple of > details that I haven't been able to solve. > > First, (and most important) I would like to be able to dynamically modify the > classes from which a class inherits. I haven't found any way to do it with > the language as it is. If there is a way, any suggestion will be truly > appreciated. If I had to modify the source code to achieve this, I hope that > you could give me some hints; I have an idea of how something like this could > be achieved but since I don't know deeply the python sourcode I could get > lost. > > Second, since my program will be modifying classes during run time, I would > like to have a way to write on a file the python code that would have defined > the class with the functions and attributes as they were left, just as if it > had been writen like that at the very begining. I need it to be python code > because I will be using that latter. Maybe I will have to solve this second > problem by myself but I just wrote in case anybody had a good idea. > > Thank you very much for your help. > > > > Vero > > La sociedad es inherentemente democr?tica: la mayor?a decide si pensar p or > si misma o si dejar que alguien m?s les diga qu? pensar. > > http://mx.geocities.com/aqua_azul_2000/ > > > > > > > __________________________________________________ > Correo Yahoo! > Espacio para todos tus mensajes, antivirus y antispam ?gratis! > Reg?strate ya - http://correo.yahoo.com.mx/ > I'm not going to show my ignorance by noting the half-baked thoughts I had when reading your post, but I will point you at the article that initiated my thoughts so you might form your own (fully baked hopefully :~). http://www-106.ibm.com/developerworks/linux/library/l-pymeta.html Lee C From nid_oizo at yahoo.com_remove_the_ Thu Jun 23 14:24:55 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 23 Jun 2005 14:24:55 -0400 Subject: Reraise exception with modified stack In-Reply-To: <42baf628$1@nntp0.pdx.net> References: <20zue.74584$Kk4.909739@news20.bellglobal.com> <42badec0$1@nntp0.pdx.net> <42baf628$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Have you tried it? Looked to do what you described to me when I run a > sample. Note that is an unadorned raise with no args. The idea is to > simply modify the exception object and then use raise to carry the > whole original exception along as if not intercepted. Oups, sorry, I tried it but wrote "raise exception" instead of "raise". Yes, that's a very good idea indeed. I'll change to that. Thx, Nicolas From peter.o.mueller at gmx.de Sat Jun 18 05:10:59 2005 From: peter.o.mueller at gmx.de (peter.o.mueller at gmx.de) Date: 18 Jun 2005 02:10:59 -0700 Subject: Using swig to use an existing dll/library Message-ID: <1119085859.495422.169890@g14g2000cwa.googlegroups.com> Hi together, i have a Windows DLL in C that is internally multithreaded and provides a callback function to signal specific events. As I understood one can use "normal" C-code with swig. Is it also possible to use existing DLLs? Does swig can also handel the callback method? If not - is there another wrapper toolkit that can do that? Thanks, Peter From http Wed Jun 22 17:36:52 2005 From: http (Paul Rubin) Date: 22 Jun 2005 14:36:52 -0700 Subject: Optimize a cache References: Message-ID: <7xoe9yt6ob.fsf@ruckus.brouhaha.com> Florian Lindner writes: > What possible you see to optimize this lookup? Or anything else you see to > make it better? Use the heapq module. From pwatson at redlinepy.com Mon Jun 20 12:25:27 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Mon, 20 Jun 2005 11:25:27 -0500 Subject: Want to learn a language - is Python right? References: <1119264546.393296.245650@f14g2000cwb.googlegroups.com> <7x3brdjnyt.fsf@ruckus.brouhaha.com> <1119278824.847517.294700@g47g2000cwa.googlegroups.com> Message-ID: <3ho8vrFhmoprU1@individual.net> "Aziz McTang" wrote in message news:1119278824.847517.294700 at g47g2000cwa.googlegroups.com... > Hi Paul, > > Thanks for your input. > > As usual, hearing some answers helps formulate the question... > > What I'm looking for is more to learn one good, comprehensive > programming language well than several approximately on an ad hoc > basis. What I also failed to mention is the desire to develop my > presently limited computer skills a lot further. You have received some good advice. There are strong tools to support localization, but they are not inexpensive. They might be lower cost than developing your own. However, your goal to develop your programming skills is also a cost to be considered. Are you interested in developing an open source localization tool? A consideration for web applications is who will be maintaining the code. If these are all your own and no one else will ever work on them, then use any tool you like. Coding them in x86 assembly language would increase your computer knowledge, but we both know that is not the right tool for this task. From peter at engcorp.com Thu Jun 2 18:04:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 18:04:05 -0400 Subject: saving .zip or .txt email attachments instead of deleting them In-Reply-To: <1117748648.949066.94300@g44g2000cwa.googlegroups.com> References: <1117746435.769666.186810@z14g2000cwz.googlegroups.com> <119utnt1mvdue50@news.supernews.com> <1117748648.949066.94300@g44g2000cwa.googlegroups.com> Message-ID: scrimp wrote: > OK i got past that syntax error I think. This is the error I am getting > now....AttributeError: 'NoneType' object has no attribute 'lower' All > Im reading is a text file of the email message with an attachment --zip > file Always post a *complete* traceback, with the line numbers and all, cut and pasted from the output window. That way there's no chance we will misunderstand the error you are getting or have to guess at what's really happening. -Peter From tziade at nuxeo.com Fri Jun 10 17:21:06 2005 From: tziade at nuxeo.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Fri, 10 Jun 2005 23:21:06 +0200 Subject: IMAP Proxy In-Reply-To: <42A9F6BA.6060206@quad.com.ar> References: <42A99B1C.7020507@nuxeo.com> <42A9F6BA.6060206@quad.com.ar> Message-ID: <42AA0442.3040405@nuxeo.com> Alex Verstraeten wrote: > Tarek Ziad? wrote: > >> Hi, >> >> I want to write a small TCP Server in Python to make an IMAP Proxy for >> post-processing client requests. >> >> It is not long either complicated but needs to be very robust so... >> maybe someone here has already done such a thing I can use or know where >> i can get it ? >> >> Cheers, >> >> Tarek >> >> > I wrote one with twisted.. it's quite easy and minimal.. > you can start hooking stuff to it, I only use "dataReceived" > as I only need to watch what cmds are imap client sending. > > from twisted.protocols.portforward import ProxyFactory > from twisted.protocols.portforward import ProxyClientFactory > from twisted.protocols.portforward import ProxyClient > from twisted.protocols.portforward import ProxyServer > from twisted.internet import reactor > > class PS(ProxyServer): > def dataReceived(self, data): > print "PS->dataReceived(%s)" %repr(data) > ProxyServer.dataReceived(self, data) > pfactory = ProxyFactory('192.168.1.1',143) > pfactory.protocol = PS > > reactor.listenTCP(143, pfactory) > reactor.run() > > this will bind to port 143 and proxy all requests to the real imap > server at 192.168.1.1, while printing the commands being sent to stdout. > Here, my proxy runs on different box than imap server... if you need > to put both of them on same box you'll need to change the port number > of , either imap server, or imap proxy. > > well.. > hope it helps Great thank you, it will help me for sure. Tarek > > > Alex From t-meyer at ihug.co.nz Tue Jun 28 21:20:43 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Wed, 29 Jun 2005 13:20:43 +1200 Subject: Modules for inclusion in standard library? In-Reply-To: Message-ID: >>> Do you have any other good and valued Python modules that you would >>> think are bug-free, mature (that includes a long release >>> distance) and useful enough to be granted a place in the stdlib? >> >> First of all, numeric/numarray, obviously! > > There has been recent discussion about this. Check the > python-dev list archives I think. Or the python-dev summaries, of course . The most recent one to discuss this was this one, I believe: =Tony.Meyer From twic at urchin.earth.li Tue Jun 28 13:22:49 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 28 Jun 2005 18:22:49 +0100 Subject: Better console for Windows? In-Reply-To: <1119928421.011284.183810@o13g2000cwo.googlegroups.com> References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> Message-ID: On Tue, 27 Jun 2005, Brett Hoerner wrote: > Rune Strand wrote: > > Christ, thanks. When you install Windows it should pop up first thing > and ask if you want to be annoyed, Y/N. What, and not install if you say no? Perhaps your best way to get a proper shell on windows is just to install a proper shell; Cygwin () has bash, but it also installs a bunch of other unixish stuff you might or might not want. This: http://www.steve.org.uk/Software/bash/ looks like a standalone bash, plus ls, mv, cp rm, chmod and less. Here: http://gnuwin32.sourceforge.net/packages.html you can get various further bits of free software compiled for windows, including: http://gnuwin32.sourceforge.net/packages/coreutils.htm the GNU coreutils, which is the 1% of commands you use 99% of the time. bash + coreutils should do nicely. For a mostly complete GNU development toolchain, check out MinGW: http://www.mingw.org/ Which, IMHO, is a better solution than Cygwin for general programming. tom -- i'm prepared to do anything as long as someone else works out how to do it and gives me simple instructions... -- Sean From robin at SPAMREMOVEjessikat.fsnet.co.uk Thu Jun 2 03:53:58 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 02 Jun 2005 07:53:58 +0000 Subject: BUG pythonw vs subprocess In-Reply-To: <87mzq97l1a.fsf@pobox.com> References: <429DFB8B.4090102@jessikat.fsnet.co.uk> <7xfyw1zzt1.fsf@ruckus.brouhaha.com> <87mzq97l1a.fsf@pobox.com> Message-ID: <429EBB16.7040302@jessikat.fsnet.co.uk> John J. Lee wrote: > Paul Rubin writes: > > >>I thought pythonw didn't provide a console and so it could be that >>stdin and stdout aren't connected to anything. Popen therefore doesn't >>make sense. You have to use sockets or something. > > > Yeah... I don't know about module subprocess, but I recall there's a > known bug where pythonw actually crashes on win9x when you write to > sys.stdout, since it's not connected to anything... > > > John So then it's not possible to get pythonw apps eg tkinter guis to use subprocess properly? Seems a bit daft to me. -- Robin Becker From onurb at xiludom.gro Tue Jun 28 07:42:13 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 28 Jun 2005 13:42:13 +0200 Subject: Newbie: Help Figger Out My Problem In-Reply-To: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> Message-ID: <42c13796$0$28110$636a15ce@news.free.fr> ChuckDubya at gmail.com wrote: > ##Coin Flip: randomly flips 100 "coins" and prints results > ##Original draft: june 27, 2005 > ##Chuck > > import random > heads = 0 > tails = 0 > flips = 0 > while flips < 99: > coin = random.randrange(0, 2) > if coin == 0: > heads = heads + 1 heads += 1 > else: > tails = tails + 1 idem > flips = flips + 1 idem > if flips >= 99: Why do you think you need this test ?-) > print "Heads: " + heads print "Heads: %d" % heads > print "Tails: " + tails idem > print "Total: " + flips + "flips" idem > raw_input("Press the enter key to exit.") May I suggest this version ? from random import randrange def flip_coins(flips): coins = [0, 0] for i in xrange(flips): coins[randrange(0, 2)] += 1 return coins[0], coins[1] if __name__ == "__main__": flips = 100 heads, tails = flip_coins(flips) print "Heads: %d\nTails %d\nTotal: %d flips\n" % (heads, tails, flips) #raw_input("Press the enter key to exit.") HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From dalke at dalkescientific.com Thu Jun 2 16:57:29 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 02 Jun 2005 20:57:29 GMT Subject: Two questions References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: Steven D'Aprano wrote: > I can think of a number of reasons why somebody might want to hide their > code. In no particular order: > (3) You have create an incredibly valuable piece of code that will be > worth millions, but only if nobody can see the source code. Yeah right. - id software makes a lot of money licensing their 3D FPS engine - stock market trading companies make money in part by having specialized software to help with market trading, forecasts, etc. > (8) You are programming a game or puzzle, and you don't want players to > cheat by reading the source code. Consider pulling out the information > they need to cheat and putting it in an encrypted data file instead. But code is data ... > There may be other reasons for wanting to keep the code secret. Some of > them might even be good reasons, for some value of "good". You are the US government developing software to design/test the next generation nuclear weapons system and don't want any other country to use it. (GnuNuke?) You are a student working on a take-home example and you aren't allowed to work with/help anyone else > If you really what to hide your code, you might like to think about > using C-extensions instead. Or go the Amazon/EBay/Google approach and provide only client access to your code. Andrew dalke at dalkescientific.com From peter at engcorp.com Tue Jun 7 08:03:41 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Jun 2005 08:03:41 -0400 Subject: file permissions on windows XP (home) In-Reply-To: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> Message-ID: <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> barney wrote (having trouble with a file): [snip] > IOError: [Errno 13] Permission denied: "02 - New Year's Day.mp3" [snip] > I'm at a loss to understand what is going on. > > Why is python returing True from os.access? > Why isn't chmod doing anything? Check your results using os.stat() after doing that, perhaps? If it shows the right values for the permissions, then clearly the problem has nothing to do with Python per se, or your own code. > Why is cygwin able to sort the problem out? I suggest (a) trying again, making sure that the file is not in use in another application such as the Media Player, and (b) trying with some other file that you've just created for the purpose of testing this to compare your results. I just tried the whole sequence you showed without any problems, on a file called "test" that I created in my own My Music folder. (Not using cygwin, however, since I don't use it, but in this case there was no need for me to use it anyway.) -Peter From peter at engcorp.com Wed Jun 15 06:13:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Jun 2005 06:13:49 -0400 Subject: Does Python cause tides? In-Reply-To: <42AFB8FD.1060504@REMOVEMEcyber.com.au> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> <42AFB8FD.1060504@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Roy Smith wrote: >> Steven D'Aprano wrote: >> >High and low tides aren't caused by the moon. >> They're not??? > > Nope. They are mostly caused by the continents. ... > The true situation is that tides are caused by the interaction of the > gravitational fields of the sun, the moon and the Earth, the rotation of > the Earth, the physical properties of water, its salinity, the depth, > shape and composition of the coast and shoreline, the prevailing ocean > currents, vibrationary modes of the ocean (including up to 300 minor > harmonics), ocean storms, and even the wind. You can understand why we > usually simplify it to "the moon causes the tides", even though the moon > isn't even the largest contributing factor. > > See, for example: > > http://home.hiwaay.net/~krcool/Astro/moon/moontides/ Steve, please go and read that page again. While I readily accept that you may be far more of an expert on tides than I, Roy, and whoever contributed to the Wikipedia article, nearly every section on the page that *you* referenced directly contradicts your basic claims. I quote: "Tides are created because the Earth and the moon are attracted to each other..." "The sun's gravitational force on the earth is only 46 percent that of the moon. Making the moon the single most important factor for the creation of tides." [you said the moon isn't the largest factor] "Since the moon moves around the Earth, it is not always in the same place at the same time each day. So, each day, the times for high and low tides change by 50 minutes." [if the moon were not such a large cause, it wouldn't have this effect] I believe you are still just saying that the *magnitude* of the tides is greatly affected by other things, such as the shoreline, but what I keep reading is you basically saying "the moon is not the cause and is only a minor factor". I also see nothing to suggest that if the moon and the sun were removed from the picture, there would be much in the way of tides at all. (The page you quoted says the sun has about 46% the effect of the moon which, if true, means the statement "the presence of the moon and the sun cause tides" still seems pretty accurate, certainly not a "lie for children" but merely a simplification, if anything. -Peter From cjbottaro at alumni.cs.utexas.edu Fri Jun 10 17:25:20 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Fri, 10 Jun 2005 16:25:20 -0500 Subject: DB API 2.0 and transactions References: Message-ID: Magnus Lycka wrote: > You might have spotted a fairly nasty bug there! > PostgreSQL violates the SQL standards by running in autocommit mode > unless you explicitly perform its non-standard BEGIN command. If you > are right about the behaviour you describe, the PostgreSQL binding > for Python that you use may have taken the easy route, and performs > a "BEGIN" on connect and after every commit or rollback. Check this out... import pgdb import time print time.ctime() db = pgdb.connect(user='test', host='localhost', database='test') time.sleep(5) db.cursor().execute('insert into time_test (datetime) values (CURRENT_TIMESTAMP)') db.commit() curs = db.cursor() curs.execute('select datetime from time_test order by datetime desc limit 1') row = curs.fetchone() print row[0] Fri Jun 10 17:27:21 2005 '2005-06-10 17:27:21.654897-05' Notice the times are exactly the same instead of 5 sec difference. What do you make of that? Some other replies to this thread seemed to indicate that this is expected and proper behavior. -- C > If so, this is a serious bug, and should be reported as one. The correct > thing to do is to insert the BEGIN just before the first SQL statement > that is affecting transactions. Of course, this means that the binding > needs to keep track of transaction state, and this makes it a little > bit more complicated. You'd need something like this in the binding: > > class connection: > def __init__(...): > ... > self.inTxn = False > > def commit(...): > ... > self.inTxn = False > > def rollback(...): > ... > self.inTxn = False > > def execute(...): > ... > if not self.inTxn: > perform the BEGIN command against the backend > self.inTxn = True > ... > > Actually, this isn't perfect either, because not all SQL commands > (should) initate transactions, but it's a lot closer to what we want. > > This bug has implications far beyond timestamps. Imagine two transaction > running with isolation level set to e.g. serializable. Transaction A > updates the AMOUNT column in various rows of table X, and transaction > B calculates the sum of all AMOUNTS. > > Lets say they run over time like this, with | marking begin and > > commit (N.B. ASCII art, you need a fixed font): > > ...|--A-->.......|--A-->........ > ...........|-B->.........|-B->.. > > This works as expected...but imagine transactions implicitly > begin too early: > > |-----A-->|---------A-->|------- > |------------B->|----------B->|- > > This will cause the aggregations in B to show "delayed" results. > Not at all what one might expect... > > > For more about isolation levels, see e.g. here: > http://pgsqld.active-venture.com/transaction-iso.html From jepler at unpythonic.net Fri Jun 24 15:35:53 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 24 Jun 2005 14:35:53 -0500 Subject: Frame widget (title and geometry) In-Reply-To: References: Message-ID: <20050624193550.GB30048@unpythonic.net> Tkinter.Frame instances are not created with "geometry" or "title" attributes. Whatever 'classtitle' and 'classtitle2' are, they are not written to work with Tkinter.Frame instances. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From michele.simionato at gmail.com Tue Jun 14 11:12:27 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Jun 2005 08:12:27 -0700 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42AED7B3.8060009@carmen.se> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <42AED7B3.8060009@carmen.se> Message-ID: <1118761947.653174.239440@g47g2000cwa.googlegroups.com> Magnus Lycka: > While scientists do build and create things, > the ultimate goal of science is understanding. Scientists build > so that they can learn. Programmers and engineers learn so that > they can build. Well put! I am going to add this to my list of citations :) Michele Simionato From grobinson at transpose.com Wed Jun 29 10:08:57 2005 From: grobinson at transpose.com (garyrob) Date: 29 Jun 2005 07:08:57 -0700 Subject: MS Compiler to build Python 2.3 extension Message-ID: <1120054137.471983.240320@o13g2000cwo.googlegroups.com> Hello, I have no Microsoft compilers on my hard disk. I recenly built a C API Python extension for Python 2.3 on OS X, and now I need to build it for Windows. When I start Python 2.3 on Windows, it says it was built with "MS C v.1200". I'm not sure how that maps to current Microsoft compiler products. Someone who works with me (at another location) has MS Visual Studio Pro 6.0 which he isn't using and can send to me. Will that do the trick? Or do I need to buy another package? Thanks, Gary -- Gary Robinson CTO [of a very tiny company] Emergent Music, LLC grobinson at goombah.com 207-942-3463 Company: http://emergentmusic.com Blog: http://www.garyrobinson.net From philippe at philippecmartin.com Tue Jun 14 18:04:05 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 14 Jun 2005 22:04:05 GMT Subject: eclipse, pydev and wxpython - standard output redirection ? References: Message-ID: app = MyApp(False) app.MainLoop() will keep wxWidgets from using its own window. Grzegorz wrote: > Hello, I'm using eclipse with pydev plugin, I'm working on a program using > wxpython . > When I'm executing that application standard error output does not show in > eclipse console window - wxpython seems to redirect standard output to > some another window , and closes that window immediately, so I can't see > any error messagess. > Is there a way to redirect standard output to eclipse console ? From tjreedy at udel.edu Fri Jun 10 13:29:02 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Jun 2005 13:29:02 -0400 Subject: Abstract and concrete syntax References: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Message-ID: "Kay Schluehr" wrote in message news:1118411839.922816.94730 at g43g2000cwa.googlegroups.com... > Mandus schrieb: >> You can do stuff like this: lambda x: x and 2 or 3 This is limited by the requirement (often met) that bool(true-branch) == True > You can also do this > > lambda x: {True:2,False:3}.get(bool(a)) This is limited by the requirement that both branches be computable regardless of the value of the condition. > which is both beautiful and pythonic. Beauty is in the eye of the beholder. It seems that relative pythonicity sometimes is also ;-). Terry J. Reedy From http Wed Jun 1 22:26:14 2005 From: http (Paul Rubin) Date: 01 Jun 2005 19:26:14 -0700 Subject: Pressing A Webpage Button References: <119sqr8dihknie3@corp.supernews.com> <119sra7cit79816@corp.supernews.com> Message-ID: <7xll5th4u1.fsf@ruckus.brouhaha.com> Grant Edwards writes: > > I presume you can figure out how to open the URL instead of > > printing it? > > Ah, never mind. That doesn't work. Google somehow detects > you're not sending the query from a browser and bonks you. Try setting the User-agent: header to one that looks like a browser. From kenneth.m.mcdonald at sbcglobal.net Tue Jun 14 00:35:51 2005 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 13 Jun 2005 23:35:51 -0500 Subject: Which Python Wiki engine? Message-ID: <4F136808-6D44-49E1-963C-59426C9602F1@sbcglobal.net> I'm looking for a Wiki engine to set up for my company, so that we can incrementally add user documentation for a fairly complex program, plus allow users to add their own comments for the benefit of others. I'd strongly prefer a Python-based Wiki, since that allows me the chance to add plugins with minimal effort (being a python enthusiast and programmer). However, I'd also like something that can provide a little more structure than MoinMoin seems able to provide (correct me if I'm wrong.) Though there would be cross-references amongst various sections, the idea is that the structure of the wiki would be very much that of an outline, with topics divided into sub topics and then into sub sub topics, etc. A person at our company would be the "editor"; responsible for setting up the original structure, putting in the documentation we currently have, and periodically editing contributions from users. Here are some of the features I'd greatly like to have that I haven't seen provided by the (relatively few) wiki engines I've looked at. Mind you, I don't claim to have looked at even these few exhaustively. (No time!) MoinMoin is the one I've looked at the most. 1) Automatically generated table of contents, based on the outline structure. This would be regenerated periodically (probably nightly) 2) Ability for users to add new subsections, but not to change that part of the document structure which has been locked by the editor. 3) Clear visual distinction between material added by the users, and material added or approved by the editor. 4) Legal-style numbering of sections, subsections, etc. 5) Ability to have single pages containing both locked text (which users cannot edit or delete) and unlocked text. Such a page would consist of one or more locked blocks of text, interspersed with comments put in by users. Users could put comments anywhere except side a locked text block. Ideally, this would also be something that doesn't depend on a backend database or other things besides the web server and python packages. This is not likely to be a wiki where huge amounts of interactivity must be supported; there will probably be a moderate amount of reading, and a small amount of writing. If you know of any Python wiki engines which can satisfy (even partially) this list, please let me know. I'd strongly prefer to have a Python engine. On the other hand, if you know of another type of wiki that matches well with these requirements, I won't complain if you mention it :-) Thanks, Ken McDonald From Scott.Daniels at Acm.Org Tue Jun 28 12:20:52 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 28 Jun 2005 09:20:52 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <5y3we.1231$cb6.1034@newssvr30.news.prodigy.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <5y3we.1231$cb6.1034@newssvr30.news.prodigy.com> Message-ID: <42c17153$1@nntp0.pdx.net> Philippe C. Martin wrote: > Hi, > > A couple links ... > > > http://www.summerland.uku.co.uk/ > http://pylogo.org/ > http://www.python.org/sigs/edu-sig/ > > > BORT wrote: > > >>Please forgive me if this is TOO newbie-ish. >> >>I am toying with the idea of teaching my ten year old a little about >>programming. I started my search with something like "best FREE >>programming language for kids." After MUCH clicking and high-level >>scanning, I am looking at Python and Forth. Both have advocates that >>say each is a great approach to learning computers. >> >>My programming classes were a long, long time ago in a land far, far >>away. My programming muscles, which were never truly developed, have >>atrophied even so. That said, I want to learn this as we go. The >>PROCESS of research and using net resources for a self-learning >>adventure is almost as much of the goal as learning a programming >>skill. >> >>That said, a good learning goal for my kid would be to create a >>spelling tutor for his little brother. My (simple) vision would be: >> >>1. an input file of this week's word list >>2. use a free text-to-speech engine to call out one word at a time >>3. in turn, monitor each key press as a particular word is being >>typed, beeping on an incorrect keystroke and going to the next word if >>correct >> >>I don't care if it takes a year or two to get to this level, I just >>want a vehicle that will take us there. >> >>I told my son, who wants to learn how to compute probabilities, that we >>have to start with some boring stuff so we can learn how to do the cool >>stuff. Adding and subtracting aren't really fun, but figuring odds on >>rolling dice IS fun. Learning to program will be kind of like that. >>He accepted that explantion. >> >>So, that said... In ~simplest~ terms for the stated goal -- Forth or >>Python? >>...the goal is NOT the spelling tutor... it is learning how to use a >>tool to solve a problem. I am asking which tool is more suited to an >>otherwise arbitrary direction of "spelling tutor program." >> >>[NOTE: This is not a troll. I'm geting ready to bark up a tree and I >>prefer to avoid the wrong one. I am cross-posting.] >> >>Thanks > > Over on comp.python.education, David Handy recently announced his book with a fairly long message (excerpted here): ... Written by a homeschooling Dad and professional software developer, "Computer Programming is Fun!" fills a need for a book that teaches computer programming to teenage youth. ... 208 pages, $29.95 plus taxes and shipping if applicable Order from the author's web site: http://www.handysoftware.com/cpif/ ... "Why teach computer programming to teenagers? For the same reason you would teach them piano or any other musical instrument. Consider the computer an instrument for the mind." I've not seen the book myself, but it seems like it is targeted to very nearly your situation, so I'd investigate it. --Scott David Daniels Scott.Daniels at Acm.Org From jepler at unpythonic.net Wed Jun 15 08:32:36 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 15 Jun 2005 07:32:36 -0500 Subject: Strange socket problem In-Reply-To: References: Message-ID: <20050615123233.GB2888@unpythonic.net> When using os.system(), files that are open in the parent are available in the child, as you can see here in Linux' listing of the files open by the child program: [jepler at sofa jepler]$ python -c 'f = open("/tmp/test", "w"); print f.fileno(); import os; os.system("ls -l /proc/self/fd")' 3 total 5 lrwx------ 1 jepler jepler 64 Jun 15 07:25 0 -> /dev/pts/2 lrwx------ 1 jepler jepler 64 Jun 15 07:25 1 -> /dev/pts/2 lrwx------ 1 jepler jepler 64 Jun 15 07:25 2 -> /dev/pts/2 l-wx------ 1 jepler jepler 64 Jun 15 07:25 3 -> /tmp/test lr-x------ 1 jepler jepler 64 Jun 15 07:25 4 -> /proc/3108/fd You may be able to set the FD_CLOEXEC flag on the files that should not be passed to children, something like this: old = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) Refer to a real Unix reference for more information on what FD_CLOEXEC does. You may want to replace the use of os.system() with fork + close files + exec. Then "myserver.py" will no longer have the listening socket descriptor of your cherrypy server. Python 2.4's 'subprocess' module may work better in this respect than os.system. It seems to include support for requesting that fds be closed in the child (the close_fds parameter to subprocess.Popen) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kveretennicov at gmail.com Mon Jun 20 20:47:55 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 02:47:55 +0200 Subject: Tuple Unpacking in raise In-Reply-To: <200506201709.39961.jstroud@mbi.ucla.edu> References: <200506201709.39961.jstroud@mbi.ucla.edu> Message-ID: <4660fe30050620174761417d7c@mail.gmail.com> On 6/21/05, James Stroud wrote: > Hello All, > > Is this a bug? No, it works as documented. You should've consulted language reference: http://docs.python.org/ref/raise.html - kv From eric_brunel at despammed.com Thu Jun 23 08:23:34 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 23 Jun 2005 14:23:34 +0200 Subject: Python 2.1 / 2.3: xreadlines not working with codecs.open Message-ID: Hi all, I just found a problem in the xreadlines method/module when used with codecs.open: the codec specified in the open does not seem to be taken into account by xreadlines which also returns byte-strings instead of unicode strings. For example, if a file foo.txt contains some text encoded in latin1: >>> import codecs >>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace') >>> [l for l in f.xreadlines()] ['\xe9\xe0\xe7\xf9\n'] But: >>> import codecs >>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace') >>> f.readlines() [u'\ufffd\ufffd'] The characters in latin1 are correctly "dumped" with readlines, but are still in latin1 encoding in byte-strings with xreadlines. I tested with Python 2.1 and 2.3 on Linux and Windows: same result (I haven't Python 2.4 installed here) Can anybody confirm the problem? Is this a bug? I searched this usegroup and the known Python bugs, but the problem did not seem to be reported yet. TIA -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From rrr at ronadam.com Wed Jun 15 18:56:03 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 15 Jun 2005 22:56:03 GMT Subject: "also" to balance "else" ? In-Reply-To: References: Message-ID: <7m2se.132779$IO.112@tornado.tampabay.rr.com> Terry Hancock wrote: > On Wednesday 15 June 2005 03:57 am, Fredrik Lundh wrote: > >>where your "abnormal behaviour" is, of course, the expected >>behaviour. if you insist on looking at things the wrong way, >>things will look reversed. > > Unfortunately, the converse is true, too: no matter how twisted > an idea is, you can make it seem logical with the right point > of view. ;-) > > I think the OP is correct in saying that for-else is non-intuitive. Although it took me a while to verbalize it, My motivation for suggesting 'also' was/is that it might enable writing code that better matches the context it's written in. Code that's more intuitive and as a result more readable. There are 4 possible outcomes to a loop. 1. Not Entered. Nothing done. (current possible for-else behavior) 2. Entered. Some loops may have completed. 3. Not finished. (break) Some loops may have completed. 4. Finished (no break) All possible loops completed. (current for-else behavior) (This doesn't include exit by return statements.) One possibility may be to use a keyword that parallels the except in try-except blocks which will accept a test designator. (building on your refernce to finally) (This is probably a definite after 3k item I think, or more likely just academic discussion, but I enjoy that too.) So use loop as the new keyword with the above conditions and have the else as the alternative to any of them. (Feel free to suggest different words) for item in collection: if : print "item found" break loop Finished: print "item was not found." return for item in collection: if : print "bad item" break loop Finished: print "The Collection pass's the test" else: print "The Collection is invalid" for item in collection: loop NotEntred: print "The Collection was empty" for line in textbuffer: print line loop Entered: print time.date() else: print "The buffer was empty" while : if : break loop Entered: I think these are sufficiently explicit as to avoid being non-intuitive. The endloop might be generalized into a endblock or endsuite statement possibly. I'm not sure if that would have any uses's in the proposed "with" statements or not. (?) Regards, Ron From trentm at ActiveState.com Thu Jun 9 12:56:36 2005 From: trentm at ActiveState.com (Trent Mick) Date: Thu, 9 Jun 2005 09:56:36 -0700 Subject: Windows Installer with Debug Dlls and Libs In-Reply-To: <1118333031.075043.28230@g43g2000cwa.googlegroups.com> References: <1118325506.087132.64400@g44g2000cwa.googlegroups.com> <1118333031.075043.28230@g43g2000cwa.googlegroups.com> Message-ID: <20050609165636.GA3468@ActiveState.com> [DE wrote] > Thanks Trent. That's good news. > > Does ActivateState produce the debug package everytime they build a > python release ? Yes, we do. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From grante at visi.com Wed Jun 22 23:03:11 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Jun 2005 03:03:11 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> Message-ID: <11bk9jf5s6gk204@corp.supernews.com> On 2005-06-23, Tim Peters wrote: > C89 doesn't define the result of that, but "most" C compilers these > days will create a negative 0. > >> and (double)0x80000000 doesn't work, I think you meant something like float f; *((uint32_t*)&d) = 0xNNNNNNNN; >> And I don't know how to test for it either, x < 0.0 is not >> necessarily true for negative 0. > > If it's a 754-conforming C compiler, that's necessarily false (+0 and > -0 compare equal in 754). Picking the bits apart is again the closest > thing to a portable test. Across platforms with a 754-conforming > libm, the most portable way is via using atan2(!): [brain-bending example elided] It's probobly because of the domains in which I work, but I don't think I've ever cared whether a zero is positive or negative. I understand why it's easier to impliment things that way, but I don't see why anybody would care. OTOH, NaNs and Infinities are indisposable for real-world stuff. >> I am not trying to say there is no way to do this. I am >> trying to say it takes thought and effort on every detail, in >> the definition, implementations, and unit tests. > > It's par for the course -- everyone thinks "this must be easy" > at first, and everyone who persists eventually gives up. > Kudos to Michael Hudson for persisting long enough to make > major improvements here in pickle, struct and marshal for > Python 2.5! I would think it doable if one assumed IEEE-754 FP (famous last words). I suppose there are still a few VAX machines around. And there are things like TI DSPs that don't use IEEE-754. -- Grant Edwards grante Yow! RELAX!!... This at is gonna be a HEALING visi.com EXPERIENCE!! Besides, I work for DING DONGS! From greg at cosc.canterbury.ac.nz Wed Jun 1 22:32:46 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 02 Jun 2005 14:32:46 +1200 Subject: Python as client-side browser script language In-Reply-To: <7xk6leylhi.fsf@ruckus.brouhaha.com> References: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> <7xk6leylhi.fsf@ruckus.brouhaha.com> Message-ID: <3g79esFb0jkrU1@individual.net> Paul Rubin wrote: > Huh? The language itself has to provide the sandbox. > Remember that scripts have to be able to see > certain DOM elements but not others, and some of them have to be > read-only, etc. If the DOM objects are implemented as built-in Python types, there shouldn't be any difficulty with that. Python objects have complete control over which attributes can be read or written by Python code. That, together with restricting what the open() function can do, ought to provide a pretty good sandbox. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From scrimp212 at yahoo.com Thu Jun 2 17:07:15 2005 From: scrimp212 at yahoo.com (scrimp) Date: 2 Jun 2005 14:07:15 -0700 Subject: saving .zip or .txt email attachments instead of deleting them Message-ID: <1117746435.769666.186810@z14g2000cwz.googlegroups.com> How would I go about retriving an email message and stripping out the attachment into a file. I have seen examples where they would read in the file and delete the attachment and replace it with text saying that the attachment was removed. For testing purposes Im using a pop3 server to receive messages from. I can log into the pop3 server get all the messages and print them to the screen or to a file. I have another script that I got from ActiveSource that deletes the attachment. This is where I will need to save the attachment instead of deleting it. Any help is appreciated thanks! --Barry From newsgroups at jhrothjr.com Sun Jun 19 09:11:02 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 19 Jun 2005 07:11:02 -0600 Subject: See Pep 315. was: Re: Loop until condition is true References: Message-ID: <11barn8pdf1kbd7@news.supernews.com> See Pep 315, which is still open, and targeted at 2.5. It survived the recent spate of PEP closings and rejections. http://www.python.org/peps/pep-0315.html John Roth "Remi Villatel" wrote in message news:d90bej$c0a$1 at news.tiscali.fr... > Hi there, > > There is always a "nice" way to do things in Python but this time I can't > find one. > > What I'm trying to achieve is a conditionnal loop of which the condition > test would be done at the end so the loop is executed at least once. It's > some way the opposite of "while". > > So far, all I got is: > > while True: > some(code) > if final_condition is True: > break > # > # > > What I don't find so "nice" is to have to build an infinite loop only to > break it. > > Is there a better recipe? > > -- > ================== > Remi Villatel > maxilys_ at _tele2.fr > ================== From steve.horsley at gmail.com Fri Jun 24 18:21:32 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Fri, 24 Jun 2005 23:21:32 +0100 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: Neat. Thank Goodness for syntax-colouring editors! Steve From Xavier.Decoret at imag.fr Fri Jun 24 08:48:16 2005 From: Xavier.Decoret at imag.fr (=?ISO-8859-1?Q?Xavier_D=E9coret?=) Date: Fri, 24 Jun 2005 14:48:16 +0200 Subject: Two questions on lambda: Message-ID: Hi, I cannot find the way to do generic lambda functions using the lambda syntax in python. I am probably missing a point. For example, the code # f = lambda : print "hello" # f() does not compile, although: # def f(): # print "hello" # f() does compile. Is there a particular syntax for lambda that I am missing or is it simply limited and I cannot do what I want with lambda. In the same spirit, how can I do to compute intermediary values in the body of a lambda function. Let's say (dummy example): f = lambda x : y=x*x,y+y In languages like Caml, you can do: let f = function x -> let y=x*x in y+y;; Does the lambda : syntax in python allow for the same kind of constructs? Thanks. From cameron.mccloud at gmail.com Tue Jun 21 10:58:55 2005 From: cameron.mccloud at gmail.com (cameron.mccloud at gmail.com) Date: 21 Jun 2005 07:58:55 -0700 Subject: Running WMI within a Windows service Message-ID: <1119365935.658724.225470@g14g2000cwa.googlegroups.com> Hi, When trying to import the WMI module in a Python Windows Service, I get the following: dynamic module does not define init function (initwmi) The WMI version is 0.6. Python 2.4 on Win32, Python Win32 extensions version 203 Code below, Cam. def SvcDoRun(self): import servicemanager servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, '')) print "Running..." try: import wmi print "module imported" except Exception, e: print "exception: " + str(e) print "Stopped." self.ReportServiceStatus(win32service.SERVICE_STOPPED) servicemanager.LogMsg( servicemanager.EVENTLOG_INFORMATION_TYPE, servicemanager.PYS_SERVICE_STOPPED, (self._svc_name_, "EventMonSvc stopping..." ) ) From fredrik at pythonware.com Thu Jun 2 05:50:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 2 Jun 2005 11:50:52 +0200 Subject: Moving Places, Subtracting from slices/lists References: <429EACCE.8050101@snow.email.ne.jp><429EB16C.1090509@snow.email.ne.jp> Message-ID: Elliot Temple wrote: > btw hotcat[:] is a *copy* of hotcat, so just leave out "[:]" when you want to modify the thing you're looping over, you need to be careful. looping over a copy is often a good idea (see the Python tutorial and the FAQ for more on this). > enumerate is a function that adds indexes to a list. observe: >>> hotcat = ['roof', 'roof', 'roof'] >>> for index, word in enumerate(hotcat): >>> if word == 'roof': del hotcat[index] >>> print hotcat ['roof'] if I understand the OP correctly, he wants to *move* the "roof" to the end of the string. try: hotcat.remove("root") hotcat.append("root") except ValueError: pass is most likely the fastest way to do that. From harold.fellermann at upf.edu Tue Jun 14 13:08:43 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 14 Jun 2005 19:08:43 +0200 Subject: Problem with simple C extension In-Reply-To: <3dc77a7e7317fe820d6452813bc3809f@upf.edu> References: <3dc77a7e7317fe820d6452813bc3809f@upf.edu> Message-ID: On 14.06.2005, at 18:58, harold fellermann wrote: > Am I stupid or what? Yes I was ... > // PhysicsDPD instance structure > typedef struct { > PyObject_HEAD > double cutoff; > double friction; > double noise; > double dt; > } hyper_PhysicsDPD; > > > //-------------------------------------------------------------------- > // tp_init > //-------------------------------------------------------------------- > static int > hyper_PhysicsDPD_init(hyper_PhysicsDPD *self, PyObject *args, PyObject > *kwds) > { > if (!PyArg_ParseTuple(args,"ffff", > &self->cutoff, > &self->friction, > &self->noise, > &self->dt > )) > return -1; > > printf("%f %f %f > %f\n",self->cutoff,self->friction,self->noise,self->dt); > > return 1; > } format string must be "dddd" - as the members are defined as doubles, not floats. Sorry to bother you. - harold - -- A country without army is like a fish without bicycle. -- From drool.galz at gmail.com Wed Jun 22 05:47:06 2005 From: drool.galz at gmail.com (Aditi) Date: 22 Jun 2005 02:47:06 -0700 Subject: suggestions invited Message-ID: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> hi all...i m a software engg. student completed my 2nd yr...i have been asked to make a project during these summer vacations...and hereby i would like to invite some ideas bout the design and implementation of an APPLICATION MONITORING SYSTEM....i have to start from scrach so please tell me how to go bout it rite from the beggining this is the first time i m making a project of this complexity... i have to make a system used by the IT department of a company which contains 31 applications and their details which are being used in a company ...the details are... Application sub application catagory platform language version IT owner functional owner remarks source code documentation last updated dates i want to design a system such that it lets the it employee enter the name of the application and gives him all the details about it...please suggest an appropriate design and the language which you think would be best to use...as i have enouf time with me and i can learn a new language as well...i currently know c and c++...your advise is welcomed Aditi From gene.tani at gmail.com Thu Jun 30 13:48:34 2005 From: gene.tani at gmail.com (gene tani) Date: 30 Jun 2005 10:48:34 -0700 Subject: Seeking IDE In-Reply-To: <1120152895.285989.66450@g44g2000cwa.googlegroups.com> References: <1120152895.285989.66450@g44g2000cwa.googlegroups.com> Message-ID: <1120153714.920539.111070@g49g2000cwa.googlegroups.com> woops: I like komodo (almost free, from: http://wiki.python.org/moin/Komodo and jedit: http://www.opensourcetutorials.com/tutorials/Server-Side-Coding/Python/review-of-python-ide/page1.html http://plugins.jedit.org/updates.php?page=3 Heard good things about WIngIDE, the other almost free IDE From nidoizo at yahoo.com Sun Jun 5 00:34:05 2005 From: nidoizo at yahoo.com (Nicolas Fleury) Date: Sun, 05 Jun 2005 00:34:05 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Ilpo Nyyss?nen wrote: > Nicolas Fleury writes: >>What about making the ':' optional (and end implicitly at end of current >>block) to avoid over-indentation? >> >>def foo(): >> with locking(someMutex) >> with opening(readFilename) as input >> with opening(writeFilename) as output >> ... > > > How about this instead: > > with locking(mutex), opening(readfile) as input: > ... > > So there could be more than one expression in one with. I prefer the optional-indentation syntax. The reason is simple (see my discussion with Andrew), most of the time the indentation is useless, even if you don't have multiple with-statements. So in my day-to-day work, I would prefer to write: def getFirstLine(filename): with opening(filename) as file return file.readline() than: def getFirstLine(filename): with opening(filename) as file: return file.readline() But I agree that in the case of only one with-statement, that's no big deal. Also, if multiple with-statements are separated by other indentating statements, your proposal doesn't help: with locking(lock) if condition: with opening(filename) as file for line in file: ... would still be needed to be written: with locking(lock): if condition: with opening(filename) as file: for line in file: ... Regards, Nicolas From sjmachin at lexicon.net Wed Jun 15 19:36:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Jun 2005 09:36:56 +1000 Subject: splitting delimited strings In-Reply-To: References: Message-ID: <42B0BB98.2020106@lexicon.net> Nicola Mingotti wrote: > On Wed, 15 Jun 2005 23:03:55 +0000, Mark Harrison wrote: > > >>What's the most efficient way to process this? Failing all >>else I will split the string into characters and use a FSM, >>but it seems that's not very pythonesqe. > > > like this ? No, not like that. The OP said that an embedded @ was doubled. > > >>>>s = "@hello at world@@foo at bar" >>>>s.split("@") > > ['', 'hello', 'world', '', 'foo', 'bar'] > >>>>s2 = "hello at world@@foo at bar" >>>>s2 > > 'hello at world@@foo at bar' > >>>>s2.split("@") > > ['hello', 'world', '', 'foo', 'bar'] > > > bye From tdaitx at gmail.com Sat Jun 4 21:19:35 2005 From: tdaitx at gmail.com (=?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=) Date: Sat, 4 Jun 2005 22:19:35 -0300 Subject: Looking for help with a python-mode/pdbtrack/gdb patch In-Reply-To: <17058.3002.992164.256805@montanaro.dyndns.org> References: <17058.3002.992164.256805@montanaro.dyndns.org> Message-ID: Unfortunatly the only tip I can give you is that there's a list for mode-python in http://mail.python.org/mailman/listinfo/python-mode, but you probably already know about it. Regards, Tiago S Daitx On 6/4/05, Skip Montanaro wrote: > > > Can someone who uses Emacs's python-mode, pdbtrack and gdb take a look at > this simple but ancient patch: > > > http://sourceforge.net/tracker/index.php?func=detail&aid=785816&group_id=86916&atid=581351 > > As you'll see from the discussion, Barry had problems with it from XEmacs > and was thinking of rejecting it way back when. I'd like to resolve it one > way or the other, but I've never used pdb, let alone pdbtrack. > > Thanks, > > Skip > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From edreamleo at charter.net Tue Jun 21 08:31:30 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Tue, 21 Jun 2005 07:31:30 -0500 Subject: Leo 4.3.1 released Message-ID: Leo 4.3.1 final is now available at http://sourceforge.net/projects/leo/ This is a bug fix release, with the following new features: - Added support for Tk resource files. - Added support for coloring the PL/SQL language. - All Mark commands are now undoable. - Improved Resize To Screen command. What people are saying about Leo -------------------------------- "Still using Leo as the world's best outliner and not for programming tasks (I'm in love for more than 2 years now :-)" -- Franz Geiger More quotes at: http://webpages.charter.net/edreamleo/testimonials.html What makes Leo special? ----------------------- - Leo's outlines add a new dimension to programming. - Leo shows you your code and data the way _you_ want to see them. - Leo extends, completes and simplifies literate programming. - Leo's script buttons bring scripts to data. What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.2.1 or above and tcl/tk 8.4 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From tzot at sil-tec.gr Tue Jun 28 08:45:54 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 15:45:54 +0300 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: On Mon, 13 Jun 2005 20:27:46 -0400, rumours say that Roy Smith might have written: >Andrea Griffini wrote: >> Hehehe... a large python string is a nice idea for modelling >> memory. >Actually, a Python string is only good for modelling ROM. If you want to >model read-write memory, you need a Python list. This is a misquote, since Andrea paraphrased what Peter Maas said. It was Peter that suggested string usage to model memory (and obviously forgot momentarily about string immutability in python). If you included (even better, read :) the rest of Andrea's paragraph, it would be obvious that you actually agree with Andrea. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From rkern at ucsd.edu Wed Jun 29 14:43:28 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 29 Jun 2005 11:43:28 -0700 Subject: Graphs/statistics using wxPython In-Reply-To: <42c2e859$1@griseus.its.uu.se> References: <42c2df8b$1@griseus.its.uu.se> <42c2e859$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Robert Kern wrote: >>Trick #1: >> >>import matplotlib > > Oh. :-) > > That's a pretty neat trick -- now can you make my embarrassment go away? > > I did do a quick search to see if anyone had done anything similar; > but I guess I wasn't using the right keywords. > >>;-) > > You may point and laugh. > > Damn, that's a neat toolkit! Thanks for pointing me to it! It's okay. Just about every Pythonista in the sciences has, at one time or another, started a plotting library. It's a rite of passage. Welcome to the club. :-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Thu Jun 23 17:05:31 2005 From: http (Paul Rubin) Date: 23 Jun 2005 14:05:31 -0700 Subject: Hardening enviroment by overloading __import__? References: Message-ID: <7x8y10dbs4.fsf@ruckus.brouhaha.com> Steve Juranich writes: > Am I barking up the wrong tree with __import__?? Yes. > Where should I look for this answer? Don't. From knight at baldmt.com Wed Jun 8 23:51:15 2005 From: knight at baldmt.com (Steven Knight) Date: Wed, 8 Jun 2005 23:51:15 -0400 (EDT) Subject: identifying 64-bit Windows from 2.3.5? Message-ID: If I have installed 2.3.5 from the python.org Windows installer, can any one point me to a run-time way to identify whether I'm running on a 32-bit vs. 64-bit version of Windows XP, given that Python itself was built on/for a 32-bit system? I hoped sys.getwindowsversion() was the answer, but it returns the same platform value (2) on both 32-bit and 64-bit systems. sys.platform ("win32") and sys.maxint are both set at compile time. Things like os.uname() aren't on Windows. Can some Windows-savvy Pythonista point me to some way to distinguish between these two? Thanks, --SK From kent37 at tds.net Tue Jun 7 05:53:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 05:53:25 -0400 Subject: help with sending mail in Program In-Reply-To: References: Message-ID: <42a56e49_3@newspeer2.tds.net> Ivan Shevanski wrote: > Could someone send me a good tutorial for sending mail then? The one I > found is not what I'm looking for. Also please dont send me the stmp > definition cause i've looked at that enough. Here is a module I use to send mail to myself using smtplib: #!/usr/local/bin/python ''' Send mail to me ''' from smtplib import SMTP def sendToMe(subject, body): me = '"Kent Johnson" ' send(me, me, subject, body) def send(frm, to, subject, body): s = SMTP() # s.set_debuglevel(1) s.connect('mail.mycompany.com') s.ehlo('10.0.3.160') # IP address of my computer, I don't remember why I needed this msg = '''From: %s Subject: %s To: %s %s ''' % (frm, subject, to, body) s.sendmail(frm, to, msg) s.quit() if __name__ == '__main__': sendToMe('Testing', 'This is a test') From devrim.erdem at gmail.com Thu Jun 9 12:03:51 2005 From: devrim.erdem at gmail.com (DE) Date: 9 Jun 2005 09:03:51 -0700 Subject: Windows Installer with Debug Dlls and Libs In-Reply-To: References: <1118325506.087132.64400@g44g2000cwa.googlegroups.com> Message-ID: <1118333031.075043.28230@g43g2000cwa.googlegroups.com> Thanks Trent. That's good news. Does ActivateState produce the debug package everytime they build a python release ? If this is a policy at ActivateState, I will feel myself on better grounds :) Ciao, DE From hancock at anansispaceworks.com Thu Jun 30 21:18:35 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 30 Jun 2005 20:18:35 -0500 Subject: Favorite non-python language trick? In-Reply-To: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> References: <1120144919.331057.319450@f14g2000cwb.googlegroups.com> Message-ID: <200506302018.35261.hancock@anansispaceworks.com> On Thursday 30 June 2005 10:21 am, todddeluca at gmail.com wrote: > If I had to choose one feature, I would like to see better support for > nested lexical scopes. However, I imagine this is no easy "trick" to > add to the language. Doesn't that already happen in versions 2.2+? What exactly do you mean by "better" support for nested lexical scopes? Can you give an example of something that doesn't work, but should? I'm just curious. The whole question of lexical scoping seemed a bit esoteric to me at the time --- I think I must instinctively avoid situations where it causes trouble. The most important exception would have to be the behavior of lambda and locally-defined functions --- I still expect them to know the variables in the defining function's namespace. But I think that lexical scoping fixed this so that they do, IIRC (I don't use them often, so I'm not so sure). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From gherron at islandtraining.com Mon Jun 13 20:52:43 2005 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 13 Jun 2005 17:52:43 -0700 Subject: Going crazy... In-Reply-To: <42ae2729$1@griseus.its.uu.se> References: <42ae2729$1@griseus.its.uu.se> Message-ID: <42AE2A5B.7070206@islandtraining.com> Jan Danielsson wrote: >Hello all, > > I'm 100% sure that I saw an example which looked something like this >recently: > > > >>>>a=(1, 2, 3, 4, 5, 6) >>>>b=(2, 3, 6) >>>>a - b >>>> >>>> >(1, 4, 5) > > The only new language I have been involved in lately is Python. Is my >memory failing me, or have I seen such an Python-example somewhere? If >so: Where; or more importantly: How does it work? > > I just tried typing the above in Python, and it - obviously - doesn't >work, so it must be some other syntax. > > Not with tuples, lists or dictionaries. However a more recent addition to the language is Sets, and they support set differences: >>> from sets import Set >>> Set([1,2,3,4,5,6]) - Set([2,3,6]) Set([1, 4, 5]) Gary Herron From meissnersd at yahoo.com Sat Jun 4 15:25:54 2005 From: meissnersd at yahoo.com (meissnersd) Date: 4 Jun 2005 12:25:54 -0700 Subject: Komodo ide font color issue Message-ID: <1117913149.451873.313480@g49g2000cwa.googlegroups.com> Komodo ide font color issue I prefer a dark back ground with light text. So I edited my preferences and made a dark color scheme. I am using python and komodo is dumping exceptions out in the output window in red. Red text on a black background is awful. This does not change even when I set the color of stderr in my scheme in the Preferences dialog. So how can I change the text color of exceptions in the Komodo output window? Thanks Karl From Scott.Daniels at Acm.Org Wed Jun 22 18:44:43 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Jun 2005 15:44:43 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <11bjeckpaq4ir8e@corp.supernews.com> References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> Message-ID: <42b9e272$1@nntp0.pdx.net> Grant Edwards wrote: > On 2005-06-22, Scott David Daniels wrote: >>Several issues: > > >>(1) The number of distinct NaNs varies among platforms. > > According to the IEEE standard, there are exactly two: > signalling and quiet, and on platforms that don't impliment > floating point exceptions (probably in excess of 99.9% of > python installations), the difference between the two is moot. But it does not specify the representation of such NaNs. > Negative 0 isn't a NaN, it's just negative 0. Right, but it is hard to construct in standard C. >>(2) There is no standard-conforming way to create these values. > What standard are you looking at? My copy of the IEEE 754 > standard is pretty clear. I was talking about the C89 standard. In the absence of a C standard way to create, manipulate, and test for these values, you must implement and test platform-by-platform. > The bit patterns are defined by the IEEE 754 standard. Perhaps this is right and I misunderstand the standard, but my understanding is that the full bit pattern is not, in fact, defined. > If there are Python-hosting platoforms that don't use IEEE 754 as > the floating point representation, then that can be dealt with. There are. > Python has _tons_ of platform-specific code in it. But the _tons_ are written in C89 C. > Why all of a sudden is it taboo for Python to impliment > something that's not universally portable and defined in a > standard? Where's the standard defining Python? It is not taboo. I am trying to explain why it is not a trivial task, but a substantial effort. If you are willing to perform the substantial effort, good on you, and I'll help. If you simply want to implement on the two platforms you use, and want everyone else to implement the interface you choose, that seems to me an unreasonable request. --Scott David Daniels Scott.Daniels at Acm.Org From agriff at tin.it Tue Jun 14 03:04:20 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 14 Jun 2005 07:04:20 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <42ade58b$0$25394$636a15ce@news.free.fr> <6fasa1d9l1m4ifkn3nmo34j3eu6t1cmabe@4ax.com> <8cOdnXxJn6Ah0TPfRVn-pg@comcast.com> Message-ID: <870ta1hjq16n4kgj93fc57tg1cffdrk6au@4ax.com> On Mon, 13 Jun 2005 22:19:19 -0500, D H wrote: >The best race driver doesn't necessarily know the most about their car's >engine. The best baseball pitcher isn't the one who should be teaching >a class in physics and aerodynamics. Yes, both can improve their >abilities by learning about the fundamentals of engines, aerodynamics, >etc., but they aren't "bad" at what they do if they do not know the >underlying principles operating. And when you've a problem writing your software who is your mechanic ? Who are you calling on the phone for help ? Andrea From hancock at anansispaceworks.com Mon Jun 13 13:04:40 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 12:04:40 -0500 Subject: case/switch statement? In-Reply-To: References: Message-ID: <200506131204.40950.hancock@anansispaceworks.com> On Sunday 12 June 2005 07:33 am, Dan Sommers wrote: > > There is no case statement in Python. If you don't care about > > readability, one alternative is to use a dictionary: > > > case = {5: do_this, 6: do_that} > > case.get(x, do_something_else)() > > I find this very readable. YMMV. Yeah, and I find this even more so: case = { 5: do_this, 6: do_that, } case.get(x, do_default)() Which is looking pretty close to a case statement, anyway. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Mon Jun 13 02:43:55 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 16:43:55 +1000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: > At some point, you need to draw a line in the sand (so to speak) and say, > "I understand everything down to *here* and can do cool stuff with that > knowledge. Below that, I'm willing to take on faith". I suspect you would > agree that's true, even if we don't agree just where the line should be > drawn. You seem to feel that the level of abstraction exposed by a > language like C is the right level. I'm not convinced you need to go that > far down. I'm certainly not convinced you need to start there. The important question is, what are the consequences of that faith when it is mistaken? As a Python developer, I probably won't write better code if I understand how NAND gates work or the quantum mechanics of electrons in solid crystals. But I will write better code if I understand how Python implements string concatenation, implicit conversion from ints to longs, floating point issues, etc. It seems that hardly a day goes by without some newbie writing to the newsgroup complaining that "Python has a bug" because they have discovered that the floating point representation of 0.1 in decimal is actually more like 0.10000000000000001. And let's not forget the number of bugs out there because developers thought that they didn't need to concern themselves with the implementation details of memory management. It makes a difference whether your algorithm runs in constant time, linear, quadratic, logarithmic or exponential time -- or something even slower. The implementation details of the language can hide quadratic or exponential algorithms in something that looks like a linear or constant algorithm. Premature optimization is a sin... but so is unusably slow code. -- Steven. From Me at Privacy.NET Fri Jun 3 01:07:10 2005 From: Me at Privacy.NET (Jeff_Relf) Date: 3 Jun 2005 05:07:10 GMT Subject: Bailo's LSD: Linux_Shamanism_Delusion. References: <429e7155.6739473@news.alphalink.com.au> Message-ID: Hi Bailo, Leonard_Blaisdell and Phaywood, I commented: Targeting Win_XP is taboo somehow ? It shouldn't be. And Bailo, under the heavy influence of LSD, the Linux_Shamanism_Delusion, asked: Why target a dying OS that a Top Tier ISP has abandoned ? Earthlink is featuring the thrifty Xandrox Desktop. A $69 PC that is Internet Ready? Earthlink has it! It can't be done with the buggy and expensive Windos... As I've told you a quintillion times, Earthlink's insanity aside, Win_XP is a virtual network, quite indepent of the connection used. Linux is hardly an OS, it's just a kernel. From lycka at carmen.se Wed Jun 1 07:50:39 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Jun 2005 13:50:39 +0200 Subject: Python as client-side browser script language In-Reply-To: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> References: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> Message-ID: Rune Strand wrote: > What would it take to create a Firefox extension that enables Python as > a script language in the browser - just like Javascript? Is it at all > possible? Are the hundred good reasons not to bother? There are certainly security issues. A simple implementation that started a "normal" Python script fetched from a web page on the shady parts of the web, could certainly create a real mess. Ouch. Today, there are really no security features in Python. Those that used to exist were remvoed since they weren't considered good enough, and giving a false sense of security wasn't considered a good idea... Of course, one might suggest that it's the task of the browser, and not of the scripting language, to provide a safe sandbox where scripts can mess around and without causing havoc on your computer. Such a system in the browser could be used to grant different rights to different parts of the net, regardless of what kind of scripting language the resources on those parts of the net use. When Firefox has something like that, it's time to start marketing Python for client side scripting I think. From kent37 at tds.net Tue Jun 7 20:51:11 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 20:51:11 -0400 Subject: Help! File objects and scoping In-Reply-To: References: Message-ID: <42a640b0$1_1@newspeer2.tds.net> bens wrote: > I'm trying to return an 'mmap' object from a function. The return > works, but some of the object's methods crash. Here are two examples > > doesntwork.py > --------------------------- > import mmap > import os > > name="/any/real/file/on/my/hard/drive" > > def getfile(name): > somefile=file(name, 'r+b') > mmapped = mmap.mmap(fileno=somefile.fileno(), \ > length=os.path.getsize(name)) > return mmapped > > mmapped=getfile(name) > mmapped.seek(1) #this works, so mmapped is a working mmap object > print mmapped.size() #this dies with an error > mmapped.close() > -------------------------- > > doesntwork.py dies with the error: > EnvironmentError: [Errno 9] Bad file descriptor My guess is that when getfile() returns, somefile goes out of scope and the actual file is closed. Try returning both somefile and mmapped or some other way of keeping a reference to someefile. Kent > > On the other hand, > doeswork.py > --------------------------- > import mmap > import os > > name="/the/exact/same/file" > > somefile=file(name, 'r+b') > mmapped = mmap.mmap(fileno=somefile.fileno(), \ > length=os.path.getsize(name)) > > mmapped.seek(1) #works fine > print mmapped.size() #works fine, prints out the right number > mmapped.close() > -------------------------- > > The only difference between doeswork and doesntwork is whether 'mmapped' > is created in the global scope or created in a local scope and returned. > Why does that make a difference? > > The strangest thing about this, I think, is that the error printed out > above, EnvironmentError, is listed in the docs under "only used as base > classes for other exceptions". In other words, it's never supposed to > be thrown. > > I'll take any advice you can give me. > Thanks, > Ben Schwartz > www.mit.edu/~bens/ From dalke at dalkescientific.com Wed Jun 1 23:22:11 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 02 Jun 2005 03:22:11 GMT Subject: any macro-like construct/technique/trick? References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <1117676088.978273.272940@g47g2000cwa.googlegroups.com> <1117680577.332110.241060@g47g2000cwa.googlegroups.com> Message-ID: Mac wrote: > After I wrote my post I realized I didn't provide enough context of > what I'm doing, [explanation followed] I have a similar case in mind. Some graph algorithms work with a handler, which is notified about various possible events: "entered new node", "doing a backtrack", "about to leave a node". A general algorithm may implement many of these. But if the handler doesn't care about some of the events there's still the cost of either doing a no-op call or checking if the callback function doesn't exist. I've considered the idea of limited macro/template support for that case, which either removes a callback or perhaps in-lines some user-supplied code for the given circumstance. >it... no... wait... no good, the problem is the following case: > # real line of code > DbgObjFoo(a,b,costly_function(c)) > # real line of code In another branch I suggested debug_emit(DbgObjFoo, a, b, costly_function(c)) which obviously wouldn't work for this case. The following lightly tested code would work (assuming appropriate debugging) debug_emit(DbgObjFoo, a, b, Call(costly_function, c, Call(expensive_function, d))) def debug_emit(klass, *args): if debug: emit_dbg_code(Call(klass, *args)()) class Call: def __init__(self, f, *args): self.f = f self.args = args def __call__(self): args = [] for arg in self.args: if isinstance(arg, Call): args.append(arg()) else: args.append(arg) return self.f(*args) There's still the overhead of making the Call objects, but it shouldn't be that large. You can save a smidgeon by doing if debug: class Call: ... as defined earlier else: def Call(f, *args): pass Andrew dalke at dalkescientific.com From greg at cosc.canterbury.ac.nz Thu Jun 2 23:00:55 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 03 Jun 2005 15:00:55 +1200 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <3g9vflFbd3puU1@individual.net> Andrew Dalke wrote: > You are the US government developing software to design/test the > next generation nuclear weapons system and don't want any other > country to use it. (GnuNuke?) Hmmm... if these are GPL weapons, if you want to fire them at anyone you'll *have* to make them available to all other countries as well... not good for non-proliferation... -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From philippe at philippecmartin.com Sat Jun 25 14:04:05 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 18:04:05 GMT Subject: Big problem fetching members from dynamically loaded module References: Message-ID: Hi, Hopefully to make things clearer: this works from a shell: In [23]:from SC.CARDS.BC import * In [24]:l = inspect.getmembers(eval('BC')) #l will get all members from class 'BC' whereas the code referenced below gets an exception saying 'BC' is not defined. Thanks, Philippe Philippe C. Martin wrote: > Hi, > > I'm getting pretty desperate here: > > The code below crashes on the last line (but works from a shell). > > The class 'BC' exists and the loop on self.__BC_EXEC_LIST passes fine. > > It's got to be something really stupid but I've been looking at it too > long I guess. > > Any clue would be quite welcome. > > Regards, > > Philippe > > > > > > > __EXEC_LIST = [ \ > 'import os', \ > 'import sys', \ > 'from SC.pilot.SC_Script_Processor import *', \ > 'from SC.utils.SC_Convert import *', \ > 'import string ', \ > 'from SC.iso.SC_Dec_ISO import *', \ > 'from SC.iso.SC_Enc_ISO import *', \ > 'from SC.iso.SC_Analysis import *', \ > 'sc_sp = SC_Script_Processor ()', \ > 'sc_enc = SC_Enc_ISO ()', \ > 'sc_dec = SC_Dec_ISO ()', \ > 'sc_a = SC_Analysis ()', \ > 'sc_conv = SC_Convert()' ] > > __BC_EXEC_LIST = ['from SC.CARDS.BC import *','from > SC.Solutions.SCF.BCInterface import *','sc_bc = BC_Interface()'] > > > for l_s in self.__BC_EXEC_LIST: #this loop works fine > try: > exec (l_s, self.m_process_global,self.m_process_local) > > except: > traceback.print_exc() > > for l_s in self.__EXEC_LIST: #this loop works fine > try: > exec (l_s, self.m_process_global,self.m_process_local) > > except: > print >> sys.stderr, 'FATAL INIT ERROR - PLEASE CHECK YOUR > CONFIGURATION' > > l = inspect.getmembers(eval('SC_Dec_ISO')) #THIS WORKS - the class > exists > l = inspect.getmembers(eval('BC')) #THIS CRASHES - the class > exists From jarausch at skynet.be Sat Jun 25 11:21:20 2005 From: jarausch at skynet.be (Helmut Jarausch) Date: Sat, 25 Jun 2005 17:21:20 +0200 Subject: BaseHTTPServer and priviledge separation? Message-ID: <42bd7671$0$341$ba620e4c@news.skynet.be> Hi, to use a port below 1000 on a Unix system one needs root priviledges. But it's dangerous to execute all of a script under those priviledges. Therefore I'd like to drop the root priviledges as soon as possible. (How) is this possible? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From cam.ac.uk at mh391.invalid Fri Jun 3 06:40:18 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 03 Jun 2005 11:40:18 +0100 Subject: optparse.py: FutureWarning error In-Reply-To: <429FBE20.8020608@lexicon.net> References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> Message-ID: John Machin wrote: > Michael Hoffman wrote: > >> Terry Reedy wrote: >> >>> c) Check to see if Python has a startup option for suppressing warnings >>> >>> As to c) python -h gives a list indicating what I thought, that -W >>> controls warnings, but gives insufficient info for me to use it, and >>> I didn't find any more in the docs. I hope someone else chimes in. >> >> >> >> man python. Search for -W. > > > """ > C:\junk>man python > 'man' is not recognized as an internal or external command, > operable program or batch file. > """ Well it's obviously not going to work if you don't install man. """ C:\Documents and Settings\MichaelH>man python PYTHON(1) NAME python - an interpreted, interactive, object-oriented programming language """ Here's a copy of the man page: http://linuxcommand.org/man_pages/python1.html -- Michael Hoffman From steve.horsley at gmail.com Thu Jun 30 13:39:27 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Thu, 30 Jun 2005 18:39:27 +0100 Subject: Scket connection to server In-Reply-To: References: Message-ID: JudgeDread wrote: > hello python gurus > > I would like to establish a socket connection to a server running a service > on port 29999. the host address is 10.214.109.50. how do i do this using > python? > > many thanks > > Off the top of my head (so there could be errors): import socket s = socket.Socket() s.connect((10.214.109.50, 29999)) s.send("Hello, Mum\r\n") That should point you in the right direction, anyway. There is a higher level socket framework called twisted that everyone seems to like. It may be worth looking at that too - haven't got round to it myself yet. Steve From fredrik at pythonware.com Mon Jun 20 09:09:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Jun 2005 15:09:52 +0200 Subject: global name not defined :$ References: <20050620101043.174B77AD7E@mail.internet.is> Message-ID: "Anna M." wrote: > I am trying to write a red-black tree implementation in python. I am very > new to python and appologize if my question is terribly stubid. But I ran > into some trouble. I have a class and in it there are functions but when I > try to run the code I have I just get an error on one of the functions > "global name 'balancedFourNode' is not defined" Now of course I realize > that I am doing something wrong when defining the function but I just can't > seem to find it. > > Any insight would be greatly appreciated. classes have methods, not functions. if "x" is an instance of a class and "method" is a method defined by that class, you should use "x.method()" to call the method. if you're trying to call the method from another method in the same class, use "self.method()". if you type "method" or "method(x)", Python won't know where to look. From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 28 16:10:38 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 28 Jun 2005 22:10:38 +0200 Subject: Modules for inclusion in standard library? In-Reply-To: <1119977801.449923.128330@o13g2000cwo.googlegroups.com> References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> <42c1662d$0$26260$626a14ce@news.free.fr> <1119977801.449923.128330@o13g2000cwo.googlegroups.com> Message-ID: <3idp5uFkua1fU1@individual.net> George Sakkis wrote: >> "bruno modulix" wrote: > >> George Sakkis wrote: >> > I'd love to see IPython replace the standard interpreter. >> I dont. > > Care to say why ? For an easy, quick interactive interpreter, it's way to overloaded with functions and too slow in startup. However, having ipython in the Python distribution is worth a thought. Reinhold From finite.automaton at gmail.com Thu Jun 9 13:14:03 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 9 Jun 2005 10:14:03 -0700 Subject: Any way to not create .pyc files? Message-ID: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> In short: Is there any way to run Python WITHOUT trying to create .pyc files (or .pyo) or to have Python not attempt to import the .pyc files it finds? Reason: We have a site-specific package installed on a network drive[1]. When anyone with write access imports this package, the network drive gets spammed with .pyc files. If these .pyc files exist, they appear to cause problems when other users' Python interpreters use them instead of the .py files. (I know, they *should* work, but they don't). This may have something to do with the fact that all of these users (on Windows) have the network drive mapped to arbitrary drive letters. I don't know. PEP 304 would have helped, but it appears to be deceased. What I really want is a command line option I'm going to have to cobble together a work-around, like having imported modules delete their own .pyc files immediately after import, but it would be really nice to have a /good/ way of not using .pyc... (footnotes) [1] Because it's an administrative nightmare to distribute code updates to dozens of non-technical users From leftwing17 at gmail.com Tue Jun 7 18:39:16 2005 From: leftwing17 at gmail.com (Adam Endicott) Date: 7 Jun 2005 15:39:16 -0700 Subject: wxPython: GridBagSizer, EXPAND, and HtmlListBox In-Reply-To: <1118093139.869663.310520@g44g2000cwa.googlegroups.com> References: <1118093139.869663.310520@g44g2000cwa.googlegroups.com> Message-ID: <1118183956.405917.93470@o13g2000cwo.googlegroups.com> Just an update if anyone runs across this through google. It appears this was an issue fixed in 2.6.0.1 (or 2.6.1.0, I forget which exactly). I was using 2.6.0.0. From philippe at philippecmartin.com Mon Jun 27 23:33:21 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 03:33:21 GMT Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <5y3we.1231$cb6.1034@newssvr30.news.prodigy.com> Hi, A couple links ... http://www.summerland.uku.co.uk/ http://pylogo.org/ http://www.python.org/sigs/edu-sig/ BORT wrote: > Please forgive me if this is TOO newbie-ish. > > I am toying with the idea of teaching my ten year old a little about > programming. I started my search with something like "best FREE > programming language for kids." After MUCH clicking and high-level > scanning, I am looking at Python and Forth. Both have advocates that > say each is a great approach to learning computers. > > My programming classes were a long, long time ago in a land far, far > away. My programming muscles, which were never truly developed, have > atrophied even so. That said, I want to learn this as we go. The > PROCESS of research and using net resources for a self-learning > adventure is almost as much of the goal as learning a programming > skill. > > That said, a good learning goal for my kid would be to create a > spelling tutor for his little brother. My (simple) vision would be: > > 1. an input file of this week's word list > 2. use a free text-to-speech engine to call out one word at a time > 3. in turn, monitor each key press as a particular word is being > typed, beeping on an incorrect keystroke and going to the next word if > correct > > I don't care if it takes a year or two to get to this level, I just > want a vehicle that will take us there. > > I told my son, who wants to learn how to compute probabilities, that we > have to start with some boring stuff so we can learn how to do the cool > stuff. Adding and subtracting aren't really fun, but figuring odds on > rolling dice IS fun. Learning to program will be kind of like that. > He accepted that explantion. > > So, that said... In ~simplest~ terms for the stated goal -- Forth or > Python? > ...the goal is NOT the spelling tutor... it is learning how to use a > tool to solve a problem. I am asking which tool is more suited to an > otherwise arbitrary direction of "spelling tutor program." > > [NOTE: This is not a troll. I'm geting ready to bark up a tree and I > prefer to avoid the wrong one. I am cross-posting.] > > Thanks From martin.witte at gmail.com Sun Jun 19 18:13:20 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 19 Jun 2005 15:13:20 -0700 Subject: calling subclass constructor question In-Reply-To: References: Message-ID: <1119219199.994619.256710@o13g2000cwo.googlegroups.com> No. You will go into an infinite loop - at least I get there when I try someting like this: class Base: def __init__(self): Derived.__init__(self) print 'Base' class Derived(Base): def __init__(self): Base.__init__(self) print 'Derived' d = Derived() From newsgroups at jhrothjr.com Fri Jun 17 09:42:47 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 17 Jun 2005 07:42:47 -0600 Subject: utf8 and ftplib References: <11b3ftrea0k2e29@news.supernews.com> Message-ID: <11b5kqpf5ruttaa@news.supernews.com> "Richard Lewis" wrote in message news:mailman.568.1119001245.10512.python-list at python.org... > > On Thu, 16 Jun 2005 12:06:50 -0600, "John Roth" > said: >> "Richard Lewis" wrote in message >> news:mailman.540.1118935910.10512.python-list at python.org... >> > Hi there, >> > >> > I'm having a problem with unicode files and ftplib (using Python >> > 2.3.5). >> > >> > I've got this code: >> > >> > xml_source = codecs.open("foo.xml", 'w+b', "utf8") >> > #xml_source = file("foo.xml", 'w+b') >> > >> > ftp.retrbinary("RETR foo.xml", xml_source.write) >> > #ftp.retrlines("RETR foo.xml", xml_source.write) >> > >> >> It looks like there are at least two problems here. The major one >> is that you seem to have a misconception about utf-8 encoding. >> > Who doesn't? ;-) Lots of people. It's not difficult to understand, it just takes a bit of attention to the messy details. The basic concept is that Unicode is _always_ processed using a unicode string _in the program_. On disk or across the internet, it's _always_ stored in an encoded form, frequently but not always utf-8. A regular string _never_ stores raw unicode; it's always some encoding. When you read text data from the internet, it's _always_ in some encoding. If that encoding is one of the utf- encodings, it needs to be converted to unicode to be processed, but it does not need to be changed at all to write it to disk. >> Whatever program you are using to read it has to then decode >> it from utf-8 into unicode. Failure to do this is what is causing >> the extra characters on output. >> > >> >> Amusingly, this would have worked: >> >> xml_source = codecs.EncodedFile("foo.xml", "utf-8", "utf-8") >> >> It is, of course, an expensive way of doing nothing, but >> it at least has the virtue of being good documentation. >> > OK, I've fiddled around a bit more but I still haven't managed to get it > to work. I get the fact that its not the FTP operation thats causing the > problem so it must be either the xml.minidom.parse() function (and > whatever sort of file I give that) or the way that I write my results to > output files after I've done my DOM processing. I'll post some more > detailed code: Please post _all_ of the relevant code. It wastes people's time when you post incomplete examples. The critical issue is frequently in the part that you didn't post. > > def open_file(file_name): > ftp = ftplib.FTP(self.host) > ftp.login(self.login, self.passwd) > > content_file = file(file_name, 'w+b') > ftp.retrbinary("RETR " + self.path, content_file.write) > ftp.quit() > content_file.close() > > ## Case 1: > #self.document = parse(file_name) > > ## Case 2: > #self.document = parse(codecs.open(file_name, 'r+b', "utf-8")) > > # Case 3: > content_file = codecs.open(file_name, 'r', "utf-8") > self.document = parse(codecs.EncodedFile(content_file, "utf-8", > "utf-8")) > content_file.close() > > In Case1 I get the incorrectly encoded characters. > > In Case 2 I get the exception: > "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe6' in > position 5208: ordinal not in range(128)" > when it calls the xml.minidom.parse() function. > > In Case 3 I get the exception: > "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe6' in > position 5208: ordinal not in range(128)" > when it calls the xml.minidom.parse() function. That's exactly what you should expect. In the first case, the file on disk is encoded as utf-8, and this is aparently what mini-dom is expecting. The documentation shows a simple read, it does not show any kind of encoding or decoding. > Anyway, later on in the program I create a *very* large unicode string > after doing some playing with the DOM tree. I then write this to a file > using: > html_file = codecs.open(file_name, "w+b", "utf8") > html_file.write(very_large_unicode_string) > > The problem could be here? That should work. The problem, as I said in the first post, is that whatever program you are using to render the file to screen or print is _not_ treating the file as utf-8 encoded. It either needs to be told that the file is in utf-8 encoding, or you need to get a better rendering program. Many renderers, including most renderers inside of programming tools like file inspectors and debuggers, assume that the encoding is latin-1 or windows-1252. This will throw up funny characters if you try to read a utf-8 (or any multi-byte encoded) file using them. One trick that sometimes works is to insure that the first character is the BOM (byte order mark, or unicode signature). Properly written Windows programs will use this as an encoding signature. Unixoid programs frequently won't, but that's arguably a violation of the Unicode standard. This is a single unicode character which is three characters in utf-8 encoding. John Roth > > Cheers, > Richard From littlejohn.75 at news.free.fr Mon Jun 13 09:43:50 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 13 Jun 2005 13:43:50 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: <42ad8d96$0$31709$636a15ce@news.free.fr> Le Mon, 13 Jun 2005 07:53:03 -0400, Roy Smith a ?crit : > Python let's you concentrate on the real universal > fundamentals of data structures, algorithms, and control flow without > getting bogged down in details. +1 QOTW From peter at engcorp.com Mon Jun 13 10:17:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Jun 2005 10:17:01 -0400 Subject: Controlling assignation In-Reply-To: References: Message-ID: Xavier D?coret wrote: > I would like to know if there is for python's classes an equivalent of > the operator= that can be overidden. > > Let's say I have > >>> a=A() > and I want to write > >>> a=5 > and I want this to change some internal value of a instead of making a > point to a new object (an int 5) > > In other word, I would like to be able to use a=5 instead of a.set(5) > > Is that possible? Not with simple names, such as "a". You can do it if you assign to an attribute of an object, such as a.b, by intercepting the assignment call via __setattr__ or a property. In Python, anyone reading your code would expect that "a=5" represents a rebinding of the name "a" to a new object, possibly destroying the old object, and if you did manage to subvert that you'd just be making your code unreadable, in the way that overuse of #define to change syntax in C can make C code (even more) unreadable. Please reconsider why you want to do that and find a more conventional approach, such as a.set(5). -Peter From trentm at ActiveState.com Tue Jun 14 11:46:42 2005 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 14 Jun 2005 08:46:42 -0700 Subject: windows directory In-Reply-To: References: Message-ID: <20050614154642.GA14602@ActiveState.com> [Peter Hansen wrote] > Richard Lewis wrote: > > If you want to know where a particular directory is (on a Windows > > 'drive') you could use: > > > > for drive_label in ["C", "D"]: > > if "Program Files" in os.listdir(drive_label + ":/"): return > > drive_label > > This would cause trouble in at least two cases that I've seen. One was > a multiboot machine that had Windows 2000 on D: and Windows XP on C:. > The other was a machine that had the Program Files folder copied, for > reasons I don't recall (and perhaps only temporarily), to the D: drive. And on non-English locales the folder name isn't actually "Program Files". And on some 64-bit architectures you can have "Program Files" and "Program Files (x86)". :) > Use one of the defined APIs for getting this information, not a hack > like this please. Amen. Trent -- Trent Mick TrentM at ActiveState.com From thomas at thomas-lotze.de Mon Jun 20 07:05:14 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Mon, 20 Jun 2005 13:05:14 +0200 Subject: OO approach to decision sequence? References: <1119079963.742936.56500@g49g2000cwa.googlegroups.com> Message-ID: Jordan Rastrick wrote: > Without knowing more about your problem, I think the most obvious OO > approach would be to write a seperate (simple) class for each of > node_type_1, node_type_2, etc. While I agree that this is the cleanest and usually simplest approach, it does have its drawbacks. I'm currently working on a project where I'd very much like to avoid writing a whole set of classes just for the purpose of avoiding a decision chain. For a PDF library, I need basic data types that are used in a PDF document. Such are integers, floats, strings, lists, dictionaries and a few. At some point they have to be written to a file, and at first I was tempted to create types like pdfint, pdffloat, pdfstr etc. which implement the respective file encoding either in a write method or directly in __str__. However, the whole point of the library is to allow working with the document's data. Beside manipulating existing (as in read from a PDF file) mutable objects this includes creating new objects of type pdffoo. And I realized it is very bothersome to have to say x = pdfint(5) instead of x = 5 everytime I deal with integers that would end up in the document. Similar for, e.g., adding to PDF integers: x = pdfint(y+z) instead of just x = y+z. The latter can be cured by touching all methods returning any pdffoo instances. No sane person would do this, however, and it would not eliminate any pdffoo(x) type conversions in the app code anyway. So I decided that in this case it is best to go without special types and use those provided by Python, and live with an ugly decision chain or two at defined places in the library. -- Thomas From deets at web.de Sun Jun 19 19:19:34 2005 From: deets at web.de (Diez B. Roggisch) Date: Mon, 20 Jun 2005 01:19:34 +0200 Subject: references/addrresses in imperative languages In-Reply-To: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: <3hmcs7FhrlmlU1@uni-berlin.de> > > In hindsight analysis, such language behavior forces the programer to > fuse mathematical or algorithmic ideas with implementation details. A > easy way to see this, is to ask yourself: how come in mathematics > there's no such thing as "addresses/pointers/references". Mathematics also has no notion of computational complexity - solving the TSP for a million cities is a matter of a single term in math - but in the real world, you'll have time for a cup of coffee or two waiting for that - including the time it takes you to travel to the restaurant at the end of the universe to drink it there. So even the more simple minded can see that math and programming aren't equivalent. But obviously that's too much to comprehend for you - as is everything regarding programming. How about stop using a computer, and stick to an abacus, a pencil and a piece of paper? A positive sideeffect would be that you wouldn't be able to post in NGs. But I somehow think you won't show us that courtesy. Diez From nid_oizo at yahoo.com_remove_the_ Thu Jun 23 13:22:29 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Thu, 23 Jun 2005 13:22:29 -0400 Subject: Reraise exception with modified stack In-Reply-To: <42badec0$1@nntp0.pdx.net> References: <20zue.74584$Kk4.909739@news20.bellglobal.com> <42badec0$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > How about dropping reraise and changing: > reraise(...) > to: > addinfo(...) > raise It doesn't work, or at least it doesn't do what I want. I want to keep the same exception stack to be able to identify the original error. I would like to avoid also writing in the caller something like sys.exc_info()[-1]. Regards, Nicolas From mwm at mired.org Thu Jun 9 17:49:22 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 09 Jun 2005 16:49:22 -0500 Subject: Start application & continue after app exits References: Message-ID: <86u0k75hgd.fsf@guru.mired.org> "guy lateur" writes: >>>Also note that this method of creating tempfiles is technically unsafe, >>>as it is theoretically possible that another process would create a file >>>of the same name in the same directory and then try to use it, resulting >>>in a race condition between the two processes. This is practically >>>unlikely, however, and I'm a pragmatist. > > I see what you mean, but wouldn't a call to open(fn, 'w') on a filename > that's in use (for reading or writing) result in an error condition or > something? I'm a noob, btw. Not necessarily - it depends on the OS. Unix is quite happy to let multiple processes read/write a file at the same time. FWIW, this also means that the methodology as outlined is insecure. Some other program can read the temporary file as it exists on the disk, thus disclosing it's contents to unauthorized readers. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dsa at unilestemg.br Wed Jun 8 06:15:03 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Wed, 8 Jun 2005 10:15:03 +0000 Subject: need some cgi help please In-Reply-To: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> References: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> Message-ID: <200506081015.03539.dsa@unilestemg.br> Hi ! Im a python begginer, but... > form = cgi.FieldStorage() > DataRecord = form['DataTime'].value > Customer = form['CustName'].value # should be automatically filled in > Can you try this ? print "Content-Type: text/html\n\n" print WorkingFile = open("/var/www/stretch/web_root/SidCrops/"+Customer+"/"+DataRecord,"r") for line in WorkingFile: print line WorkingFile.close() > here is the error: > WorkingFile undefined, builtin open = , Customer = > 'tenderloin', DataRecord = 'Tue Jun 7 20:13:35 2005.txt' > > IOError: [Errno 2] No such file or directory: > '/var/www/stretch/web_root/SidCrops/tenderloin/Tue Jun 7 20:13:35 > 2005.txt' > args = (2, 'No such file or directory') > errno = 2 > filename = '/var/www/stretch/web_root/SidCrops/tenderloin/Tue Jun > 7 20:13:35 2005.txt' > strerror = 'No such file or directory' This files '/var/www/stretch/web_root/SidCrops/tenderloin/Tue Jun 7 20:13:35 2005.txt' exists ? See the spaces in the file... -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From roy at panix.com Tue Jun 28 07:23:40 2005 From: roy at panix.com (Roy Smith) Date: Tue, 28 Jun 2005 07:23:40 -0400 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: Ivan Van Laningham wrote: > In which case, you should start with PostScript;-) I learned it by > plugging a glass tty into the serial port on one of the very first > AppleWriters and typing away. Same here. I had the RedBook and remember reading it and not quite believing it would work. Then I plugged in a terminal, typed in the first example in the book, and it blew my mind when a piece of paper came out with a square drawn on it. > Seriously, PostScript is a lot more fun to learn than Forth, and more > directly useful. Since the rewards are so immediate, a kid's attention > could be gained and kept pretty easily. There is something to be said for that. On the other hand, PostScript is not easy to debug. If you blow the stack, you mostly just get programs that mysteriously (and perhaps silently) don't work. It was frustrating enough for me; it'll probably just turn a kid off from the whole idea of programming. But then again, little kids seem to not have any problem programming VCRs, so maybe their brains just work differently :-) From tjreedy at udel.edu Sat Jun 11 13:59:26 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 11 Jun 2005 13:59:26 -0400 Subject: How to overcome automatic cyrillic-to-/hex convert References: Message-ID: wrote in message news:web-10021930 at dir.bg... > But when I enter some Bulgarian (actually cyrillic) text as a string, > it > seems that Python automatically converts it to '\x00..\x00 ' and once > converted that way I can't get it back into its original look. The only > way to get it right is using print : > >>>> a = '????' # 'Mam' in Bulgarian >>>> print a > '????' > > but > >>>> a > '\xcc\xe0\xec\xe0' There is a difference between internal data and external presentation. Print a calls str(a) to get a 'nice' presentation. Echoing 'a' calls repr(a) to get an invertible presentation (eval(repr(somestring)) == somestring). Internally, 'a' is the 4 bytes indicated by the repr presentation, not the 16 chars displayed in that presentation. There is no conversion until that presentation. I cannot comment about wxGrid and how to get it to display the nice version you want. Terry J. Reedy From roy at panix.com Wed Jun 22 15:39:30 2005 From: roy at panix.com (Roy Smith) Date: 22 Jun 2005 15:39:30 -0400 Subject: how to use more than 1 __init__ constructor in a class ? References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: scott wrote: >hi people, > >can someone tell me, how to use a class like that* (or "simulate" more >than 1 constructor) : >#-- >class myPointClass: > def __init__(self, x=0, y=0): > self.x = x > self.y = y > def __init__(self, x=0, y=0, z=0): > self.__init__(self, x, y) > self.z = z Python does not have the kind of polymorphism that C++ or Java has. There is only a single copy of each method (including __init__) for each class, but methods can take variable numbers of arguments, with default values. You probably want something like: def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z You can call this with 0, 1, or 2 arguments, i.e. any of the following are legal: MyClass() # x, y, and z all get defaulted to 0 MyClass(1) # x=1, y and z both default to 0 MyClass(1, 2) # x=1, y=2, z defaults to 0 MyClass(1, 2, 3) # x=1, y=2, z=3 Once you get the hang of it, you'll understand just how brain-dead C++ and Java really are :-) Take a look at http://docs.python.org/ref/function.html for more details. From carlos80 at gmail.com Wed Jun 1 14:42:18 2005 From: carlos80 at gmail.com (los) Date: 1 Jun 2005 11:42:18 -0700 Subject: Running a python program during idle time only In-Reply-To: References: <1116637560.499307.28700@o13g2000cwo.googlegroups.com> <1116869538.611233.264960@g14g2000cwa.googlegroups.com> <5j64x9gz09.fsf@idiom.com> <4296D2E3.8060605@hathawaymix.org> Message-ID: <1117651337.972718.59510@g44g2000cwa.googlegroups.com> I'm writting the code with the win32 module I found. The way I'm planning on attacking the problem after reading all the remarks is as follows: 1.) have the program run a full system index, and once it completes it turn the flag on a configuration file to true 2.) after this initial index, every time the program is started it will check this flag in the configuration file, and if it has had the full system index then the system will be kept up to date using the win32 modules, listening for events and changes made to the file system. I am basing my code pretty closely to what I found in the last example of this page http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html I'm aware that in case the program isn't running, all the changes made to the file system during that time won't be picked up next time the program starts. I haven't thought of a good way to solve this problem other than just do a full system index every once in a while to actually go through each directory updating and deleting records as necessary. Thanks once again for the posts! -los From wuwei23 at gmail.com Fri Jun 10 03:04:11 2005 From: wuwei23 at gmail.com (alex23) Date: 10 Jun 2005 00:04:11 -0700 Subject: how to operate the excel by python? References: Message-ID: <1118387051.811181.146710@o13g2000cwo.googlegroups.com> ???????? wrote: > i want to compare the content in excel,but i don't know whick module to use! > can you help me? I noticed a package on PyPi today that might be useful to you: http://www.python.org/pypi/xlrd/0.3a1 The homepage is a little brief, so I clipped their example from the README: import xlrd book = xlrd.open_workbook("myfile.xls") print "The number of worksheets is", book.nsheets print "Worksheet name(s):", book.sheet_names() sh = book.sheet_by_index(0) print sh.name, sh.nrows, sh.ncols print "Cell D30 is", sh.cell_value(rowx=29, colx=3) for rx in range(sh.nrows): print sh.row(rx) I haven't had cause to use it myself, however. -alex23 From newsgroups at jhrothjr.com Sat Jun 25 21:31:20 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 25 Jun 2005 19:31:20 -0600 Subject: Thoughts on Guido's ITC audio interview References: Message-ID: <11bs1bc5jotvg9c@news.supernews.com> "Dave Benjamin" wrote in message news:slrndbrse5.71d.ramen at lackingtalent.com... > Guido gave a good, long interview, available at IT Conversations, as was > recently announced by Dr. Dobb's Python-URL! The audio clips are available [snip] > - Java: the usual static vs. dynamic, static analysis vs. unit testing > arguments. Guido says that there's such a small amount of problems that > can be caught at compile time, and even the smallest amount of unit > testing would also catch these problems. "The blindness of that > [static] > position... escapes me." Three years ago, this was a viable arguement. Two years ago, it was beginning to show difficulties. Today anyone who makes it can be accused of having their head in the sand [1]. What's being ignored is that type information is useful for other things than compile type checking. The major case in point is the way IDEs such as IntelliJ and Eclipse use type information to do refactoring, code completion and eventually numerous other things. A Java programmer using IntelliJ or Eclipse can eliminate the advantage that Python used to have, and possibly even pull ahead. The only thing that is even vaguely similar in the Python community is Bycycle Repair Man, and, to be brutal about it, it sucks in comparison with what either Eclipse or IntelliJ can do. I agree with Guido's point later in the interview that type inference is the way to go, and that it's very difficult to retrofit it to an existing language. Difficult does not mean impossible though. The place to start is to go through the standard objects and make sure all return values make sense. I'll throw out one very simple example in the string library. The index() and find() methods, and their variants, suffer from a bad case of non-obviousness inherited from the C library. A very simple replacement would fix this. -------------------------------- findall([maxfind,] sub, [start, [end]]) findall returns a list (possibly a tuple) of the beginning index of each substring which matches sub. If there are no matches, an empty list is returned. At most maxfind indexes are returned. start and end have the same meaning as in the existing find and index methods. -------------------------------- This version works intuitively with if statements (an empty list is false), goes directly into for statements, can be implemented as an iterator, and is only less efficient by a constant (creation of the list) if the maxfind parameter is used. It never throws an exception (unless the parameter list has the wrong types). Its an example of a method that can be used cleanly with a type inferencer, while the index and find methods cannot. [snip] John Roth [1] I'm well aware that ostritches do not stick their heads in the sand to avoid looking at distressing things, such as advancing predators. It is, however, a useful metaphor. > > Cheers, > Dave From caseyhHAMMER_TIME at istar.ca Sun Jun 19 01:46:49 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Sun, 19 Jun 2005 05:46:49 GMT Subject: What platforms have Python Virtual Machines and what version(s) of Python do they support? Message-ID: <361ab1trhpgra9hig255r7arv68gfpe7lj@4ax.com> What platforms have Python Virtual Machines and what version(s) of Python do they support? In particular: Palm OS PocketPC What version of Python does Jython support? Does any machine running a JVM support Jython? Does it depend on the JVM version and if it's J2ME? Thank you for your time! -- Regards, Casey From python at rcn.com Fri Jun 3 02:34:52 2005 From: python at rcn.com (Raymond Hettinger) Date: 2 Jun 2005 23:34:52 -0700 Subject: decimal and trunkating References: Message-ID: <1117780492.437558.242370@g47g2000cwa.googlegroups.com> >> i want to trunkate 199.999 to 199.99 >> getcontext.prec = 2 isn't what i'm after either, all that does >> is E's the value. do i really have to use floats to do this? The precision is the total number of digits (i.e 199.99 has 5 digit precision). Either round to that precision level or use the quantize method to round to a fixed number of places after the decimal point: >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('199.999') Decimal("199.99") >>> Decimal('199.999').quantize(Decimal('0.01'), rounding=ROUND_DOWN) Decimal("199.99") Raymond Hettinger From vdavidster at gmail.com Mon Jun 27 01:40:12 2005 From: vdavidster at gmail.com (vdavidster at gmail.com) Date: 26 Jun 2005 22:40:12 -0700 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: <1119849232.609949.272220@g43g2000cwa.googlegroups.com> References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> Message-ID: <1119850812.545438.187700@g47g2000cwa.googlegroups.com> Hi, Thanks for your reply! A new thing learned.... Allow me to follow that up with another question: Let's say I have a result from a module called pyparsing: Results1 = ['abc', 'def'] Results2 = ['abc'] They are of the ParseResults type: >>> type(Results1) >>> type(Results2) I want to convert them into Python lists. list() will work fine on Results1, but on Results2, it will return: ['a', 'b', 'c'] Because 'abc' is a string. But I want it to return ['abc']. In short, my question is: how do I typecast an arbitrary object, whether a list-like object or a string, into a Python list without having Python split my strings into characters? Thanks very much for your help! David p.s. I know pyparsing has an asList() method, but let's just say I am unable to use it in my circumstances. From silasju at gmail.com Tue Jun 21 08:35:59 2005 From: silasju at gmail.com (silasju at gmail.com) Date: 21 Jun 2005 05:35:59 -0700 Subject: Python can do it for me? Message-ID: <1119357359.145942.139840@g43g2000cwa.googlegroups.com> Hello people! I think it is my first message here. Well, I would go to start a Delphi database program, but now my client want a program that runs in Linux. So I want to know your opinion: what best language/IDE I can use for my purposes? I need mainly: MySQL or Potsgree SQL ***remote connection***(it's the most important). GUI interface. Report generator. Barcode printing. I just remember that for now... Maybe PyGTK can do it for me? What do you think? What do you think? Thank you! Bye! From thorsten at thorstenkampe.de Fri Jun 3 05:50:30 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 3 Jun 2005 10:50:30 +0100 Subject: calling ksh script from python References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: <8lkhyu4ap59o$.84pfven4y3nv$.dlg@40tude.net> * Cameron Laird (2005-06-02 18:08 +0100) > In article , > Donn Cave wrote: >>Meanwhile, it might be worthwhile to reconsider the use >>of ksh here, if you have any choice in the matter. Ksh >>is fine for interactive use, but has some unfortunate >>flaws as a programming shell, and due to proprietary issues >>one commonly encounters an alternative implementation that's >>even worse. On most modern platforms, sh will have a pretty >>good programming feature set, and will be more reliable >>(especially if it isn't just ksh by another name.) > . > Infidel. While I sure feel that way about csh(1), it > surprises me you'd criticize ksh(1) so. 'Fact, 'mong > all the *sh-s, I *recommend* ksh for programming. May- > be the two of us see things differently. http://groups-beta.google.com/group/comp.unix.shell/msg/98578e8d95137a3c From aahz at pythoncraft.com Thu Jun 2 20:00:21 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2005 17:00:21 -0700 Subject: The need to put "self" in every method References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: In article , Peter Maas wrote: >Aahz schrieb: >>> >>>Because Python has no declarations there must be a different way to >>>indicate in which category an identifier falls. >[...] >> Any objection to swiping this for the FAQ? (Probably with some minor >> edits.) > >There is already a 'self' section (1.4.4) in the official Python FAQ. >Looks like this has been forgotten. Perhaps it would be helpful to >create a short version of the FAQ with the top most frequently asked >questions/stumbling blocks/annoyances titled "top 10 things you always >wanted to know about Python and didn't dare to ask" and post it weekly >in this newsgroup :) Ahhh... I looked in the Programming FAQ, but not the General FAQ. I still think that section could use some clarification based on Piet's wording, but it's less urgent. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The only problem with Microsoft is they just have no taste." --Steve Jobs From rkern at ucsd.edu Wed Jun 15 16:36:55 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 15 Jun 2005 13:36:55 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118697529.173406.134460@g44g2000cwa.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In , Robert Kern > wrote: > >>PyPK wrote: >> >>>One reason why I don't want to use PIL is it seems very slow for tiff >>>images of very large sizes(2400x4800). So I am looking for a better >>>tool than does the right job faster. >> >>This isn't fast enough? >> >>In [8]: %time img2 = Image.open('foo.tiff') >>CPU times: user 0.00 s, sys: 0.01 s, total: 0.01 s >>Wall time: 0.03 >> >>In [9]: img2.size >>Out[9]: (2400, 4800) > > It's fast enough to open the file and read the meta-data. The OP wants to > decode the actual pixels. Okay. In [12]: %time d = img.getdata() CPU times: user 0.31 s, sys: 1.43 s, total: 1.73 s Wall time: 6.19 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tim.golden at viacom-outdoor.co.uk Fri Jun 3 11:45:42 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 3 Jun 2005 16:45:42 +0100 Subject: tempfile.gettempdir() result on Windows Message-ID: <9A28C052FF32734DACB0A288A3533991EBB88D@vogbs009.gb.vo.local> | [Leo Breebaart] | | | | On MS Windows, I am trying to find out a good default location to | | save some temporary files. | | | | The tempfile module seemed to have exactly what I wanted: | | | | >>> import tempfile | | >>> tempfile.gettempdir() | | 'c:\\docume~1\\admini~1\\locals~1\\temp' | | >>> | | | | My problem (entirely cosmetic, but still) is that I also need to | | show this location to the users of my program, who I suspect | | would be much happier with a 'proper' Windows path than with this | | '~1' DOS malarkey. | | | | Does anybody know how I can obtain a temp directory in 'verbose' | | format (or somehow convert the gettempdir() result to that)? | [Tim Golden] | Have a look at win32api.GetLongPathName | (from the pywin32 extensions, in case it wasn't | obvious). So something like this: | | | import tempfile | import win32api | | print tempfile.gettempdir () | print win32api.GetLongPathName (tempfile.gettempdir ()) | | | | TJG And, incidentally, while you're there, the win32api.GetTempPath function does the same as tempfile.gettempdir so you don't even have to import the tempfile module if you don't want to. TJG (again) ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From lothar.sch at gmx.de Fri Jun 10 05:22:05 2005 From: lothar.sch at gmx.de (lothar.sch at gmx.de) Date: 10 Jun 2005 02:22:05 -0700 Subject: Python as CGI on IIS and Windows 2003 Server References: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> <1118338442.024062.24150@o13g2000cwo.googlegroups.com> <1118376702.458747.309710@g14g2000cwa.googlegroups.com> Message-ID: <1118395325.128822.178110@g44g2000cwa.googlegroups.com> jean-marc schrieb: > Some bits are coming back to me: the problems stemmed from adresses - > getting the root of IIS was different so accessing files didn't work > the same way. thanks for that. you are right, IIS versions are different. Wich kind of adresses do you mean, http-adresses or paths in file systems to root of IIS or to pythonscripts below IIS' root? Unfortunately I couldn't find a way to solve the problem. regards Lothar From could.net at gmail.com Tue Jun 28 02:16:01 2005 From: could.net at gmail.com (could ildg) Date: Tue, 28 Jun 2005 14:16:01 +0800 Subject: How to compress a folder and all of its sub directories and files into a zip file? Message-ID: <311b5ce105062723167e892833@mail.gmail.com> I want to compress a folder and all of its sub files including empty folders into a zip file. what's the pythonic way to do this? Thanks in advance. From matt at maudit.net Sun Jun 26 01:06:08 2005 From: matt at maudit.net (Matt Hollingsworth) Date: Sat, 25 Jun 2005 22:06:08 -0700 Subject: noob question Message-ID: <42BE37C0.3000306@maudit.net> Hello, Very new to python, so a noob question. When I've written stuff in JavaScript or MEL in the past, I've always adopted the variable naming convention of using a $ as the first character (no, I don't use perl, never have). Not possible in python. What are some good options that people commonly use so that they can easily and quickly identify variable with just a glance? When I was writing stuff in SoftImage XSI/JScript, many of the examples in the SDK used just a leading lower case o, but I'd like somethign that's more visible. I'm not a super advanced user and am just starting out in python (pretty much just working my way through Learning Python, at around page 160 or so). Seems like an _extremely_ elegent language that is very easy to read, so I suppose it's not really as much of an issue as it is with other languages. Still, I would like to see what other people do and what are some good ideas for this kind of thing. Thank you for any and all ideas. cheers, -Matt From mwm at mired.org Sun Jun 5 15:38:16 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 05 Jun 2005 14:38:16 -0500 Subject: GUI builders considered harmful (Was: anygui,anydb, any opinions?) References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> Message-ID: <86fyvwa91z.fsf_-_@guru.mired.org> "Thomas Bartkus" writes: > "Paul Rubin" wrote in message >> Are we talking about a drag-and-drop GUI builder? > I am! [...] > I happen to be one - and I *know* I'm not alone - who thinks that building > user interfaces is way too difficult and way too important. It is > particularly frustrating in that we do seem to be moving backwards in this > department. "What GUI builder should I use", or similar, is a common question on c.l.python. I'm a curmudgeon, and don't like GUI builders - so I avoid them. While normally that wouldn't cause me to encourage others to avoid GUI builders, I think they have a worse problem: they encourage the delivery of applications without flexible, robust user interfaces. In short, the help produce inferior applications. While this isn't strictly a python issue, c.l.python is where I run into it - so I'm bringing it up here. Now, I'm not an expert on GUIs, GUI toolkits, or GUI builders. I've used some of each, and draw my conclusions from that admittedly small sampling. Possibly there are other samples that don't have the problems I describe. Part of the point of posting this is to expose these thoughts to others, and find out what I've overlooked. I'll return to these points where appropriate. What the user deserves. I'm going to take a side trip into what constitutes a robust, flexible user interface - which is what I believe the user deserves. Please bear with me. By robust, I mean the user interface should adopt to the environment it's being run in. Windows that don't fit on the screen are simply unacceptable - but all to common if you use a very small screen resolution. By flexible, I man the user should be able to adjust the UI to suit their viewing conditions - the DPI on the screen, the viewing distance, and their possibly aging eyesight. I use two systems with graphical interfaces, and both are a bit out of the ordinary. You might even call them extreme. One is a 1600x1200 desktop on a 21" monitor viewed from about 18" away. The other is a 640x480 desktop on a 53" monitor viewed from about 10' away. Even those these are on opposite sides of "normal" users systems, they both suffer from the same problem - out of the box applications have UI elements that are unreadably small. The obvious solution would be for the system to detect all these environmental factors, and scale the applications accordingly. However, things like viewing distance and the quality of my eyesight are hard to detect automatically, and it would be a pain to have to enter all those things manually. Since the end result of all these is a single factor - a UI scale factor - a system wide knob to scale applications would seem to be the solution. Note that this is *not* an easy thing to do. Anyone who's tried scaling bit-mapped fonts will tell you you can't simply scale something and expect it to look good. Scalable fonts have "hints" and other goodies in them so they look good as you scale the fonts up/down. This may be why, but most windowing systems don't seem to do provide a global UI scale knob. X certainly doesn't. Windows has a limited capability to scale fonts system-wide, but it doesn't work very well. OSX seems to have a system-wide display DPI setting one can play with, but it's not clear how well that works. NeWS and NeXT could probably do this, but would seem to have a negligible to nonexistent user bases. rio seems capable, but the typical rio UI is ugly even by my admittedly low standards. Failing the single system-wide knob, a flexible application should have allow the user to scale the application with a single knob. This is hard to do with modern GUI toolkits. I do it by using text for imagery in the UI, and having a scaling factor that is applied to the font sizes. While I prefer text to graphics for UI elements, that's a rant for a different time. I'll concede that such an interface is probably unacceptable on a modern commercial application - users now expect graphics. But how many GUI toolkits let you use a scalable graphics format (SVG, PS, etc) for images in the UI? My predilections have kept me from looking closely, but I certainly don't recall seeing any in the GUI toolkits I've looked at. I claim it's obvious from this what's wrong with GUI builders. But I want to look at what I, as a developer, want from GUI development tools before going into details. What the developer wants. Ok, what I mean is what *I* want. But I don't think I'm that unusual, so I'm going to generalize to other developers as well. I'll point out what has to be different for this generalization to fail. First, I'm not a graphics designer. While I've studied page layout and typographical design, and read Tufte's books on design, I'm a *long* way from being a good graphics designer. I know even less about the field of human-computer interactions. Hopefully, a good GUI library will have had people on the development team who do know something about these fields. In this - the desirable - case, the library should have more knowledge about good UI design than I happen to posses. Given that, the more I can depend on the library to do for me - the less I have to specify - the more likely I am to produce a good UI with that library. Conversely, the more I have to specify in the GUI development process, the more likely I am to screw things up. I claim this statement should hold for most developers, unless they happen to be experts in the fields of graphics design or human-computer interactions. What's wrong with GUI builders. Ok, *now* we're ready to deal with GUI builders. The first, and most obvious, thing that GUI builders do is force the developer to specify an exact position - if not size - for the graphical elements of the UI. Better GUI libraries don't do that. Instead they let the developer specify the position as part of the overall structure, say as "the third button in the second toolbar from the top", or "one of two buttons in a toolbar running across the bottom of the window". This latter allows the knowledge of the library designers to dominate the design, hopefully producing a better UI than the you get from your typical software developer. The GUI builder might provide an advantage if it allowed the GUI design to be cleanly separated from the underlying code, so that a specialist in UI design could do the graphics design, and then the developer could come and add the underlying code. However, the GUI builders I've dealt with require specifying names for the various elements of the UI, which names should make sense in both environments. This would seem to defeat such a split design, but I've never tried it, so I can't say for sure. Further, look at the kind of interface the GUI builder gives you. The position of all the elements are nailed down. This makes it hard for the GUI to adopt to the extremes of display environments that you find in the wild. The GUI builders I've used made it hard, if not impossible, to build an application that can scale the GUI to meet the users needs. In other words, the GUI builder helps build applications without flexible, robust user interfaces that are inferior to what can be built using a GUI library. Typically, I don't find a GUI builder that much faster than a good GUI library. If I have to specify pixel positing for elements, the builder will be a win, but if not, then not. So I haven't examined all the GUI builders in depth. Maybe there's one out there that will let the application developer scale the GUI when the application is invoked, and will re-arrange elements of the GUI so they fit on the screen properly. If so, I'd love to hear about it. Thank you, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From me at privacy.net Fri Jun 10 13:51:24 2005 From: me at privacy.net (Dan Sommers) Date: 10 Jun 2005 13:51:24 -0400 Subject: Annoying behaviour of the != operator References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: On Fri, 10 Jun 2005 09:50:56 -0500, Rocco Moretti wrote: > Dan Sommers wrote: >> On Thu, 09 Jun 2005 15:50:42 +1200, >> Greg Ewing wrote: >> >>> Rocco Moretti wrote: >>> >>>> The main problem is that Python is trying to stick at least three >>>> different concepts onto the same set of operators: equivalence (are >>>> these two objects the same?), ordering (in a sorted list, which comes >>>> first?), and mathematical "size". >> >>>> This gives the wacky world where >>>> "[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't. >> Python inherits that wackiness directly from (often wacky) world of >> Mathematics. >> IMO, the true wackiness is that >> [ AssertionError, (vars, unicode), __name__, apply ].sort( ) >> "works," too. Python refusing to sort my list of complex numbers is a >> Good Thing. > The "wackyness" I refered to wasn't that a list of complex numbers isn't > sortable, but the inconsistent behaviour of list sorting. As you > mentioned, an arbitraty collection of objects in a list is sortable, but > as soon as you throw a complex number in there, you get an exception. Yes, I agree: it is inconsistent. > One way to handle that is to refuse to sort anything that doesn't have > a "natural" order. But as I understand it, Guido decided that being > able to sort arbitrary lists is a feature, not a bug. But you can't > sort ones with complex numbers in them, because you also want > '1+3j<3+1j' to raise an error. As George Sakkis noted, Guido has since recanted. Unfortunately, in this case, the time machine would have broken too much existing code. >> Four separate classes of __comparison__ methods in a language that >> doesn't (and can't and shouldn't) preclude or warn about rules >> regarding which methods "conflict" with which other methods? I do >> not claim to be an expert, but that doesn't seem very Pythonic to me. > What "conflict"? Where are you getting the doesn't/can't/shouldn't > prescription from? Perhaps "conflict" wasn't quite the right word. For example, if I define __ne__ and __equal__ and __lt__, then which method(s) should Python use if I later use a <= or a >= operator? "Doesn't" and "can't" (call me pessimistic) comes from all the issues and disagreements we're having in this thread, and "shouldn't" comes from the Zen: Explicit is better than implicit. In the face of ambiguity, refuse the temptation to guess. > Which method you use depends on what you want to achieve: > (Hypothetical Scheme) > Object Identity? - use 'is' > Mathematical Ordering? - use '__eq__' & friends > Object Equivalence? - use '__equiv__' > Arbitrary Ordering? (e.g. for list sorting) - use '__order__' So which method would python use when sorting a list that happens to consist only of numbers? or a list that contains mostly integers and a few complex numbers? > The only caveat is to define sensible defaults for the cases where one > fuction is not defined. But that shouldn't be too hard. At the risk of repeating myself: Explicit is better than implicit. In the face of ambiguity, refuse the temptation to guess. Also, as I noted in a previous discussion on an unrelated topic, it seems that we all have our own notions and limitations of expliciticity and impliciticity. > __eqiv__ -> __eq__ -> is > __order__ -> __lt__/__cmp__ >> AIUI, __cmp__ exists for backwards compatibility, and __eq__ and friends >> are flexible enough to cover any possible comparison scheme. > Except if you want the situation where "[1+2j, 3+4j].sort()" works, and > '1+3j < 3+1j' fails. I'm sticking with my position that both should fail, unless you *explicity* tell sort what to do (since for now, we all seem to agree that the other one should fail). If I have an application that thinks it has to sort a list of arbitrary objects, then I have to be clever enough to help. > I think the issue is you thinking along the lines of Mathematical > numbers, where the four different comparisons colapse to one. Object > identity? There is only one 'two' - heck, in pure mathematics, there > isn't even a 'float two'/'int two' difference. Equivalence *is* > mathematical equality, and the "arbitrary ordering" is easily defined > as "true" ordering. It's only when you break away from mathematics do > you see the divergance in behavior. IIRC, there was a discussion about overhauling of all of Python's numbers to make them act more like the mathematical entities that they represent rather than the Python objects that they are. The long/int "consolidation," better handling of integer division, and the Decimal class came out of that discussion. But that still leaves the issue of what to do with 1 < "foo" and "bar" > 2j and 3j < 4j. Regards, Dan -- Dan Sommers From swiftset at gmail.com Tue Jun 14 10:24:15 2005 From: swiftset at gmail.com (Alex Gittens) Date: Tue, 14 Jun 2005 09:24:15 -0500 Subject: Geometry library In-Reply-To: References: Message-ID: The Polygon library for Python: http://www.dezentral.de/warp.html?http://www.dezentral.de/soft/Polygon/index.html provides some support for dealing with polygons, which seems to be the only hard thing on this list. The rest you should be able to implement easily. Alex On 6/14/05, Cyril BAZIN wrote: > Hello, > > I am looking for a geometry library for Python. > I want to make some computations like: > -distance between vertex and polygon, vertex and polyline, vertex and > segment, etc > -if a point is inside a polygon, if a polyline intersect a polygon, etc -- ChapterZero: http://tangentspace.net/cz/ From tim.peters at gmail.com Thu Jun 2 00:33:45 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 2 Jun 2005 00:33:45 -0400 Subject: dictionaries and threads In-Reply-To: <20050601231009.396072.becbe514@goombah.com> References: <20050601231009.396072.becbe514@goombah.com> Message-ID: <1f7befae05060121332c0e7338@mail.gmail.com> [Gary Robinson] > I know the Global Interpreter Lock ensures that only one python thread > has access to the interpreter at a time, which prevents a lot of > situations where one thread might step on another's toes. Not really. The CPython implementation's C code relies on the GIL in many ways to provide mutual exclusion, but there's no such effect at the Python level: operations from multiple Python threads can get interleaved in any order consistent with sequential execution within each thread. The guarantee that the builtin datatypes provide "not to go insane" in the absence of application synchronization is really a separate matter, _aided_ in CPython by the GIL, but not guaranteed by the GIL alone. There's still an enormous amount of delicate fiddling in Python's C code to keep internals sane in the absence of application locking. > But I'd like to ask about a specific situation just to be sure I > understand things relative to some code I'm writing. > > I've got a dictionary which is accessed by several threads at the same > time (that is, to the extent that the GIL allows). The thing is, > however, no two threads will ever be accessing the same dictionary > items at the same time. In fact the thread's ID from thread.get_ident() > is the key to the dictionary; a thread only modifies items > corresponding to its own thread ID. A thread will be adding an item > with its ID when it's created, and deleting it before it exits, and > modifying the item's value in the meantime. > > As far as I can tell, if the Python bytecodes that cause dictionary > modifications are atomic, then there should be no problem. But I don't > know that they are because I haven't looked at the bytecodes. It's unclear what kind of problem you're concerned about. The kind of dict you described is widely used in Python apps; for example, it's at the heart of the implementation of threading.currentThread() in the standard library. That dicts promise not to go insane in the absence of locking isn't a GIL issue, even if multiple threads do modify d[k] simultaneously (in the absence of app locking, all such threads will eventually change d[k], but in an undefined order; if no two threads can muck with the same k, there's no problem at all). > Any feedback on this would be appreciated. For various reasons, we're > still using Python 2.3 for the time being. Best practice in 2.3 is to subclass threading.Thread for all threads you use. Then instead of mucking with a dict, you can just set/retrieve an attribute on the current Thread object. You can get the currently active Thread at any time via calling threading.currentThread(). From franz.steinhaeusler at gmx.at Tue Jun 14 03:45:37 2005 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Tue, 14 Jun 2005 09:45:37 +0200 Subject: wxpython wxlistctrl with combo References: <9ymre.1419$yM4.20011@twister2.libero.it> Message-ID: On Mon, 13 Jun 2005 21:05:09 GMT, "Fabio Pliger" wrote: >Hi all, >i'm working on a very large project using wx 2.5... On one frame i have a >wx.lib.mixins.listctrl widget, wich is a listctrl extended with the >possibility to edit the columns text entrys.... Anyone know if it's possible >(or if there's a widget...) to have also the possbility to have a comboBox >in the list (with the text edit entry)? The final result i need is a list >with 2 columns, one with the text entry editable, and the other with a >comboBox in it... Anyone know to do it? >TNX a lot... > >F.P. > Hm, I'm no expert, and it is probably better to ask in the wxpython-user mailing list. For what I saw: I think, you use TextEditMixin class. How about making a new class, (copying the TextEditMixin code), change the PreTextCtrl to a PreComboBox and maybe the navigation keys (TAB, ...)? -- Franz Steinhaeusler From ramen at lackingtalent.com Wed Jun 8 13:32:22 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 08 Jun 2005 10:32:22 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> Message-ID: Jordan Rastrick wrote: > Surely the != operator should, if no __ne__ method is present for > either object, check to see if an __eq__ method is defined, and if so, > return its negation? > > Actually, that brings me to a wider question - why does __ne__ exist at > all? Surely its completely inconsistent and unnessecary to have > seperate equals and not equals methods on an object? a != b should just > be a short way of writing not (a == b). The fact the two can give a > different answer seems to me to be utterly unintuitive and a massive > pitfall for beginners (such as myself). I agree that it's confusing. I didn't even understand this behavior myself until I went and looked it up: http://docs.python.org/ref/customization.html The rationale for this behavior is in PEP 207 -- Rich Comparisons: http://python.fyxm.net/peps/pep-0207.html Personally, I implement the __cmp__ method when I want my objects to be comparable, so I've never run into this problem. Dave From martin.witte at gmail.com Tue Jun 7 15:40:44 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 7 Jun 2005 12:40:44 -0700 Subject: different time tuple format References: Message-ID: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> In your case it is the EEST, as this is the DST timezone (see again: http://docs.python.org/lib/module-time.html) ** martin at ubuntu:~ $ python ** Python 2.4.1 (#2, Mar 30 2005, 21:51:10) ** [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 ** Type "help", "copyright", "credits" or "license" for more information. ** >>> import time ** >>> print time.tzname ** ('CET', 'CEST') ** >>> time.strptime("2005-06-07 15:07:12 CET", "%Y-%m-%d %H:%M:%S %Z") ** (2005, 6, 7, 15, 7, 12, 1, 158, 0) ** >>> time.strptime("2005-06-07 15:07:12 CEST", "%Y-%m-%d %H:%M:%S %Z") ** (2005, 6, 7, 15, 7, 12, 1, 158, 1) ** >>> From kent37 at tds.net Wed Jun 15 09:12:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Jun 2005 09:12:10 -0400 Subject: dynamic In-Reply-To: References: Message-ID: <42b028af$1_3@newspeer2.tds.net> Riccardo Galli wrote: > Hi all. > It's easier if I show an example first. > > Say I have > > class A(object): > def speak(self): print 'A!' > > class B(object): > def speak(self): print 'B!' > > I also have a factory function like this. > > def foo(kind,*args,**kwds): > if kind=='a': return A(*args,**kwds) > else: return B(*args,**kwds) > > I need foo to be a class, so that I could inherit from it and still use > it as a factory, so that I can do: > > Foo('a').speak() > Foo('b'.speak() > > class Final(Foo): > def __init__(self,kind,*args,**kwds): > super(Foo,self).__init__(kind,*args,*kwds) I'm not clear why you want to do this. Presumably you want to be able to say Final('a').speak() ?? How will this differ from Foo('a').speak() Why does Final need to subclass Foo? Can you use either of these syntaxes? Either one can be specialized in a subclass: Foo()('a').speak() # use Foo.__call__() as factory Foo.make('a') # Use classmethod as factory Kent From ejensen at visi.com Sat Jun 18 16:38:23 2005 From: ejensen at visi.com (Ed Jensen) Date: Sat, 18 Jun 2005 20:38:23 -0000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> Message-ID: <11b91hv96u75fb5@corp.supernews.com> Grant Edwards wrote: >> I've guessed that python is purely an interpreted language unless its >> compiled into another language (ie. it needs python installed in order >> to run programs). Is this correct? > > It's just like Java. It's compiled into bytecode and then the > bytecode is executed on a virtual machine. Keep in mind that all modern JVMs "just-in-time" compile Java bytecode to native code. It looks something like this: Java source -> Java bytecode -> Java virtual machine -> Native code So, in the end, users are typically running natively compiled code. (Warning: This is a simplification, but this description seems adequate for the OP.) Java typically outperforms Python by a very wide margin. From theller at python.net Fri Jun 3 12:21:40 2005 From: theller at python.net (Thomas Heller) Date: Fri, 03 Jun 2005 18:21:40 +0200 Subject: bdist_wininst to distribute a patched python References: Message-ID: <1x7jo1gr.fsf@python.net> mg writes: > Hi, > > Because of I have patched Python, I would like to create a Windows > installer containing my patched-Python. So, I try to use the option > 'bdist_wininst' on the setup.py file distributed by python.... it is > supported ? bdist_wininst can only be used to create distributions of Python modules and packages, not Python itself. > If yes, I have a problem : the run tell me that pyconfig.h does not > exist. What is the solution ? > > Thanks From leszczynscyATnospam.yahoo.com.nospam Wed Jun 8 23:16:28 2005 From: leszczynscyATnospam.yahoo.com.nospam (Andy Leszczynski) Date: Wed, 08 Jun 2005 22:16:28 -0500 Subject: Python Challenge web site Message-ID: <98OdnUvjYdn8LjrfRVn-qg@comcast.com> Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit http://www.pythonchallenge.com/ anybody get to the level 30? :-) From guettli at thomas-guettler.de Mon Jun 20 09:44:24 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 20 Jun 2005 15:44:24 +0200 Subject: import via pathname References: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> Message-ID: Am Mon, 20 Jun 2005 06:31:38 -0700 schrieb passion_to_be_free: > Okay, so in my li'l python script I'm importing a few 3rd party modules > that I have installed on my comp. I need to distribute this script to > several other people, but I won't have access to install the modules on > their comp's. I'm thinking I'll include these modules with my script > and deliver them as a bundle. When I write my script, is there a way to > declare the import statements and specify a relative path to where the > modules are located? Hi, You can change sys.path at runtime. Example: libdir=os.path.join(os.environ["HOME"], "mylibs") assert(os.path.exists(libdir)) sys.path.insert(0, libdir) import mylibrary # $HOME/mylib/mylibrary.py HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From peter at engcorp.com Fri Jun 10 13:03:41 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Jun 2005 13:03:41 -0400 Subject: match groups: optional groups not accessible In-Reply-To: <2LCdndztfdImHzTfRVn-pg@powergate.ca> References: <1118403410.852579.24710@z14g2000cwz.googlegroups.com> <2LCdndztfdImHzTfRVn-pg@powergate.ca> Message-ID: <5Pednd5pY72yVDTfRVn-3A@powergate.ca> Peter Hansen wrote: > david.reitter at gmail.com wrote: > >> Why does the following result in an IndexError? >> I try to match an optional group, and then access it via its group >> name. The group happens to not participate in the match, but is >> obviously defined in the pattern. >> >>>>> m = re.match('(?Pmaybe)?yes', "yes") > > Uh, don't you need to actually *group* the first "yes" part, with > parentheses, to make it a group? Otherwise you aren't going to be > treating it as other than text-between-groups-that-can-be-skipped. Oops... from Duncan's reply and a reread I can see I missed the point entirely... I obviously thought you were expecting the "yes" to be in a group too. Duh. -Peter From siyer at Princeton.EDU Fri Jun 10 15:55:29 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Fri, 10 Jun 2005 15:55:29 -0400 Subject: a question from a newcomer to this language Message-ID: <1ba3d9c32b101.42a9b7f1@Princeton.EDU> Thank you for your help. I will post the problem in more detail if I find that I cannot avoid using exec. Shankar ----- Original Message ----- From: Michael Chermside Date: Friday, June 10, 2005 3:49 pm Subject: RE: a question from a newcomer to this language > Shankar writes: > > Is there any way to convert a string into an instruction that > will be > > executed? > > Short answer: > Yes. The exec statement does what you want: > > >>> x = 3 > >>> y = 4 > >>> exec "z = x * y" > >>> print z > 12 > > HOWEVER... the long answer is that you almost certainly do NOT want > to use exec. Nearly everything that can be done with exec can be > done without it and the solution that does NOT use exec is faster, > more understandable, and has better security features. Often the > solution that does not use exec will be simpleer and more elegant > as well. > > If you look at a problem and are nearly certain that it needs to be > solved using exec, try posting it here... the people on this newsgroup > are very good at solving challenges like that. But try it yourself > first... you may learn something. > > -- Michael Chermside > > -- > http://mail.python.org/mailman/listinfo/python-list > From jeffelkins at earthlink.net Sat Jun 4 16:56:48 2005 From: jeffelkins at earthlink.net (Jeff Elkins) Date: Sat, 4 Jun 2005 16:56:48 -0400 Subject: Walking through a mysql db In-Reply-To: <200506040924.25574.jeffelkins@earthlink.net> References: <200506040924.25574.jeffelkins@earthlink.net> Message-ID: <200506041656.48222.jeffelkins@earthlink.net> Thanks for the replies! I went ahead and used the fetchall() approach and work with the array, writing changes back to the database. It's working fine. Jeff From gsakkis at rutgers.edu Mon Jun 13 02:44:25 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jun 2005 23:44:25 -0700 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: <1118645065.728744.74800@z14g2000cwz.googlegroups.com> "Andrea Griffini" wrote: > I think that if you don't understand memory, > addresses and allocation and deallocation, or > (roughly) how an hard disk works and what's > the difference between hard disks and RAM then > you're going to be a horrible programmer. > > There's no way you will remember what is O(n), > what O(1) and what is O(log(n)) among containers > unless you roughly understand how it works. There's a crucial distinction between these two scenarios though: the first one has to do with today's hardware and software limitations while the second one expresses fundamental, independent of technology, algorithmic properties. In the not-too-far-future, the difference between RAM and hard disks may be less important than today; hard disks may be fast enough for most purposes, or the storage policy may be mainly decided by the OS, the compiler, the runtime system or a library instead of the programmer (similarly to memory management being increasingly based on garbage collection). As programmers today don't have to know or care much about register allocation, future programmers may not have to care about whether something is stored in memory or in disk. OTOH, an algorithm or problem with exponential complexity will always be intractable for sufficiently large input, no matter how fast processors become. The bottom line is that there is both fundamental and contemporary knowledge, and although one needs to be good at both at any given time, it's useful to distinguish between them. George From hongli at gmail.com Sun Jun 19 22:11:38 2005 From: hongli at gmail.com (frost) Date: 19 Jun 2005 19:11:38 -0700 Subject: login website that using PHP Message-ID: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> Hi, I am trying to login a website that using PHP and javascript. This is what happend if you browse that website using IE, after you login, you can go anywhere without enter your name and password again, as long as you keep that IE open, but after you close that IE, then later on open that website in a new window, you need to login again. I guess some session is created as long as your original login window dose not close. How I can handle this in python? I want get some information from that website. But the login page is not what I want, how can I simulate regular IE browser? I mean after I login, I can get to other pages from it, but I find my programe can't go other place except the login page. Hope you could understand my question. Thank you very much! From hancock at anansispaceworks.com Sun Jun 26 06:59:18 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 26 Jun 2005 05:59:18 -0500 Subject: Favorite non-python language trick? In-Reply-To: <87r7eptn9w.fsf@wilson.rwth-aachen.de> References: <87r7eptn9w.fsf@wilson.rwth-aachen.de> Message-ID: <200506260559.18488.hancock@anansispaceworks.com> On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote: > Hall?chen! > However, then you must forbid a=b=1 for assigning to two variables > at the same time. Why? It's already handled as an exception in the syntax. In C, what you say makes sense, because "b=1" is an expression as well as an assignment. But I don't think Python reads it that way -- it just has code to recognize multiple assignment as a statement. I think I remember reading that in the Language Reference or something. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From no.spam Fri Jun 24 15:04:15 2005 From: no.spam (Christophe Delord) Date: Fri, 24 Jun 2005 21:04:15 +0200 Subject: what list comprehension can't References: <1119638714.090433.130520@z14g2000cwz.googlegroups.com> Message-ID: <20050624210415.48f5dace.no.spam@box> Hello, On 24 Jun 2005 11:45:14 -0700, ajikoe at gmail.com wrote: > Hello, > > Can we impose if then else into list comprehension ? > Like we do in lambda-map form: > > This code change None into 0 > L = [None, 12] > R = map(lambda x: (x==None and [0] or x)[0], L) # [0,12] > Do you mean: [(x==None and [0] or [x])[0] for x in L] or [{None:0}.get(x,x) for x in L] or [x or 0 for x in L] Well, the third solution doesn't exactly fit the specification but may be easier to read. Christophe From kveretennicov at gmail.com Sat Jun 25 11:41:58 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 25 Jun 2005 17:41:58 +0200 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <4660fe300506250841f51c143@mail.gmail.com> On 6/25/05, Mandus wrote: > It is really a consensus on this; that > removing map, filter, reduce is a good thing? It will render a whole lot > of my software unusable :( I think you'll be able to use "from __past__ import map, filter, reduce" or something like that :) They don't have to be built-in. - kv From cam.ac.uk at mh391.invalid Thu Jun 30 11:46:12 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 30 Jun 2005 16:46:12 +0100 Subject: How to compare two directories? In-Reply-To: References: Message-ID: could ildg wrote: > I found dircmp compare only the direct dirs and files, > and it will not do anything to the sub-directories. The documentation for dircmp.report_full_closure() disagrees with you. -- Michael Hoffman From desertgarden at netscape.com Sun Jun 12 11:40:09 2005 From: desertgarden at netscape.com (Brian) Date: Sun, 12 Jun 2005 15:40:09 GMT Subject: What language to manipulate text files In-Reply-To: References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: Hi Roose, Actually, it is a good thing because it allows those who know the Python language to be able to show the benefits and weaknesses of the language. Sure, the attitude here will be "Yes, it's a great language." Yet, at the same time, it also enables the poster to be able to see potential benefits to Python that he or she may not of been aware of. If we don't let others know about the benefits of Python, who will? Brian --- Roose wrote: > Why do people keep asking what language to use for certain things in the > Python newsgroup? Obviously the answer is going to biased. > > Not that it's a bad thing because I love Python, but it doesn't make sense > if you honestly want an objective opinion. > > R From hotdoc at despammed.com Tue Jun 28 11:36:26 2005 From: hotdoc at despammed.com (Andreas Heiss) Date: Tue, 28 Jun 2005 17:36:26 +0200 Subject: building python 2.4.1 References: Message-ID: John Abel wrote: > Andreas Heiss wrote: > >>Hi ! >>I am trying to build python 2.4.1 from source on a Linux system. >>Everything seems fine, but tkinter seems not to work. >>The file _tkinter.pyd is missing. >>How can tell configure to build all necessary components ? >> >>Thanks >>Andreas >> >> > It looks to like Tcl/Tk is not installed on your system. You will need > to have them installed for Tkinter to build. Actually, tk and tcl 8.4 are installed. However, there are no tcl.h and tk.h header files. I haven't ssen those files since Tcl/Tk8.0 From mwm at mired.org Thu Jun 30 20:55:20 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 30 Jun 2005 20:55:20 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> Message-ID: <864qbf8hvr.fsf@bhuda.mired.org> Ivan Van Laningham writes: > Mike Meyer wrote: >> xeys_00 at yahoo.com writes: >> As other have noted, C was never really used for everything. Unix >> tools were designed to connect together from the very beginning, which >> is what makes shell scripting so powerful. This was true before there >> was a C. Likewise, some things you need more control over the machine >> than you get in C - those are still done in assembler. These days, C >> compilers let you embed assembler statements in your C, so some of >> these things are done in such variants. > It really was used "for everything"; C compilers have *always* let you > include assembler, with the "asm" keyword. Unless you're talking about > the early days of DOS/Windows compilers, about which I know little, but > all *K&R* compilers had asm. Actually, I was thinking of pre-K&R Unix compilers. The v6 Unix compiler, and the photo7 compiler. I don't believe they had asm statements. If they did, it wasn't used in the v6 kernel. > And living with structs instead of classes was not nearly as much of a > pain in the butt as you make out; it was perfectly reasonable to include > methods within structs, by including a pointer to a function. X10 and > X11 showed just how object-oriented you could get with C, using > callbacks with required signatures, and specifying how Widgets were to > be written--contracts before there were contracts. Yeah, X is a good example of how to do OO programming in a non-OO language. The current BSD kernels do the same kind of things. But I'd say it was a bigger pain in the but than I made out to be. You wind up having to invoke the function through your data object, and then pass the data object in - sort of as an explicit "self". > It's true that OO languages are better, and languages like Python which > allow you to combine fairly low-level calls with an OO worldview make > life *vastly* easier, but C is still hugely flexible, highly adaptable, > and very powerful. For about 10 or 15 years there, knowing C was pretty > much a guarantee of a good job. That changed when C++ compilers became > common and good and not merely preprocessors that wrote really, really > ugly C. I still use C when I need more control/speed than I can get out of Python (or something modern). And for wrapping things to use in HLLs. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From dalke at dalkescientific.com Mon Jun 6 19:45:42 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 06 Jun 2005 23:45:42 GMT Subject: Creating file of size x References: <42a4cea6$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Is there any way to create a file with a specified size? Besides the simple def make_empty_file(filename, size): f = open(filename, "wb") f.write("\0" * size) f.close() ? If the file is large, try (after testing and fixing any bugs): def make_empty_file(filename, size, block = 32*1024): f = open(filename, "wb") written = 0 s = "\0" * block for i in range(size//block): f.write(s) remainder = size%block f.write(s[:remainder]) f.close() As Grant Edwards pointed out, you can do a seek(size-1) but I don't know if it's fully portable. Andrew dalke at dalkescientific.com From chad.hughes at pnl.gov Tue Jun 14 19:27:40 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Tue, 14 Jun 2005 16:27:40 -0700 Subject: Opening a drive folder from Python Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6177@pnlmse27.pnl.gov> I think you are talking about the following: from win32com.client import Dispatch path = raw_input('Type in a path: ') s=Dispatch('WScript.Shell') s.Run('Explorer %s'%path) Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of John Henry Sent: Tuesday, June 14, 2005 4:02 PM To: python-list at python.org Subject: Opening a drive folder from Python Can somebody please tell me how to pop open a drive folder from a Python script? Thanks. -- John -- http://mail.python.org/mailman/listinfo/python-list From Scott.Daniels at Acm.Org Sun Jun 26 13:58:48 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 26 Jun 2005 10:58:48 -0700 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: References: Message-ID: <42bee555$1@nntp0.pdx.net> Dave Benjamin wrote: > ... > I think Python's decision to use reference counting was an instance of > worse-is-better: at the time, reference counting was already known not to be > "the right thing", but it worked, and the implementation was simple. > Likewise with dynamic typing versus type inference. It seems that Guido > shares Alan Kay's viewpoint that type inference is really "the right thing", > but modern language technology is really not ready to make it mainstream, > whereas dynamic typing works today, and is arguably a better "worse" > solution than explicit/manifest static typing due to its verbosity. > > From the perspective of writing C extensions, Guido claims that the amount > of pain (regarding memory management) is about the same whether you're > extending a reference-counted language like CPython or a garbage collected > language like Java. Anyone with experience writing C extensions want to > comment on this? This is probably true for extensions written from scratch. From the point of view of connecting an existing block of code, Python made a great choice. If allocated memory doesn't need to move, and the garbage collector needn't get to _all_ the references in the system, the extension can make blocks of memory and include references to it in their own code, in their own format. They simply need to hold the objects in a Python-visible way. If the memory system needs to move allocated blocks, many data structures lose their efficiency in a haze of either adjusting and identifying references or indirection through piles of tables. One of the hard problems of talking "cross- language" has to do with "who is in charge of memory." Lots of languages are happy to allow interaction with another language as long as the other language is restricted to writing subroutines fitting the model of "the language really in charge." The fights are usually about memory allocation, non-standard flow of control, and intermediate data structures. C is easy to talk to because it was conceived as a "portable assembly language". Only straight assembler is easier to write language extensions in, because only assembly has less of a preconception of how memory is used and what code is and is not allowed to do. If you want to know pure hell, try to write a program that has significant code in both Smalltalk and Lisp (or even better, ML) in the same address space. They both want to be in charge, and you will quickly decide the best thing to do is put each language into its own process. > Type inferencing is especially difficult to add to a dynamically typed > language, and in general I think results are much better if you have type > inference from the very beginning (like ML and Haskell) rather than trying > to retrofit it later. Guido says that they've only been able to get it to > work reliably in Python with constants, which isn't very useful. Look at the Self language. That language has less of a surface concept of type than Python (classes are not defined). Still, Self was/is used as a platform to investigate type inferencing, code specialization, and native code generation. --Scott David Daniels Scott.Daniels at Acm.Org From grante at visi.com Sat Jun 18 09:31:58 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 13:31:58 -0000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: <11b88ier7jled7@corp.supernews.com> On 2005-06-18, Renato Ramonda wrote: >> And also, from what I know, the Java virtual machine is more >> popular (and installed on more computers). > > And it is also HUGE, so anyone NOT having it will think twice > before downloading it only for your app. Python on the other > hand is installed by default on all linux and OSX machines, > and on windows you can use py2exe and produce packages of > 2-3MBs (correct me if I'm wrong). with everything bundled. That's about right assuming you thrown in a few of the larger libraries like wxWidgets. A Win32 installer for a simple Python app with bundled Python .dll starts at about 750K. Python + py2exe + innoSetup rocks. People have no idea they're running a Python app. The app installs and runs just like any other. -- Grant Edwards grante Yow! I feel like a wet at parking meter on Darvon! visi.com From mfranklin1 at gatwick.westerngeco.slb.com Tue Jun 7 05:27:41 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 07 Jun 2005 10:27:41 +0100 Subject: SMTP help please In-Reply-To: <001201c56b3f$864f41e0$ccbefea9@twilliams> References: <000901c56b3e$b1be99d0$ccbefea9@twilliams> <001201c56b3f$864f41e0$ccbefea9@twilliams> Message-ID: Tim Williams wrote: > ----- Original Message ----- > From: "Tim Williams" > >>try: >> s.close() >>except >> pass > > > Typo!! > > That should be s.quit() not s.close() > > :) > > > > and perhaps put into a finally: Mart From lambacck at gmail.com Sun Jun 26 01:31:48 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Sun, 26 Jun 2005 01:31:48 -0400 Subject: Life of Python In-Reply-To: <42BD55BF.6000705@benjiyork.com> References: <42BD55BF.6000705@benjiyork.com> Message-ID: On the accessor function topic. Here is a good description of why you don't need accessors in python (among other things) written by the main PEAK(http://peak.telecommunity.com/) developer (Phillip J. Eby): http://dirtsimple.org/2004/12/python-is-not-java.html Some other useful articles in a similar vein: http://dirtsimple.org/2004/12/java-is-not-python-either.html http://naeblis.cx/rtomayko/2004/12/15/the-static-method-thing Phillip has written several very interesting python related articles on his blog (dirtsimple.org). Also PEAK and the spin off pyprotocols have a lot of very interesting tools for helping to manage large python projects. -Chris On 6/25/05, Benji York wrote: > Uwe Mayer wrote: > > con: If you are planning larger applications (for a reasonable value of > > "large") you have to discipline yourself to write well structured code. > > This is definitely true, no matter the language you use. > > > Then you will want to specify interfaces, > > If you're really interested in interfaces you might want to check out > Zope3. Even if you don't want to use the "web" parts, the component > architecture parts (interfaces, adapters, etc.) might be interesting to you. > > In a related vein is PEAK (http://peak.telecommunity.com/). It also has > some related ideas about interfaces, components, adapters, etc. > > > accessor functions with different read /write access, ... > > I don't quite follow here. Are you talking about using a method like > "thing.getX" instead of just accessing the attribute directly like > "thing.x"? If so, that kind of up-front design isn't necessary in Python. > > > Unless you have designed the software interactions completely bevorehand > > (which never works out) this is the only way to incorporate changes without > > refactoring your source all the time. > > Refactoring *is* the way you handle not being able to "[design] the > software interactions completely bevorehand". > -- > Benji York > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From axel at straschil.com Mon Jun 13 00:12:54 2005 From: axel at straschil.com (Axel Straschil) Date: 13 Jun 2005 04:12:54 GMT Subject: How to get/set class attributes in Python References: <42ac0c6d$0$10102$626a14ce@news.free.fr> Message-ID: Hello! > You can 'hide' you getsetters using a property attribute[1]: For me, the property attribute is a beast: class A(object): def getP(self): return 'A' p = property(getP) class A2(A): def getP(self): return 'A2' a = A() a2 = A2() print a.getP(), a2.getP() print a.p, a2.p So, property is instance-level super() tool ;-) Lg, AXEL. -- Gentoo? Debian? RedHat? SuSE? *BSD? Stop the distri-war, make little user! From marta_andrea at tele2.it Sat Jun 4 03:43:15 2005 From: marta_andrea at tele2.it (andrea valle) Date: Sat, 4 Jun 2005 09:43:15 +0200 Subject: executing a command Message-ID: Hi to all, I need to run a program from inside python (substantially, algorithmic batch processing). I'm on mac osx 10.3.8 with python 2.3 framework and macpython. Trying to use exec*, I checked references, Brueck & Tanner, and then grab this code from effbot: >>> program = "python" >>> def run(program, *args): os.execvp(program, (program,) + args) print "ok" >>> run("python", "/Users/apple/Desktop/prova.py") Traceback (most recent call last): File "", line 1, in -toplevel- run("python", "/Users/apple/Desktop/prova.py") File "", line 2, in run os.execvp(program, (program,) + args) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/os.py", line 336, in execvp _execvpe(file, args) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/os.py", line 374, in _execvpe func(fullname, *argrest) OSError: [Errno 45] Operation not supported This OSError seems to be consistend with all exec family. What does it mean and how to use exec? I also tried with. os.system. It works if I invoke python, but it fails (in a way I don't know) when I invoke other programs. For example: command = "python /Users/apple/Desktop/test.py" >>> os.system(command) 0 (test.py write a string in a file. It works) But with lilypond or with latex I have no output (and in fact it doesn't give 0 as result): >>> command = "lilypond /Users/apple/Desktop/test.ly" >>> os.system(command) 32512 >>> command = "latex /Users/apple/Desktop/test.tex" >>> os.system(command) 32512 Any help is much appreciated Thanks a lot -a- From tim.golden at viacom-outdoor.co.uk Wed Jun 29 08:55:51 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 13:55:51 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB951@vogbs009.gb.vo.local> [Greg Miller] | line 157 is in fact where the traceback says the failure is: | | File "autoStart.py", line 241, in test | File "wmib.pyc", line 157, in ? | File "win32com\client\__init__.pyc", line 73, in GetObject | File "win32com\client\__init__.pyc", line 88, in Moniker | com_error: (-2147221020, 'Invalid syntax', None, None ) OK; I'm now officially stumped on the WMI front. If the target machine can't cope with a GetObject ("winmgmts:") then I'm guessing you're not going to be able to do anything useful with WMI on it. Any luck with the GetFileVersionInfo? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From finite.automaton at gmail.com Wed Jun 1 19:02:34 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 1 Jun 2005 16:02:34 -0700 Subject: Function Serialization References: <1117627366.569543.227090@o13g2000cwo.googlegroups.com> <1117629023.949739.302650@g14g2000cwa.googlegroups.com> <1117660410.820998.205240@g43g2000cwa.googlegroups.com> Message-ID: <1117666954.054960.214230@g47g2000cwa.googlegroups.com> By default, shelve uses pickle to serialize objects. Pickle doesn't actually serialize functions... it just saves the function's name and name of its defining module, and upon loading attempts to find that function again. This is pretty much /never/ going to work the way you want it to if you're using exec. If you really want to save a function, you're going to have to save its source code and exec it upon reloading. I think the best way to achieve this would be to make your own wrapper class which defines a __call__ method and implements custom pickling routines (see the pickle documentation for how to do this). You could probably even make it into a decorator, but I wouldn't know about that since I'm stuck with Python 2.3. It would look something like this def f(): pass f = SerializableFunction(f) where SerializableFunction is defined as: class SerializableFunction(object): def __init__(self, function): self.function = function def __call__(self, *args, **keywords): return self.function(*args, **keywords) # custom pickle routines def __getnewargs__(self): ... def __getstate__(self): # extract function source ... def __setstate__(self): ... You can use the inspect module to get function source code, although AFAIK it's impossible to get source from functions defined in the interactive interpreter. From rkern at ucsd.edu Fri Jun 3 00:14:54 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 02 Jun 2005 21:14:54 -0700 Subject: Beginner question: Logs? In-Reply-To: <3g9sk7Fba0toU1@individual.net> References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> <3g9sk7Fba0toU1@individual.net> Message-ID: Greg Ewing wrote: > Peter Hansen wrote: > >>It's always a good idea, especially when answering a beginner's >>question, to add the caution that this form ("from xxx import *") has >>certain dangers** associated with it, and is widely considered poor >>style, and should really only rarely be used. > > Better still, don't even *mention* it to a beginner. > They don't need to know about it. At all. Really. Well, the OP's use is precisely why "from xxx import *" exists: the interactive prompt. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From Scott.Daniels at Acm.Org Thu Jun 30 11:54:31 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 30 Jun 2005 08:54:31 -0700 Subject: Inheriting from object In-Reply-To: References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> Message-ID: <42c40e16$1@nntp0.pdx.net> Sion Arrowsmith wrote: > ... And if you were to do so, surely: > class foo(object): > def __init__(self, *args, **kwargs): > super(foo, self).__init__(self) > > would be the preferred way to go? > Or, perhaps: class foo(object): def __init__(self, *args, **kwargs): super(foo, self).__init__(self, *args, **kwargs) ... --Scott David Daniels Scott.Daniels at Acm.Org From philippe at philippecmartin.com Sat Jun 25 15:38:15 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 19:38:15 GMT Subject: Excellent Site for Developers References: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> Message-ID: Sorry, limbs (plus I check in a dictionnary first!) Philippe C. Martin wrote: > limns From hancock at anansispaceworks.com Wed Jun 1 15:28:56 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Jun 2005 14:28:56 -0500 Subject: The need to put "self" in every method In-Reply-To: References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: <200506011428.56800.hancock@anansispaceworks.com> On Tuesday 31 May 2005 11:52 am, Roy Smith wrote: > Note that in languages like C++ where using "this->" is optional, > people invent their own conventions for keeping local and instance > variables distinct, like prepending m_ to member names (except that > different people do it different ways, so it's more confusing). I would call this the "real" answer. I am aesthetically annoyed by code like: Post.postRead() or even Post.read_post() The dot is there for a reason -- it qualifies the variable with the class it applies to. What is the point of qualifying it AGAIN in the method name? When I notice this in my own code, I reduce such stuff to Post.read() IMHO, redundancy interferes with clarity, and one should use the semantics of the language to describe the semantics of the program --- that should make it easier for both Humans and machines to understand the relationships in the code. Using "self" is just like this, as indicated above: it replaces weird naming conventions with a much more general one. I've only ever replaced "self" with a different name once, and that was when I was writing a vector math module -- I wanted a more compact symbolic style, so I used "a": def __add__(a,b): return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z)) or something like that. I still have twinges of guilt about it, though, and I had to write a long note in the comments, apologizing and rationalizing a lot. ;-) I must say though, that as a newbie, I found this a lot easier to get my head around than learning all the implicit variables that Javascript introduces (e.g. "this", "prototype", etc). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From desertgarden at netscape.com Mon Jun 20 16:21:14 2005 From: desertgarden at netscape.com (Brian) Date: Mon, 20 Jun 2005 20:21:14 GMT Subject: Python choice of database In-Reply-To: References: Message-ID: <_yFte.7140$jX6.4729@newsread2.news.pas.earthlink.net> I am really surprised that someone hasn't mentioned Gadfly yet. It is a quick, free, relational database written directly for Python itself. http://gadfly.sourceforge.net/ Brian --- Philippe C. Martin wrote: > Hi, > > I am looking for a stand-alone (not client/server) database solution for > Python. > > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K > > > As I start with Python objects, I thought of using shelve, but looking at > the restrictions (record size + potential collisions) I feel I should study > my options a bit further before I get started. > > > Regards, > > Philippe > From bronger at physik.rwth-aachen.de Sat Jun 4 03:51:35 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sat, 04 Jun 2005 09:51:35 +0200 Subject: Removing a warnings filter? References: <87ekbj8pz6.fsf@wilson.rwth-aachen.de> Message-ID: <87y89qpnjs.fsf@wilson.rwth-aachen.de> Hall?chen! Dave Benjamin writes: > Torsten Bronger wrote: > >> When I add a warning filter with warnings.filterwarnings, how can >> I get rid of it? I've read about resetwarnings(), but it removes >> all filters, even those that I didn't install in a certain >> function. > > I have never used this module, but judging by a quick glance of > the source to "warnings.py", it appears that warning filters are > added to a list called "warnings.filters". Thank you, I'll use it in my program. However, I don't like it very much, because warnings.filters isn't mentioned in the reference, and in other languages that I've used, internal features are not guaranteed to work across different versions. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From gene.tani at gmail.com Wed Jun 22 02:27:55 2005 From: gene.tani at gmail.com (gene tani) Date: 21 Jun 2005 23:27:55 -0700 Subject: tree functions daily exercise: Table In-Reply-To: References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119392216.168822.314580@f14g2000cwb.googlegroups.com> Message-ID: <1119421675.833015.57370@g44g2000cwa.googlegroups.com> Dear Mr. Jones: Our team of 3,972 expert testers judged the output of your troll-spewing neural net virtually indistinguishable from the original. Given this, I am please to announce that our firm is willing to discuss arrangements for an exclusive license that you would likely find financially compelling. Please do not post the code on sourcefurge or whatever you call that open source thing until you speak with us. S. Ballmer From grante at visi.com Fri Jun 24 14:26:51 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 24 Jun 2005 18:26:51 -0000 Subject: Newbie question: how to keep a socket listening? References: <1119637288.536579.249340@z14g2000cwz.googlegroups.com> Message-ID: <11bok3btkedg151@corp.supernews.com> On 2005-06-24, ncf wrote: > I think your problem /may/ be in the following line of code: > sa.listen(1) > > I believe what's happening is that the listen() creates a decremental > counter of the number of connections to accept. Once it decrements to > 0, it won't accept any more connections. (I'm not at all sure, but that > sounds like what it's doing.) The "1" tells the stack how many pending connections are allowed. -- Grant Edwards grante Yow! I FORGOT to do the at DISHES!! visi.com From Xavier.Decoret at imag.fr Wed Jun 8 08:44:47 2005 From: Xavier.Decoret at imag.fr (=?ISO-8859-1?Q?Xavier_D=E9coret?=) Date: Wed, 08 Jun 2005 14:44:47 +0200 Subject: Knowing the signature of a function In-Reply-To: <42a6e5cc$1_3@newspeer2.tds.net> References: <42a6e5cc$1_3@newspeer2.tds.net> Message-ID: Kent Johnson a ?crit : > Xavier D?coret wrote: > >> Hello, >> >> I have the following code: >> >> def foo(x,y): >> pass >> >> How can I query the function object foo to know the number of >> parameters it expects. I can find it is a function using callable(f), >> I can find some information (listed by dir(foo)) such as the name of >> the function,etc.. but nowhere I can find the number of arguments. >> >> I would like to know wether the function expects one or zero arguments. > > > foo.func_code.co_argcount gives the count of named args. > len(foo.func_code.co_varnames) gives the total number of arguments > including *args and **kwds args. inspect.getargspec() might also be > helpful. > > Kent Thanks. Now I have the following issue: what if foo is not a function but a callable? inspect.getargspec raises an exception. I have to do something like: import inspect def countargs(f): if callable(f): if inspect.isfunction(f): return len(inspect.getargspec(f)[0]) return len(inspect.getargspec(f.__call__)[0])-1 raise ValueError class foo: def __call__(self,a,b): pass def bar(x): pass print countargs(foo) print countargs(bar) Is there any better way? From ivanlan at pauahtun.org Tue Jun 28 19:43:02 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Tue, 28 Jun 2005 17:43:02 -0600 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <863br2nlh9.fsf@bhuda.mired.org> Message-ID: <42C1E086.12A365E1@pauahtun.org> Hi All-- Mike Meyer wrote: > > Since the user is the one bound with B&D languages, they are clearly > tops. Which makes Python a bottom. > Well, we certainly hope Python has a safe word. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From jepler at unpythonic.net Thu Jun 2 14:07:25 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Jun 2005 13:07:25 -0500 Subject: Easy way to detect hard drives and partitions in Linux In-Reply-To: <1117730941.946683.88840@g44g2000cwa.googlegroups.com> References: <1117730941.946683.88840@g44g2000cwa.googlegroups.com> Message-ID: <20050602180724.GE19350@unpythonic.net> You're not going to find a single portable "unix" way of doing this. The format of /etc/fstab and /etc/mtab are pretty portable, but they only list mountable/mounted partitions, not all partitions. In addition to the linux possibilities mentioned in another reply, there is also /proc/partitions. Finally, if you only want to recognize FDISK.EXE-type partitions (used by many types of Linux, though that seems to be changing in Fedora Core 4), it shouldn't be hard to write a Python program to read the partition table directly from the disk. The details will be readily available online. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From skromta at gmail.com Tue Jun 14 08:41:51 2005 From: skromta at gmail.com (Kalle Anke) Date: Tue, 14 Jun 2005 14:41:51 +0200 Subject: Hopefully simple regular expression question References: <1118746918.581184.5470@g49g2000cwa.googlegroups.com> Message-ID: <0001HW.BED49D2F002CDEB2F0305550@news.individual.de> On Tue, 14 Jun 2005 13:01:58 +0200, peterbe at gmail.com wrote (in article <1118746918.581184.5470 at g49g2000cwa.googlegroups.com>): > How do I modify my regular expression to match on expressions as well > as just single words?? import re def createStandaloneWordRegex(word): """ return a regular expression that can find 'peter' only if it's written alone (next to space, start of string, end of string, comma, etc) but not if inside another word like peterbe """ return re.compile(r'\b' + word + r'\b', re.I) def test_createStandaloneWordRegex(): def T(word, text): print createStandaloneWordRegex(word).findall(text) T("peter", "So Peter Bengtsson wrote this") T("peter", "peter") T("peter bengtsson", "So Peter Bengtsson wrote this") test_createStandaloneWordRegex() Works? From vincent at visualtrans.de Sun Jun 12 12:16:28 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 12 Jun 2005 18:16:28 +0200 Subject: How to get/set class attributes in Python References: <42ac0c6d$0$10102$626a14ce@news.free.fr> <42AC3A13.9020503@lexicon.net> <87zmtvh8r3.fsf@hector.domek> Message-ID: "Peter Dembinski" schrieb im Newsbeitrag news:87zmtvh8r3.fsf at hector.domek... | Kalle Anke writes: | | [snap] | | >> sys.maxint = -12345 | > | > I don't really understand what you're meaning. | | He meant None = 1 :> I'm sure you know that has become a no-no in Python 2.4+ ;) >>> None = 1 SyntaxError: assignment to None >>> -- Vincent Wehren From thomasbartkus at comcast.net Thu Jun 23 10:13:58 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 23 Jun 2005 09:13:58 -0500 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> <3tiue.27$jv6.1568@news.uswest.net> Message-ID: "Magnus Lycka" wrote in message news:d9dopt$8ih$1 at wake.carmen.se... > Cameron Laird wrote: > > OK, I'm with you part of the way. Typical "Access" developers > > are *always* involved with DLL hell, right? You're surely not > > saying that Python worsens that frustration, are you? > > I think Dan was commenting on flaws in Microsoft's products, > not in Python. As I understand it, he was suggesting to use > something else than Access with Python, not something else > than Python with Access. The O.P. wanted a database for his > Python app, and Thomas Bartkus suggested Access. Not exactly! I suggested the built in Microsoft DAO or ADO database libraries which he could use without need to distribute with his app. The Access application is simply another client app that sits on top of DAO/ADO and would be quite unnecessary here. Any Python/DB application you wished to distribute for MS Windows would do best talk to the ADO library directly - end of distribution problems. * Everyone with WindowsXP already has the DAO and ADO libraries. * Not everyone has (or needs) MS Access which one would have to pay for and could not distribute freely with ones Python app. * Python has no need of MS Access in order to create, maintain, and manipulate databases using Microsofts built in ADO database facilities - although a developer *might* find Access useful as an inspection/debugging tool on his own workstation. All of which used to confuse the hell out of me :-) Thomas Bartkus From flupke at nonexistingdomain.com Thu Jun 2 17:33:27 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 02 Jun 2005 21:33:27 GMT Subject: (OT) lincense protection generator Message-ID: I'm going to be distributing a program based on wxPython & python in a few weeks time. The code will run on windows machines. Because i don't want the users to move the folders around or mess with the program or taking copies home to fiddle with it, i was thinking of a way to check when the program starts that it's still on the same directory and same computer. That way i at least avoid unnecessary phone calls asking me for help when they messed the program up. I'm thinking of a function that will generate such a code and put it in a file. Then when the program starts it checks this file and checks the code in there with a code that it generates at that time again based for instance on the current directory and other components unique to that computer. It could be a long string (but what info?) and then take a hash from it and store the hash value. How could i construct such a code without being a total pain? For instance i don't want to check for anything hardware related because then my program would fail to work once the people change their hardware. Anyway, it doesn't need to be waterproof. (not possible anyway) Any ideas? Regards, Benedict From xah at xahlee.org Tue Jun 21 17:37:53 2005 From: xah at xahlee.org (Xah Lee) Date: 21 Jun 2005 14:37:53 -0700 Subject: tree functions daily exercise: Table In-Reply-To: References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119357221.467207.149480@f14g2000cwb.googlegroups.com> Message-ID: <1119389873.409227.225680@f14g2000cwb.googlegroups.com> oops, another error. The example should be: Table(f,[1,2,1],[2,6,2]) returns [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]] > Wouldn't it be more sensible just to take the iterators directly as > arguments, so for this example you would do: > > Table(f, range(1,3), range(2,7,2)) well yes... but this was emulation of Mathematica functions. (Disclaimer: Mathematica is a trademark of Wolfram Research Inc, who is not affliated with this project) What you suggested is a function called Outer in Mathematica. The Table function is in a sense multi-dimentional version of Range, so they share syntax form. Xah xah at xahlee.org ? http://xahlee.org/ Duncan Booth wrote: > Xah Lee wrote: > > > '''Table(f,[iStart,iEnd,iStep]) returns a list of f applied to the > > range range(iStart,iEnd,iStep). Example: Table(f,[3,10,2]) returns > > [f(3),f(5),f(7),f(9)] Table(f,[iStart,iEnd,iStep], > > [jStart,jEnd,jStep], ...) returns a nested list of f(i,j,...) applied > > thru the iterators. Example: Table(f,[1,3,1],[2,6,2]) returns > > [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]]''' > > How does it know when to skip the end value (i.e. act as for the rest of > Python) and when to include it? Or did you mean: > > Table(f,[1,3,1],[2,7,2]) returns > [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]] > > Wouldn't it be more sensible just to take the iterators directly as > arguments, so for this example you would do: > > Table(f, range(1,3), range(2,7,2)) > > That way you have more flexibility (e.g. to do out-of-order ranges such as > [1,3,2,0,4]), and the code for Table is much simpler since it just has to > manipulate the lists it was given. From twic at urchin.earth.li Mon Jun 13 07:42:23 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 13 Jun 2005 12:42:23 +0100 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: On Sun, 12 Jun 2005, Roy Smith wrote: > Andrea Griffini wrote: > >> I think that for a programmer skipping the understanding of the >> implementation is just impossible: if you don't understand how a >> computer works you're going to write pretty silly programs. Note that >> I'm not saying that one should understand every possible implementation >> down to the bit (that's of course nonsense), but there should be no >> room for "magic" in a computer for a professional programmer. > > How far down do you have to go? What makes bytes of memory, data busses, > and CPUs the right level of abstraction? > > Why shouldn't first-year CS students study "how a computer works" at the > level of individual logic gates? After all, if you don't know how gates > work, things like address bus decoders, ALUs, register files, and the like > are all just magic (which you claim there is no room for). > > Digging down a little deeper, a NAND gate is magic if you don't know how a > transistor works or can't do basic circuit analysis. And transistors are > magic until you dig down to the truly magical stuff that's going on with > charge carriers and electric fields inside a semiconductor junction. > That's about where my brain starts to hurt, but it's also where the quantum > mechanics are just getting warmed up. It's all true - i wouldn't be the shit-hot programmer i am today if i hadn't done that A-level physics project on semiconductors. tom -- Think logical, act incremental From skip at pobox.com Thu Jun 9 19:12:35 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 9 Jun 2005 18:12:35 -0500 Subject: PEP 304 (was: Re: Any way to not create .pyc files?) In-Reply-To: References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <17064.52451.532283.312701@montanaro.dyndns.org> >> PEP 304 would have helped, but it appears to be deceased. Just resting... FWIW, I reapplied it to my cvs sandbox the other day and plan to at least generate a new patch from that. It's pretty much done, except... Once upon a time, someone identified some problems for Windows with its multiple-root file system. I've tried a couple times to dig it up, but have been unsuccessful. If anyone can find it (or was the author, better yet), let me know. At the very least I'd like to amend the PEP. Ideally, I'd like to solve the problem and get PEP 304 going again. Skip From sys1rak at ups.com Fri Jun 3 07:18:32 2005 From: sys1rak at ups.com (Kornfeld Rick (sys1rak)) Date: Fri, 3 Jun 2005 07:18:32 -0400 Subject: SFTP Message-ID: <5C1296A3D8CC9C4EB1EB9DDC08D746F6060D7FBC@njrarsvr039a.us.ups.com> Good Morning I have scoured the internet looking for an Python SFTP API. So far, I have been unable to find a suitable answer. Our needs are pretty basic. FTP & TELNET are being removed from our environment and I need to utilize SFTP for file transfers. As is probably said often, I am new to Python (love it) and need a solution that provides adequate examples and documentation. I am hoping for an open source answer, however, I am not ruling out having to purchase something. Can anyone shed some light on this for me ? Best Regards, ___________________________________ Rick Kornfeld -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Sun Jun 5 10:53:45 2005 From: jjl at pobox.com (John J. Lee) Date: 05 Jun 2005 14:53:45 +0000 Subject: method = Klass.othermethod considered PITA References: <87oeallp44.fsf@pobox.com> Message-ID: <87ekbglurq.fsf@pobox.com> Steven Bethard writes: > John J. Lee wrote: > > It seems nice to do this > > class Klass: > > def _makeLoudNoise(self, *blah): > > ... > > woof = _makeLoudNoise > > Out of curiosity, why do you want to do this? I don't. It's just a habit I picked up from the standard library. > > 1. In derived classes, inheritance doesn't work right: > > > >>>>class A: > > ... def foo(s):print 'foo' > > ... bar = foo > > ... > >>>>class B(A): > > ... def foo(s):print 'moo' > > ... > >>>>b = B() > >>>>b.bar() > > foo > > Depends on what you mean by "work right". It does do what you asked > it to do. Well, gee, I guess so! By "right" simply meant "according to the intent of the people who tend to write such code" (and I do hope you're not going to get over-literal about *that* non-clinically-precise statement). It's obviously a tacit intent, though, hence the problem. > You asked class A to store the "foo" object under the name > "bar". When you create an instance of B, and ask for the "bar" > attribute, it isn't found in class B, so Python looks to the parent > class. The parent class, A, does have an object named "bar", so > Python returns that. And that object is the same object that you > asked be named bar, namely the "foo" function. Yes. My point was simply that the simplicity of writing method2 = method1 in a class body is an attractive nuisance. > If you want "bar" to be a function that *calls* the "foo" function, > declare it as such: > > py> class A(object): > ... def foo(self): > ... print 'foo' > ... def bar(self): > ... return self.foo() > ... > py> class B(A): > ... def foo(self): > ... print 'moo' > ... > py> B().bar() > moo It was my intent to push people to do that instead, yes. > > 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do > > this. > > In Python 2.4: > > py> class A(object): > ... def foo(self): > ... print 'foo' > ... bar = foo > ... > py> import pickle > py> pickle.loads(pickle.dumps(A)).bar > > py> pickle.loads(pickle.dumps(A())).bar() > foo I meant class instances. John From Aiwass333 at gmail.com Tue Jun 14 20:40:35 2005 From: Aiwass333 at gmail.com (RunLevelZero) Date: 14 Jun 2005 17:40:35 -0700 Subject: pygtk question Message-ID: <1118796035.754511.224780@o13g2000cwo.googlegroups.com> Hopefully someone can help me out here. It's probably super simple but how do you select multiple items in a treeview? I have gtk.SELECTION_MULTIPLE set but of course that was enough. I have tried catching the ctrl button press but still nothing. Perhaps there is a better place to ask but I thought I would give this a shot first. TIA. From oren.tirosh at gmail.com Fri Jun 17 04:20:23 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 17 Jun 2005 01:20:23 -0700 Subject: 1980's Home Computer-style Package. In-Reply-To: References: Message-ID: <1118996423.556760.37280@g44g2000cwa.googlegroups.com> http://tothink.com/python/progman/ This module implements BASIC-like NEW, LOAD, RUN (sorry, no SAVE...). Oren From freddie+usenet at madcowdisease.org Thu Jun 16 10:12:30 2005 From: freddie+usenet at madcowdisease.org (Freddie) Date: Thu, 16 Jun 2005 23:42:30 +0930 Subject: ANN: GallerPy 0.7.0 Message-ID: <42b188d4$0$8141$9a6e19ea@unlimited.newshosting.com> GallerPy is a fairly basic dynamic web gallery written in Python and uses the Python Imaging Library. It is licensed under the terms of the BSD License. Features include: * Fluid CSS layout * SCGI support * Other exciting stuff GallerPy is available for download from the MadCowDisease web site: http://www.madcowdisease.org/mcd/GallerPy Or via Subversion: svn://svn.madcowdisease.org/GallerPy/tags/0.7.0 svn://svn.madcowdisease.org/GallerPy/trunk (occasionally broken) Changes in this release: * Add 'show_header' and 'show_footer' options to control the output of HTML header and footer information. * Add 'root_local' and 'root_web' options to allow easier embedding of GallerPy into other applications. * Include .BMP and .JPE in the list of recognised extensions. * Include '.svn' in the default hide_dirs listing. * Strip empty "" tags from output. * Change how we do top padding of thumbnail images so it works in that nasty cow, Internet Explorer. RAGE. * Change the default header_file from index.txt to header.txt, since index.txt is a bit confusing. * Fix ShowError() not working properly if GallerPy is running embedded in something else. From tmj at jLUNCHEON_MEATjarmania.com Thu Jun 9 15:07:10 2005 From: tmj at jLUNCHEON_MEATjarmania.com (Tim Jarman) Date: Thu, 09 Jun 2005 20:07:10 +0100 Subject: Questions on using Qt or wxWindows with Python and OS X References: Message-ID: Hi Kenneth! In article , Kenneth McDonald wrote: > If this is not an appropriate newsgroup for this type of posting, > please let me know and (if possible) suggest an alternative. I've > done a fair bit of research on the net, but information is scattered > all over the place and I haven't been able to find mailing lists > relating specifically to python and UIs. > AFAIK there isn't a specific newsgroup/mailing list for Python GUIs in general, although perhaps there should be. This is as good a place to ask as any, I'd guess. > I'd like to start using Python for some GUI programming again. I'd > like to use Tk, but it seems to be dying a slow death, so it's > probably time to look at wxPython and PythonQt. > If you're ONLY interested in OS X, then you should be aware of PyObjC (see http://pyobjc.sourceforge.net/ for details) which will let you write Cocoa GUIs directly. (Yes, you probably already know about this, but still.) This is probably the best option for OS X only apps, but of course it isn't portable to other platforms. > I'd appreciate any comments on the relevant merits of these two > libraries, both with respect to Python and more generally. I know > about the differences in licensing, that's not an issue. I'm currently using wxPython for a moderately large (~ 70K LOC) OS X project. The docs aren't bad if you can translate C++ to Python; there are also some Python-specific docs coming along (see http://www.wxpython.org/docs/api/ ). There's also a wiki at http://wiki.wxpython.org/ which includes a useful cookbook section. The demo is the best documentation though, and worth its weight in something very valuable. I have Qt installed on my Mac but haven't played with it much as yet. It's generally held to be the best of the cross-platform GUI toolkits from a technical POV, modulo licensing issues on Windows, which are changing in ways I don't know much about because I don't care about Windows, so I can't help you with that. If you do care about Windows, though, I know from a previous life that wx looks good on that platform; I can't speak to Qt. I have the impression that Qt is more mature/stable in general than wx. There's an online book on PyQt by Boudewijn Rempt (see http://www.opendocs.org/pyqt/ ) - I think it's a bit dated now, but still worth a look. Having said all that, if I were doing my project again I'd use PyObjC. > My most > specific concerns are ease of use (which includes how much in the way > of documentation or examples for using through Python are available, > and how easy the Python libs are to use in each case); availability of > a generally capable styled text widget, as one of the things I need to > build is an editor, which needs to be able to handle different fonts, > styles, tabs, and so forth; and ease of installation on a Macintosh, > since that is my preferred dev platform, and installing things made > for other UNIX variants can be a little wonky at times. > As far as application deployment goes, both wx and Qt are easy to deploy on OS X using py2app (included with PyObjC but also available separately). > I'm also curious as to the quality of documentation available for > wxPython and wxWindows, and any differences between the > wxWindows text widget (which is generally Scintilla I believe), > and the Qt text widget classes. I've had a hard time finding good > docs for wxWindows or wxPython, and the bit of documentation > on Scintilla I've found and read seems to indicate that it has some > restrictions, such as needing to use the same line height for all lines > regardless of content. > See http://www.yellowbrain.com/stc/index.html for the gory details of using the Scintilla-based widget. There's also the wxWindows text control, which may be sufficient for your needs. (I believe there is also a Scintilla-based text widget for Qt.) I've tried various GUI toolkits looking for text-widget Nirvana, and the best I've found is good ol' Tk. Unfortunately Tk/Aqua is still a long way from looking lovely IMHO. You might want to check it out all the same if text processing is your thing. I'm sure there are people here who would disagree that it's "dying a slow death" just yet. ;) > Many thanks for any feedback you can give. > > > Cheers, > Ken HTH, Tim -- Remove luncheon meat to reply. From sjmachin at lexicon.net Thu Jun 2 16:50:25 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 06:50:25 +1000 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <429F7111.1060300@lexicon.net> Steven D'Aprano wrote: > On Thu, 02 Jun 2005 06:45:18 -0700, qscomputing wrote: > >>2. Philospohy(sp?) aside, > > > Philosophy. > > >>I could potentially want to create a >>binary-only distribution of my finished apps. I noticed the >>documentation on .pyc files: how do I create these > > > In PythonCard? I have no idea. Sorry. > > In ordinary Python? > > When you run or import a Python module, the Python interpreter first looks > for a .pyc file of the same name that is more recent than the .py file. If > it doesn't find one, it compiles the .py file into byte-code, stores the > byte-code in the .pyc file, and runs that. > > In other words, to create your .pyc file, just run your .py file and > Python will do it automatically. > The notion that just running a .py file will create a .pyc file is contrary to widely-held belief, and (admittedly small, but very recent, on Python 2.4.1, in a directory to which I have and had write access) empirical evidence. I can't be bothered checking *all* sightings of the time machine but my copy of 1.5.2 exhibits the same behaviour. Is it possible that you could be mistaken? From skip at pobox.com Fri Jun 10 10:55:44 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 10 Jun 2005 09:55:44 -0500 Subject: IMAP Proxy In-Reply-To: <42A99B1C.7020507@nuxeo.com> References: <42A99B1C.7020507@nuxeo.com> Message-ID: <17065.43504.775271.117915@montanaro.dyndns.org> Tarek> I want to write a small TCP Server in Python to make an IMAP Tarek> Proxy for post-processing client requests. Tarek> It is not long either complicated but needs to be very robust Tarek> so... maybe someone here has already done such a thing I can use Tarek> or know where i can get it ? There is an IMAP filter as part of the SpamBayes project that you might find is a useful starting point: http://www.spambayes.org/ Skip From onurb at xiludom.gro Mon Jun 6 04:13:03 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 06 Jun 2005 10:13:03 +0200 Subject: If - Or statements In-Reply-To: References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> Message-ID: <42a40590$0$23331$636a15ce@news.free.fr> Ognjen Bezanov wrote: (snip) > filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom > drive Please put long comments on the previous line... And BTW, please avoid useless comments that just paraphrase the code > for thefile in filelist[:]: #for each file in the filelist Do you really need to work on a copy of the list ? > if thefile.find(".") != -1: #if the file has an extenstion > at all > ext = thefile.split('.') #get the file extension > ext[1] = ext[1].lower() #convert to lowercase you may want to read the doc of the os.path module. The os.path.splitext() function could save you a lot of work here. > print ext[1] #debugging, to see the variable before > passed to if statement > > if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" > or ext[1] == "aac" or ext[1] == "wma": > print "we have a valid extension: " + ext[1] #here > would go the code for decoding the above > pass > Here's a somewhat more pythonic version: filelist = os.listdir(path) for filename in filelist: # I assume you want to remember what's the ext is ext = os.path.splitext(filename) # debug trace print "filename : %s - ext : %s" % (filename, ext) if ext in ['.this', '.that', '.whatnot']: print "ext is %s - should process this file" % ext HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From qwweeeit at yahoo.it Tue Jun 7 07:59:24 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 7 Jun 2005 04:59:24 -0700 Subject: Create our own python source repository Message-ID: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> Hi all, beeing almost a newbie, I am trying to learn from experts. For that reason I am collecting examples of Python sources (and Pythonic way of programming...) on a CD, ready to be searched. By now, I extracted from web (using wget) all the examples of Cookbook Python (35 Mb!). After some polishing and merging I obtained 20 files (one for each Category), which sum up to 12 Mb). To this source repository, I want also add my own scripts. But since my programming habits are not very Pythonic, I should prefer to include more meaningful examples. In the web there is plenty of such material, but I need the advice of experts to address me in the right direction... Bye. From adam.courquin at zuken.co.uk Wed Jun 22 14:45:35 2005 From: adam.courquin at zuken.co.uk (adamc) Date: 22 Jun 2005 11:45:35 -0700 Subject: debugging - converting PyObject back to a variable name Message-ID: <1119465935.636758.181100@z14g2000cwz.googlegroups.com> hi, I'm currently debugging a crash occurring in the Python interpreter. I've got a Dictionary object in the form of a (PyObject *) I can cast it to (dictobject *) in the debugger watch window, and I can also use PyString_AsString(PyObject_Repr()) to get the debugger to print out a string representation of the dictionary (actually I can't - this also crashes, because one of the "values" in the dictionary has become corrupted) What I'm trying to do is relate this dictionary object back to a variable name in my application source code (i.e. written in Python) - I've been searching round the web for an easy way of doing this - hopefully some function I can type into the debugger's watch window. thanks alot for the help adam From pinard at iro.umontreal.ca Sat Jun 4 08:08:38 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sat, 4 Jun 2005 08:08:38 -0400 Subject: any macro-like construct/technique/trick? In-Reply-To: <42a18c1d$0$24365$626a14ce@news.free.fr> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <42a18c1d$0$24365$626a14ce@news.free.fr> Message-ID: <20050604120838.GA6927@phenix.progiciels-bpi.ca> [Georges JEGO] > Mac a ?crit : > > # .... do some stuff > > if debug: > > emit_dbg_obj(DbgObjFoo(a,b,c)) > Assuming your debug functions always return true, you could use: > assert emit_dbg_obj(DbgObjFoo(a,b,c)) > and have this code executed -or not- depending on the use of "-O" Dirty, dirty trick :-). `assert' is quite useful in its real and genuine purpose. There is something heretic in allowing side effects in `assert' statements. A few centuries ago, Python programmers doing this were burnt in public, and this is how Python got forgotten for so long. (Guido rediscovered it a dozen years ago, the wise guy attributed all the merit to himself!) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From __peter__ at web.de Wed Jun 15 06:06:13 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Jun 2005 12:06:13 +0200 Subject: Tkinter question References: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> Message-ID: Nicholas.Vaidyanathan at aps.com wrote: [I didn't see the original post, so just in case noone mentioned it] > if(self.buttonx.title.isdigit): Nicholas, the method is not called unless you add parentheses, e. g: >>> "1".isdigit # a bound method *always* True in a boolean context >>> "1".isdigit() # True only if all chars in the string are digits True Another observation. buttonx need not be an attribute. for y in range(4): buttonx = ... will just work as well, provided you don't want to keep a reference of the last button created in the loop. Peter From cravephi at hotmail.com Thu Jun 2 03:56:57 2005 From: cravephi at hotmail.com (cravephi at hotmail.com) Date: 2 Jun 2005 00:56:57 -0700 Subject: wxpython or PyQT to make a simulink clone ? Message-ID: <1117699017.376196.37930@f14g2000cwb.googlegroups.com> I would like to make a software like simulink: http://www.mathworks.com/cmsimages/sl_mainpage_wl_7488.gif using python. In order of bulding the interface (drag&drop block, link system between the blocks, run the simulation, double click on a block to open its properties, ...) which library will make my job easyer, PyQT or WxPython ? From wesleyhenwood at hotmail.com Thu Jun 30 15:16:08 2005 From: wesleyhenwood at hotmail.com (Wesley Henwood) Date: 30 Jun 2005 12:16:08 -0700 Subject: python commmand line params from c++ In-Reply-To: References: <1120143124.925422.290980@g44g2000cwa.googlegroups.com> Message-ID: <1120158967.960768.57330@f14g2000cwb.googlegroups.com> Thanks Denis. PySys_SetArgv should do the trick. The nested function calls are there because the FILE structrure produced by fopen is not always compatible with the FILE structure produced by the Python C++ functions. Something do with the Python C being built with different version ofthe c run-time libs. The problem is a bit strange and should be adressed, it's documented somewhere on the Python site, but no solution is given. That I had to find by trial and error. Even better would be a function such as PyRun_File(char *filename), and do away with handling the FILE structure altogether. From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Wed Jun 1 15:18:46 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Wed, 01 Jun 2005 23:18:46 +0400 Subject: eric3 question References: Message-ID: ?????? Magnus! 31 ??? 2005 ? 13:46, Magnus Lycka ? ????? ?????? ? All ?????: ML> The readline method includes the whole line, including the ML> linefeed character if you press q followed by ENTER. If you ML> change it to... ML> while not sys.stdin.readline()=="q\n": oooops. I'am usually use Ctrl+C to break my program, so this bug was not found by me. ML> ...I guess it will work in eric3. (It works in IDLE then.) no. under eric3, exception "The socket operation could not completed without blocking" on line 160 in AsincFile.py (this file is from python's distribution). It seems, cause of bug is in method of redirection the console input/output to eric's windows. Btw, raw_input works fine. ML> In general, your construct makes it a bit difficult for you ML> to debug your own code. If you had written it like below... ML> while True: ML> inp = sys.stdin.readline() ML> if inp == 'q': ML> break ML> smthing(else) # Not that you can use else as a name... I hate such loops. Usually, if I see the loop, I want to see its condition at once, I don't want to search for it. In my opinion, "while True"+"break" is something like "goto"+"if" or even worse. ML> Changes and experiments like that are very easy to do in ML> Python. It beats staring at the code in confusion 99 times ML> out of 100. It's typically much faster than asking on c.l.py, ML> although not educational for as many people... ;) Anyway, now you know that eric3 use (possibly) little bit buggy mechanism for redirection of input/output. It's cool:) Alexander, zatv at bk.ru From peter at engcorp.com Sun Jun 12 21:43:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Jun 2005 21:43:29 -0400 Subject: What is different with Python ? In-Reply-To: <86ekb713hy.fsf@guru.mired.org> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Andrea Griffini writes: >>Also concrete->abstract shows a clear path; starting >>in the middle and looking both up (to higher >>abstractions) and down (to the implementation >>details) is IMO much more confusing. > > So you're arguing that a CS major should start by learning electronics > fundamentals, how gates work, and how to design hardware(*)? No, Andrea means you need to learn physics, starting perhaps with basic quantum mechanics and perhaps with some chemistry thrown in (since you can't really understand semiconductors without understanding how they're built, right?). Oh, and manufacturing. And a fundamental understanding of scanning electron microscopes (for inspection) would be helpful as well. I think probably a Ph.D. level training in mathematics might be a good start also, since after all this is the foundation of much of computing. A while later comes the electronics, and then memory management. Things like while loops and if statements, and *how to actually write a program* are, of course, only the eventual outcome of all that good grounding in "the basics" that you need first. -Peter From steve at REMOVETHIScyber.com.au Wed Jun 8 12:10:03 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 09 Jun 2005 02:10:03 +1000 Subject: Knowing the signature of a function References: <42a6e5cc$1_3@newspeer2.tds.net> Message-ID: On Wed, 08 Jun 2005 08:35:39 -0400, Kent Johnson wrote: >> How can I query the function object foo to know the number of parameters >> it expects. I can find it is a function using callable(f), I can find >> some information (listed by dir(foo)) such as the name of the >> function,etc.. but nowhere I can find the number of arguments. >> >> I would like to know wether the function expects one or zero arguments. > > foo.func_code.co_argcount gives the count of named args. > len(foo.func_code.co_varnames) gives the total number of arguments > including *args and **kwds args. inspect.getargspec() might also be > helpful. You guys are amazing, have you been spying on me? :-) I was just about to write in with the same question. Thanks for answering before I asked. -- Steven. From mauriceling at acm.org Thu Jun 16 03:12:13 2005 From: mauriceling at acm.org (Maurice LING) Date: Thu, 16 Jun 2005 17:12:13 +1000 Subject: Generating .pyo from .py References: Message-ID: say your code is "test.py" and you usually run it as "python test.py", then the "-O" option will generate .pyo files. That is "python -O test.py" Cheers maurice skn wrote: > Hello., > > Does the python compiler provide an option to generate a .pyo(optimized byte > code file) from a .py (source file)? > > For generating .pyc I know that I only have to pass the source file name as > an argument to py_compile.py. > But for generating .pyo, I could not find anything. > > Any clues/help will be greatly appreciated. > > With best regards, > skn > > From lycka at carmen.se Tue Jun 21 04:34:41 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 21 Jun 2005 10:34:41 +0200 Subject: strxfrm works with unicode string ? In-Reply-To: <1119003766.658567.228590@g14g2000cwa.googlegroups.com> References: <1118997804.678723.170070@g44g2000cwa.googlegroups.com> <1119003766.658567.228590@g14g2000cwa.googlegroups.com> Message-ID: nicolas.riesch at genevoise.ch wrote: > Gru?zi, Gerald ;-) > > Well, ok, but I don't understand why I should first convert a pure > unicode string into a byte string. > The encoding ( here, latin-1) seems an arbitrary choice. Yes. The correct choice would be 'cp1252', not 'latin-1', since that's what your locale setting indicates. It seems to me that Python is on a journey from the ASCII world to the Unicode world, and it will take a few more versions before it gets there. Going from 2.2 to 2.3 was a bumpy part of the ride, and it's still not smooth. Just try to use raw_input with national characters. As far as I remember it hasn't worked (on windows at least) since 2.2. The clear improvement from 2.3 is that if you print unicode strings to stdout, they will look correct both in the GUI and in text mode (cmd.exe). That never worked before since Windows use different code pages in Windows and in the text mode (which is supposed to be DOS compatible). From lee at example.com Wed Jun 1 16:18:56 2005 From: lee at example.com (Lee Harr) Date: Wed, 01 Jun 2005 20:18:56 GMT Subject: What's wrong with Zope 3 ? References: <1117581035.584193.310060@g47g2000cwa.googlegroups.com> <1117646659.949604.308920@z14g2000cwz.googlegroups.com> Message-ID: >> The current stable brance is Zope2.X If you want to incorporate some >> functionalty from X3 in Zope 2.X, do a search for "Five" > > No, I do not want to migrate components from a new major release > backwards, as well as I do not want to migrate applications from WinXP > to Win98. This seems to be the wrong development process direction. > There are an awful lot of zope 2 applications out there looking to migrate to zope 3. Five is one way to start that. Sort of like there are still a lot of win98 systems out there, and running python2.4 is a great way to get more use from the systems, but still be able to migrate to xp (or mac or linux) when the time comes. From maxerickson at gmail.com Mon Jun 6 12:12:18 2005 From: maxerickson at gmail.com (max) Date: Mon, 06 Jun 2005 16:12:18 -0000 Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: Steven D'Aprano wrote in news:pan.2005.06.06.16.00.26.364108 at REMOVETHIScyber.com.au: > By law, corporations (and possibly some other organisations) > *are* people. Not natural people like you or I, but nevertheless > people. For good or bad, this is the legal fact (or perhaps > "legal fiction") in most countries, and not a myth. s/myth/legal absurdity/ This is one thing that bothers me about the gpl. It essentially tries to create 'code as a legal entity'. That is, it gives rights not to the creator of some code, but to the code itself. For me, the fact that corporations are considered people by the law is ridiculous. Using a license that ends up doing the same thing with code leaves a bad taste in my mouth. max From tziade at nuxeo.com Fri Jun 10 09:52:28 2005 From: tziade at nuxeo.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Fri, 10 Jun 2005 15:52:28 +0200 Subject: IMAP Proxy Message-ID: <42A99B1C.7020507@nuxeo.com> Hi, I want to write a small TCP Server in Python to make an IMAP Proxy for post-processing client requests. It is not long either complicated but needs to be very robust so... maybe someone here has already done such a thing I can use or know where i can get it ? Cheers, Tarek From tzot at sil-tec.gr Mon Jun 27 19:30:08 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 02:30:08 +0300 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> <1119913778.308704.238610@g44g2000cwa.googlegroups.com> Message-ID: On 27 Jun 2005 16:09:38 -0700, rumours say that "Inkiniteo" might have written: >Humm. I just create the message this way: >message = 'Serie:\t\t' + str(type) + str(series) + \ > '\t\t\tUbicaci?n:\t\t\t' + place + '\n' + \ > 'Date&Time:\t' + date >and send it with: >message = header + message >server = smtplib.SMTP('localhost') >server.sendmail('email at email.com', email, message) >server.quit() And what goes wrong when you see the message? (BTW you don't have a newline before "Ubicaci?n:"; is it intentional?) Tabs are infamous confusers of email clients, unfortunately. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From roy at panix.com Wed Jun 15 09:07:30 2005 From: roy at panix.com (Roy Smith) Date: Wed, 15 Jun 2005 09:07:30 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> <42AFB8FD.1060504@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > Roy Smith wrote: > > Steven D'Aprano wrote: > > > > >High and low tides aren't caused by the moon. > > > > > > They're not??? > > Nope. They are mostly caused by the continents. If the > Earth was completely covered by ocean, the difference > between high and low tide would be about 10-14 inches. Yeah, I know about all that stuff. But, let's explore this from a teaching point of view. > The true situation is that tides are caused by the > interaction of the gravitational fields of the sun, the > moon and the Earth, the rotation of the Earth, the > physical properties of water, its salinity, the depth, > shape and composition of the coast and shoreline, the > prevailing ocean currents, vibrationary modes of the > ocean (including up to 300 minor harmonics), ocean > storms, and even the wind. That's a lot of detail to absorb, and is appropriate for a college-level course taken by oceanography majors. The key to teaching something is to strip away all the details and try to get down to one nugget of truth with which you can lay a foundation upon which further learning can happen. Yes, both the sun and the moon have gravitational fields which affect tides. But the moon's gravitational field is much stronger than the sun's, so as a first-order approximation, we can ignore the sun. And, yes, there's a huge amplifying effect caused by coastline shape and resonant frequencies of the ocean basins, but if you took away the moon (remember, we're ignoring the sun for now), there would be no tides at all. If you took away all the continents, there would still be tides, they would just be a lot less (and nobody would notice them!). And, yes, wind affects tide. I live at the western tip of Long Island Sound. If the wind is blowing hard along the axis of the Sound for a solid day or two, I can see that it has a drastic effect on the tides. This says to me that "The tides are created by the moon, amplified by the shapes of the land masses, and altered by the wind". Sure, "the moon causes the tides" is not the whole picture, and from a quantitative point of view, may not even be the major player, but from a basic "How do I explain this physical process to a 6th grade child in a way that's both easy to understand and fundamentally correct", I think "the moon causes the tides" is the only reasonable explanation. Once that basic idea is planted, all the other stuff can get layered on top to improve the understanding of how tides work. So, to try and bring this back to the original point of this thread, which is that Python is a better first language than C, let's think of the moon as the "algorithms, data structures, and flow control" fundamentals of programming, and memory management as the continents and ocean basins. What you want to teach somebody on day one is the fundamentals. Sure, there are cases where poor memory management can degrade performance to the point where it swamps all other effects, but it's still not the fundamental thing you're trying to teach to a new CS student. From laurent.rahuel at net-ng.com Tue Jun 7 18:02:53 2005 From: laurent.rahuel at net-ng.com (Laurent RAHUEL) Date: Wed, 08 Jun 2005 00:02:53 +0200 Subject: Reading a CSV file into a list of dictionaries References: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> <42a5fc08$0$302$7a628cd7@news.club-internet.fr> <42A603C7.8000702@lexicon.net> Message-ID: <42a61971$0$306$7a628cd7@news.club-internet.fr> John Machin wrote: > Laurent RAHUEL wrote: >> RFQ wrote: >> >> >>>Hi, I'm struggling here to do the following with any success: >>> >>>I have a comma delimited file where each line in the file is something >>>like: >>> >>>PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... >> >> >> This is NOT a CSV file. A CSV file would be : >> >> PNumber,Contractor,Architect,... >> 2056,XYZ Contracting,ABC Architects,... >> > > CSV is an acronym for "Comma-Separated Values". It does not imply > anything about the contents of the fields. The OP's file *is* a CSV > file. Yes, the contents do represent an unusual application of the CSV > format -- however a bus full of parcels instead of people is still a bus. I thought you knew the number of cols and what you should expect in each. Then it sounded pretty easy to build a list of dictionaries. If you don't know what you're supposed to find in your file and how this file is structured I guess you don't know what you are doing. > >> Then, you could use the built-in CSV module of recent python versions. > > Python is a case-sensitive language. The name of the module is "csv". > The OP could use the csv module with his data. Damn, that's why I always see those annoynig import errors. I just wanted to help, maybe you're to much case-sensitive. Regards, Laurent. From tdw at tdw.net Wed Jun 22 09:19:23 2005 From: tdw at tdw.net (Tim Williams) Date: Wed, 22 Jun 2005 14:19:23 +0100 Subject: Loop until condition is true References: <1119445067.473581.266570@g43g2000cwa.googlegroups.com> Message-ID: <00c601c5772d$10326920$ccbefea9@twilliams> ----- Original Message ----- From: "Greg Lindstrom" > A bit off topic, but what does the expression "Don't try to teach your > grandfather how to suck eggs." mean? I've never heard it before and am > curious to the story behind it. A relatively well know phrase, however as quoted it is incorrect, it should have referred to "grandmother" http://www.phrases.org.uk/bulletin_board/18/messages/50.html http://www.worldwidewords.org/qa/qa-tea1.htm :) From rkern at ucsd.edu Sat Jun 4 05:13:38 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 04 Jun 2005 02:13:38 -0700 Subject: If - Or statements In-Reply-To: <42A16BBE.4080301@mailshack.com> References: <42A16BBE.4080301@mailshack.com> Message-ID: <42A170C2.7000608@ucsd.edu> Ognjen Bezanov wrote: > Another newbie-ish question. > > I want to create an if statement which will check if a particular > variable matches one of the statements, and willl execute the statement > if the variable matches any of the statements. > > I have tried the following (the pass is just used for testing) > > > if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] == > "aac" or ext[1] != "wma": > print "we have a valid extension: " + ext[1] #here would go the > code for decoding the above > pass It works fine for me. Could you post the smallest complete program (one that defines ext) that displays the behavior and its entire output? As an aside, is 'ext[1] != "wma"' correct or should it be ==? As written, you could collapse the whole thing to 'if ext[1] != "wma":' but I presume it is a typo. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From cam.ac.uk at mh391.invalid Sun Jun 12 03:45:55 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 12 Jun 2005 08:45:55 +0100 Subject: What language to manipulate text files In-Reply-To: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: ross wrote: > I want to do some tricky text file manipulation on many files, but have > only a little programming knowledge. > > What are the ideal languages for the following examples? > > 1. Starting from a certain folder, look in the subfolders for all > filenames matching *FOOD*.txt Any files matching in each folder should > be copied to a new subfolder within the current folder called EATING > with a new name of *FOOD*COPY.txt This should get you started: import errno from path import path # http://www.jorendorff.com/articles/python/path/ dst_dirpath = path("EATING") # create dst_dirpath try: dst_dirpath.makedirs() # make destination directory and its parents except OSError, err: # error! if err.errno = errno.EEXIST: # might just be that it already exists if not dst_dirpath.isdir(): # and it's a directory raise # if not, raise an exception for filepath in path(".").walkfiles("*FOOD*.txt"): infile = file(filepath) outfile = file(dst_dirpath.joinpath(filepath.namebase+"_COPY.txt")) ...do processing here... > My first objective is to process the files as described. > My second objective is to learn the best language for this sort of text > manipulation. The language should run on Windows 98, XP and Linux. > > Would Python be best, or would a macro-scripting thing like AutoHotKey > work? Personally, I'd use Python, but what do you expect when you ask here? -- Michael Hoffman From mhoy4 at cox.net Thu Jun 9 02:19:33 2005 From: mhoy4 at cox.net (Mike Hoy) Date: Wed, 08 Jun 2005 23:19:33 -0700 Subject: my golf game needs gui Message-ID: <1118297973.5296.3.camel@laptop.solodiver> hi i've been writing a golf game in text only. this was to work out some of details. it's great but making a golf course with ---'s and |||'s is kinda silly looking. (at least to some..) now i'm ready to begin shopping for a gui widget to work with python so my players can have some kind of pictures and possibly some motion. i won't be creating figures swinging the golf clubs but would like to show their golf ball flying thru the air and land on the green for one example. will pyQT work for me? any suggestions on which way I should go next? i would like my game to work on linux and possibly windows as well, unless developing for windows means i will have to write it all over again.. let me know what your reactions are. thanks. From detlev at die-offenbachs.de Sat Jun 4 06:53:22 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 04 Jun 2005 12:53:22 +0200 Subject: ANN: eric3 3.7.0 released Message-ID: Hi, this is to let all of you know about the release of eric3 3.7.0. Next to a bunch of bugfixes, it adds these features. - support for Ruby projects (debugger, syntax highlighting) - support for the generation of KDE UIs - introduction of watchpoints - added class browsers for Ruby and CORBA IDL files - added bookmark capability to the file browser - added context menus for directories to the various browsers - added tasks and a task viewer and a bunch of little improvements. As usual it is available via http://www.die-offenbachs.de/detlev/eric3.html Go get it and enjoy working with it. Many thanks to all people who have tested the snapshots, send bug reports and supported the development by sending patches and translating the eric3 UI. What is it ---------- Eric3 is a full featured development environment for Python and Ruby released under the conditions of the GPL. Please see above URL for more information and download. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From guy.lateurNNOOSSPPAAMM at pandora.be Fri Jun 10 14:06:41 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Fri, 10 Jun 2005 18:06:41 GMT Subject: how to retrieve info about print jobs References: <3EAne.108100$xW2.6437935@phobos.telenet-ops.be> Message-ID: Perhaps I should mention this: we have printers from HP, and they come with a tool called JetDirect. This allows you to browse to it and check it's status/stats. Maybe I should write something that automatically gathers the info from the printer homepage. Would that be a good/easy way to go about it? Alternatively, I could send the info about a user's print jobs from their individual pc to a central 'database', and then get it from there. Just brainstorming out loud, here.. "Guy Lateur" schreef in bericht news:B5Zpe.115048$N46.6808602 at phobos.telenet-ops.be... > Hmm, this only seems to work for jobs that originate on the machine > running the script. I really need something that actually gathers the info > from the printers (net-based). Would that be possible at all? > From johng2001 at rediffmail.com Fri Jun 24 18:37:13 2005 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 24 Jun 2005 15:37:13 -0700 Subject: Favorite non-python language trick? In-Reply-To: <42BC8051.4010800@lexicon.net> References: <1119648577.754818.119530@z14g2000cwz.googlegroups.com> <42BC8051.4010800@lexicon.net> Message-ID: <1119652633.766216.305010@o13g2000cwo.googlegroups.com> John Machin wrote: > James wrote: > > Interesting thread ... > > > > 1.) Language support for ranges as in Ada/Pascal/Ruby > > 1..10 rather than range(1, 10) > > Did you mean 1..9 or 1...10 or both or neither? You are right. There is a difference. 1..10 == range(1, 10 + 1) > Can this construct be used like this: (i+1)..n ? If not, what would you > use? Sure. In Ruby, you can do i = 2 n = 5 for x in (i+1)..n do print x end Can't in Ada/Pascal as far as I remember. > What is the frequency of range literals in the average piece of code? Well! I certainly have not done a study with code metrics. You probably can find something online. That probably will be variable and might depend on individual language affordances. BTW, Ruby's times loop is another thing I find better readable for a few cases. 4.times { print "Something ..." } than for x in range(4): print "Something ..." From tim.golden at viacom-outdoor.co.uk Wed Jun 29 07:29:51 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 12:29:51 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB94A@vogbs009.gb.vo.local> [Greg Miller] | | The two machines are both running Windows XP, the desktop is | running XP Pro, the "virgin" PC is running XP embedded. Well my first thought was: maybe XP Embedded has cut out WMI. A quick Google around suggests that it's still there, but maybe there's some restrictions in what you can give it as a moniker. My module puts sensible defaults in, rather than using the most minimalistic moniker. You can pass a ready-made moniker in: import wmi wmi._DEBUG = 1 moniker = "winmgmts:" c = wmi.WMI (moniker=moniker) for i in c.Win32_Printer (): print i.Caption You might try that to see if it gets round things. | I didn't have this problem on the | first release | as we weren't interested in displaying the file version of the .dll. | With this improved version of the product the request has come down to | have all software package versions displayed, so that is why I am now | attempting to extract the file version of the dll. Thanks again for | everyone's assistance................. There was some talk a while back about including the win32 calls to get file versions into the pywin32 packages. Might be worth checking to see if it's happened. Or using ctypes, of course. If WMI is this much trouble, and only for this one piece of info, definitely worth looking elsewhere. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From luismgz at gmail.com Thu Jun 30 09:31:35 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: Thu, 30 Jun 2005 10:31:35 -0300 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> <8c7f10c605063001207fd379ec@mail.gmail.com> Message-ID: <004601c57d79$786f1db0$1302a8c0@luis> Well, yes, it is kinda off topic, but very interesting... Being myself an argentine with spanish as mother tongue and a very bad English, it's hard foro me to tell the difference between accents. I can hardly tell an Irish from an English... But what I did tell is the broad range of different accents within London when I visited the city in 2001. Some people seemed to speak very clear to me, and others seemed to be speaking german! And as far as I know, all these people were british, not immigrants (and very hard to find indeed...). Cheers, Luis ----- Original Message ----- From: "Simon Brunning" To: "Luis M. Gonzalez" Cc: Sent: Thursday, June 30, 2005 5:20 AM Subject: Re: When someone from Britain speaks, Americans hear a "British accent"... On 29 Jun 2005 15:34:11 -0700, Luis M. Gonzalez wrote: > What's exactly the "cockney" accent? > Is it related to some place or it's just a kind of slang? A cockney is a *real* Londoner, that is, someone born within the City of London, a.k.a The Square Mile. More specifically, it's someone born "within the sound of Bow Bells" - i.e. close to St Mary le Bow, London - . This is within the theoretical sound of Bow Bells, you understand - there have been frequent and lengthy periods during which Bow Bells have not been rung at all. There are in fact no longer any hospitals with maternity units within the sound of Bow Bells, so there will be vanishingly few cockneys born in future. Strangely enough, this makes *me* a cockney, though I've never lived in the square mile, and my accent is pretty close to received. I do *work* in the City, though! The cockney accent used to be pretty distinct, but these days it's pretty much merged into the "Estuary English" accent common throughout the South East of England. > I'm not sure, but I think that I read somewhere that it is common in > some parts of London, and that it is a sign of a particular social > class, more than a regionalism. Is that true? Cockney was London's working class accent, pretty much, thought it was frequently affected by members of the middle classes. Estuary English has taken over its position as the working class accent these days, but with a much wider regional distribution. How off topic is this? Marvellous! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From foo at bar.com Mon Jun 20 16:47:24 2005 From: foo at bar.com (Steve Menard) Date: Mon, 20 Jun 2005 16:47:24 -0400 Subject: JEP and JPype in a single process In-Reply-To: References: Message-ID: skn wrote: > Hello, > > I have written a very simple java class file, which invokes a Python script > using JEP. > > Code snippet:- > ------------------- > Jep jep = new Jep(false); > jep.runScript("C:\\temp\\testscript.py"); > jep.close(); > > Now inside this Python script I want to make Java calls using JPype. > If I use startjvm() inside this Python script, a Runtime Error (exception) > is thrown. > Also tried attachThreadToJVM(), but doesn't work, again Runtime Error. > > Any clues as to how I could achieve my goal?? > The interaction shown below should happen in a single process. > > JAVA ==> jep ==> PYTHON ==> jpype ==> JAVA > > Regards, > skn > > You're trying to do something I hope to make possible somewhere down the road ... As of today, I do not think it is possible. JPype does not provide a way to initialize the JVM-bridge system except for startJvm .. which seems to be prohibited when a JVM is already running. AttachThreadToJVM will only work once the JVM-bridge system has been initialize. I will look into providing a sister method to startJVM to attach to the currently running JVM instead of starting a new one. IF it does not require major changes I will release it as 0.5.1. If you'd like you can submit an enhancement request on the JPype sourceforge page, so this doesn't get lost. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From newsgroups at jhrothjr.com Thu Jun 2 20:23:24 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 2 Jun 2005 18:23:24 -0600 Subject: saving .zip or .txt email attachments instead of deleting them References: <1117746435.769666.186810@z14g2000cwz.googlegroups.com> <119utnt1mvdue50@news.supernews.com> <1117748443.644449.30170@g43g2000cwa.googlegroups.com> Message-ID: <119v8ntj6bren91@news.supernews.com> "scrimp" wrote in message news:1117748443.644449.30170 at g43g2000cwa.googlegroups.com... > Im using the winpython IDE to run that script for the unpacking the > email. The usage says unpackmail [options] msgfile. I type unpackmail > -d filename and it gives me a syntax error. What modifications did u do > to that module to make it work? I always run it from the command line. With all due respect to the authors, there are too many problems with command execution in PythonWin for me to bother. These aren't precisely bugs, but they are environmental limitations which make it impractical to use it the way I usually use it. And as Peter said, please cut and paste the complete output, including the command you entered. Thanks. John Roth > From donn at u.washington.edu Thu Jun 23 20:27:49 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 23 Jun 2005 17:27:49 -0700 Subject: trouble subclassing str References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> Message-ID: In article , Steven D'Aprano wrote: > On Thu, 23 Jun 2005 12:25:58 -0700, Paul McGuire wrote: > > > But if you are subclassing str just so that you can easily print your > > objects, look at implementing the __str__ instance method on your > > class. Reserve inheritance for true "is-a" relationships. Often, > > inheritance is misapplied when the designer really means "has-a" or > > "is-implemented-using-a", and in these cases, the supposed superclass > > is better referenced using a member variable, and delegating to it. > > Since we've just be talking about buzzwords in another thread, and the > difficulty self-taught folks have in knowing what they are, I don't > suppose somebody would like to give a simple, practical example of what > Paul means? > > I'm going to take a punt here and guess. Instead of creating a sub-class > of str, Paul suggests you simply create a class: > > class MyClass: > def __init__(self, value): > # value is expected to be a string > self.value = self.mangle(value) > def mangle(self, s): > # do work on s to make sure it looks the way you want it to look > return "*** " + s + " ***" > def __str__(self): > return self.value > > (only with error checking etc for production code). > > Then you use it like this: > > py> myprintablestr = MyClass("Lovely Spam!") > py> print myprintablestr > *** Lovely Spam!!! *** > > Am I close? That's how I read it, with "value" as the member variable that you delegate to. Left unexplained is ``true "is-a" relationships''. Sounds like an implicit contradiction -- you can't implement something that truly is something else. Without that, and maybe a more nuanced replacement for "is-implemented-using-a", I don't see how you could really be sure of the point. Donn Cave, donn at u.washington.edu From woodsplitter at rocketmail.com Thu Jun 30 04:00:53 2005 From: woodsplitter at rocketmail.com (woodsplitter at rocketmail.com) Date: 30 Jun 2005 01:00:53 -0700 Subject: MS Compiler to build Python 2.3 extension References: <1120054137.471983.240320@o13g2000cwo.googlegroups.com> Message-ID: <1120118453.192290.32170@g44g2000cwa.googlegroups.com> MS Visual C++ 6 is indeed the compiler that the python.org distributions are built with, but MinGW works fine too. In fact, the code generated by MinGW-GCC 3.4.4 outpaces that generated by MSVC++ 6.0 by a considerable margin in some of my performance-critical extensions, and the size of the binaries is often smaller. From ptmcg at austin.rr.com Mon Jun 27 09:26:54 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Jun 2005 06:26:54 -0700 Subject: turn text lines into a list In-Reply-To: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> Message-ID: <1119878814.574356.68200@o13g2000cwo.googlegroups.com> See definition of splitlines(). (http://docs.python.org/lib/string-methods.html) -- Paul From ChuckDubya at gmail.com Wed Jun 29 03:11:17 2005 From: ChuckDubya at gmail.com (ChuckDubya at gmail.com) Date: 29 Jun 2005 00:11:17 -0700 Subject: Newbie: Explain My Problem Message-ID: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> Code: #The Guess My Number Game import random num = "" guess = "" counter = 7 num = random.randrange(1, 100) print "I'm thinking of a whole number from 1 to 100." print "You have ", counter, " chances left to guess the number." print guess = int(raw_input("Your guess is: ")) while counter != 0: if guess == num: print "You guessed the number, ", num, " in ", counter-6, " guesses!" elif guess > num: counter = counter - 1 print print "The number is less than your guess." print "You have ", counter, " chances left to guess the number." guess = int(raw_input("Your guess is: ")) else: counter = counter - 1 print print "The number is greater than your guess." print "You have", counter, " chances left to guess the number." guess = (raw_input("Your guess is ")) if counter == 0: print "You idiot, my number was", num,"!" print "YOU LOSE!" raw_input("Hit the enter key to exit.") Two things wrong happen: - Dialogue switches from saying "number is greater" to "number is less", regardless of guess - Lets user guess when user has no more guesses left in "counter" variable. Please explain to me what's wrong with my program. From rdsteph at mac.com Thu Jun 2 22:41:23 2005 From: rdsteph at mac.com (rdsteph at mac.com) Date: 2 Jun 2005 19:41:23 -0700 Subject: Looking for Image, Audio and Internet/Web HOTWO's or tutorials References: <1117735244.363447.10340@f14g2000cwb.googlegroups.com> Message-ID: <1117766483.074108.140200@g47g2000cwa.googlegroups.com> try looking at http://www.awaretek.com/tutorials.html From nospam at here.com Wed Jun 1 11:38:43 2005 From: nospam at here.com (Matt Feinstein) Date: Wed, 01 Jun 2005 11:38:43 -0400 Subject: Unhappy with numarray docs References: <429dc954$1@nntp0.pdx.net> Message-ID: <1dlr911ln6omm7nov1amaqtbikdvp51p7n@4ax.com> On Wed, 01 Jun 2005 08:11:36 -0700, Scott David Daniels wrote: >Propose some fixes to the documents that will make this easier for >the next one in line. You don't even need to get it exactly right; >the person after you can fix the mistakes you make. This is the >process we use for this. See this as an opportunity to contribute, >not simply a frustration about how much you overpaid for the product. Which is why I was specific about what I didn't like about the documentation and why I didn't like it. Seriously, what more should I do? It's plainly inappropriate for me to write documentation for a module that I'm still struggling to learn. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From david.ascher at gmail.com Thu Jun 2 13:35:14 2005 From: david.ascher at gmail.com (David Ascher) Date: Thu, 2 Jun 2005 10:35:14 -0700 Subject: New mailing list to discuss Google Summer of Code Message-ID: In order to centralize discussion and minimize spam, we've created a new mailing list to discuss the Google Summer of Code from a Python POV. I strongly encourage people interested in discussing possible projects, people who'd be willing to help students this summer as mentors, and any students considering applying for the program to join and start discussions on that list. The mailing list web page is at: http://mail.python.org/mailman/listinfo/summerofcode Cheers, -- David Ascher (PSF) From sjh at gmail.com Sun Jun 5 20:22:14 2005 From: sjh at gmail.com (sjh at gmail.com) Date: 5 Jun 2005 17:22:14 -0700 Subject: PyArg_ParseTuple and dict Message-ID: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> I'm trying to write an extension for python 2.4, and I can't seem to get PyArg_ParseTuple to work with a dict. I've tried all sorts of things, but the most simple thing that fails is: [...] if (!PyArg_ParseTuple(args, "O", &file)) { return NULL; } [...] If I call the function from python with an int, or a string, etc it works fine. If I pass in a dict I get: SystemError: new style getargs format but argument is not a tuple even though a call to: PyObject_TypeCheck(args, &PyTuple_Type) tells me that args is a tuple. PyObject_Print(args, stdout, NULL) even produces: ({'foo': 1},) Can anyone give me a minimal example of a C function that takes a dict and parses it out with PyArg_ParseTuple? -Seth From d at e.f Sat Jun 25 18:20:27 2005 From: d at e.f (D H) Date: Sat, 25 Jun 2005 17:20:27 -0500 Subject: A strange and annoying restriction, possibly a bug. A glance by a more experienced would be nice. In-Reply-To: References: Message-ID: Elmo M?ntynen wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > This is the case: > > >>>>n=(100,) tuple(*n) > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > tuple(*n) > TypeError: iteration over non-sequence The star (*n) means you are essentially calling tuple(100). And 100 alone isn't a sequence. The star explodes or expands the sequence, like in this example: def doit(x, y, z): print x, y, z vals = (1,2,3) doit(*vals) #see the star symbol From harold.fellermann at upf.edu Mon Jun 13 18:30:19 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 14 Jun 2005 00:30:19 +0200 Subject: translating C++ exceptions to python In-Reply-To: <1118661783.702138.128880@g49g2000cwa.googlegroups.com> References: <1118661783.702138.128880@g49g2000cwa.googlegroups.com> Message-ID: On 13.06.2005, at 13:23, calin.hanchevici at gmail.com wrote: > Hi all, > > I have a C++ library I call from python. The problem is I have c++ > exceptions that i want to be translated to python. I want to be able to > do stuff like: > try: > my_cpp_function() > except cpp_exception_1: > do_stuff > except cpp_exception_2: > do_other_stuff > > any ideas how can i do the translation? If you do not already use it, have a look at http://www.boost.org/libs/python/ a C++ -- library to wrap the Python C API, i.e. it helps you to extend Python in C++. AFAIK it has fascilities to transform exceptions from one type into the other. - harold - --- Everybody lies. but it does not matter, as no one listens. --- From jjl at pobox.com Sun Jun 5 10:44:28 2005 From: jjl at pobox.com (John J. Lee) Date: 05 Jun 2005 14:44:28 +0000 Subject: Q: functional/equational language, smells a little of Python References: <871x7hn5za.fsf@pobox.com> <1117959822.889652.257290@g44g2000cwa.googlegroups.com> Message-ID: <87k6l8lv77.fsf@pobox.com> "Kay Schluehr" writes: [...] > I'm curious why do you think that it "smells like Python"? Because of > "batteries included"? Partly that and the mention of dynamic typing, plus harder-to-pin down things. I didn't mean to say that it was close kin to Python, just that on first impression it has some similarities. > Are dotNET and Java Python-like because they come > up with a fast object library? [...] What's a fast object library? John From trentm at ActiveState.com Tue Jun 7 16:35:32 2005 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 7 Jun 2005 13:35:32 -0700 Subject: ANN: ActivePython 2.4.1 for Mac OS X is now available! In-Reply-To: <42A5BA80.9080909@plus.net> References: <20050607150658.GB5985@ActiveState.com> <42A5BA80.9080909@plus.net> Message-ID: <20050607203532.GA24053@ActiveState.com> > Trent Mick wrote: > >Meanwhile, some of you may be interested to know that we are busily > >working on bringing Komodo to Mac OS X. We expect to offer a beta in > >August and release later this year. [John Abel wrote] > Komodo for OSX? Now that's something I would be interested in > purchasing. We're workin' on it. :) Trent -- Trent Mick TrentM at ActiveState.com From claudio.grondi at freenet.de Mon Jun 13 04:19:02 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 13 Jun 2005 08:19:02 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: <3h4mt6FfautiU1@individual.net> > They're things that can be IMO genuinely accept > as "obvious". Even "counting" is not the lowest > level in mathematic... there is the mathematic > philosohy direction. I am personally highly interested in become aware of the very bottom, the fundaments all our knownledge is build on. Trying to answer questions like: What are the most basic ideas all other are derived from in mathematics and programming? keeps me busy for hours, days, years ... Any insights you can share with me(and/or this group)? Claudio "Andrea Griffini" schrieb im Newsbeitrag news:5q5qa1lotp0fbjru7i4492lloec251664v at 4ax.com... > On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: > > >How far down do you have to go? What makes bytes of memory, data busses, > >and CPUs the right level of abstraction? > > They're things that can be IMO genuinely accept > as "obvious". Even "counting" is not the lowest > level in mathematic... there is the mathematic > philosohy direction. From "counting" you can go > "up" in the construction direction (rationals, > reals, functions, continuity and the whole > analysis area) building on the counting concept > or you can go "down" asking yourself what it > does really mean counting, what do you mean > with a "proof", what really is a "set". > However the "counting" is naturally considered > obvious for our minds and you can build the > whole life without the need to look at lower > levels and without getting bitten too badly for > that simplification. > > Also lower than memory and data bus there is > of course more stuff (in our universe looks > like there is *always* more stuff no mattere > where you look :-) ), but I would say it's > more about electronic than computer science. > > >Why shouldn't first-year CS students study "how a computer works" at the > >level of individual logic gates? After all, if you don't know how gates > >work, things like address bus decoders, ALUs, register files, and the like > >are all just magic (which you claim there is no room for). > > It's magic if I'm curious but you can't answer > my questions. It's magic if I've to memorize > because I'm not *allowed* to understand. > It's not magic if I can (and naturally do) just > ignore it because I can accept it. It's not > magic if I don't have questions because it's > for me "obvious" enough. > > >> Also concrete->abstract shows a clear path; starting > >> in the middle and looking both up (to higher > >> abstractions) and down (to the implementation > >> details) is IMO much more confusing. > > > >At some point, you need to draw a line in the sand (so to speak) and say, > >"I understand everything down to *here* and can do cool stuff with that > >knowledge. Below that, I'm willing to take on faith". I suspect you would > >agree that's true, even if we don't agree just where the line should be > >drawn. You seem to feel that the level of abstraction exposed by a > >language like C is the right level. I'm not convinced you need to go that > >far down. I'm certainly not convinced you need to start there. > > I think that if you don't understand memory, > addresses and allocation and deallocation, or > (roughly) how an hard disk works and what's > the difference between hard disks and RAM then > you're going to be a horrible programmer. > > There's no way you will remember what is O(n), > what O(1) and what is O(log(n)) among containers > unless you roughly understand how it works. > If those are magic formulas you'll just forget > them and you'll end up writing code that is > thousands times slower than necessary. > > If you don't understand *why* "C" needs malloc > then you'll forget about allocating objects. > > Andrea From __peter__ at web.de Wed Jun 29 01:26:26 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 29 Jun 2005 07:26:26 +0200 Subject: tkinter radiobutton References: <1ygwe.532$Ox3.193@newssvr12.news.prodigy.com> Message-ID: William Gill wrote: > Also, does 'row == var.get() for var in self.variables' perform the > comparison row == var.get() for each item in self.variables???I?would > have had to write: > > for var in self.variables: > return?row?==?var.get() Or rather result = [] for var in self.variables: result.append(row == var.get()) return tuple(result) This can be rewritten to a 'list comprehension' return tuple([row == var.get() for var in self.variables]) and, since Python 2.4, to the 'generator expression' that I used and which avoids building the intermediate list. Both constructs also feature an if-clause, see http://docs.python.org/tut/node7.html#SECTION007140000000000000000 http://docs.python.org/tut/node11.html#SECTION00111100000000000000000 > p.s.??I?tweaked > > rbn = tk.Radiobutton(self, text=text, variable=var, value=y) > to > rbn = tk.Radiobutton(self, text=text, variable=var, value=y+1) > > and > > return tuple(row == var.get() for var in self.variables) > to > return tuple(row+1 == var.get() for var in self.variables) > > so that the Radiogrid doesn't initialize w/row 1 selected, and > accomodates cases where nothing is selected in any column. Another option would have been to initialize the variables ... var?=?tk.IntVar() var.set(-1) if?trace_write: ... Peter From tbr at nospam.nos Fri Jun 24 06:26:57 2005 From: tbr at nospam.nos (TechBookReport) Date: Fri, 24 Jun 2005 11:26:57 +0100 Subject: printing indented html code In-Reply-To: References: Message-ID: Lowell Kirsh wrote: > Is there a module or library anyone knows of that will print html code > indented? What I'd like would be for a function or class which works > like this: > > htmlIndent(sys.stdout, 'foobar...') > > and will print somethinkg like this to stdout: > > > > foobar > > ... > > My current way of doing this kind of stuff is less than ideal and will > write such a function if it doesn't exist. > > Thanks, > Lowell There are lots of HTML pretty printers around, but for starters take a look at this: http://www.oreilly.com/catalog/pythonsl/chapter/ch05.html HTH ========================================================================== TechBookReport - http://www.techbookreport.com From ruach at chpc.utah.edu Thu Jun 23 17:29:31 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 23 Jun 2005 15:29:31 -0600 Subject: formatted xml output from ElementTree inconsistency In-Reply-To: References: Message-ID: Jarek Zgoda wrote: > Matthew Thorley napisa?(a): > >> The output I get shows xmla as nicely formatted text, with elements on >> different lines and everything all tabbed and pretty. Inverly, xmlb is >> one long string on one line. >> >> Is that because the some_file.xml is already nicely formatted? I >> thought that the formatting was ignored when creating new elements. > > > Why want you to read an XML document "by hand"? It's a "machine related" > data chunk. > > Document formatting should be done by means of CSS and/or XSL stylesheet. > It is just data to the machine, but people may have to read and interpret this data. I don't think there is anything unsual about formatting xml with tabs. Most web pages do that in their html/xhtml. Just imagine if you wanted to change a broken link on your web page, and the entire page was one long string. That may not matter to Dream Weaver, but it sure would be annoying if you were using vi :) -Matthew From peter at engcorp.com Thu Jun 9 07:48:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 07:48:53 -0400 Subject: identifying 64-bit Windows from 2.3.5? In-Reply-To: References: Message-ID: Steven Knight wrote: > ... the same Python executable and code works just fine on both systems, > but I need to do different things (in this case, invoke a different > compiler with a different set of compiler options) based on whether or > not I'm building on a 32-bit or 64-bit system. Would a test for the presence of the 64-bit version of the compiler (or better yet, an attempt to execute it, then a fallback to the other if it fails) not work adequately? Or, failing that, does sys.maxint return something different on the 64-bit system? -Peter From michele.simionato at gmail.com Sat Jun 18 00:10:37 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Jun 2005 21:10:37 -0700 Subject: What is different with Python ? In-Reply-To: References: <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> <3hg08rFh2tr3U1@individual.net> <1119015358.155954.92430@g47g2000cwa.googlegroups.com> Message-ID: <1119067837.776544.198870@g49g2000cwa.googlegroups.com> Andrea Griffini wrote: > Why hinder ? Suppose you have to accomplish a given task using a framework which is unknown to you. The manual is 1000 pages long. In order to get the job done, it is enough to study 50 pages of it. There are people with the ability to figure out very quickly which are the relevant 50 pages and ignore the other 950. Granted, these people will have a shallow knowledge with respect to somebody studying the whole manual, but they will get the job done much faster and in some circumstances speed is more valuable than deep knowledge. To be able to content himself with a shallow knowledge is a useful skill ;) Michele Simionato From tgflynn at stny.rr.com Thu Jun 2 17:41:45 2005 From: tgflynn at stny.rr.com (Tim Flynn) Date: Thu, 02 Jun 2005 21:41:45 GMT Subject: viewing generated images References: Message-ID: Fredrik Lundh wrote: > Tim Flynn wrote: > >> def createWidgets(self): >> self.image_size = (50,50) >> self.pilim = Image.new( "1", self.image_size ) >> >> # Generate a blank image >> f = lambda(x): 0 >> Image.eval( self.pilim, f ) > > I'm not sure what you think that line is doing, but it probably > doesn't do what you think it does. > > try changing the Image.new call to > > self.pilim = Image.new( "1", self.image_size, 0 ) > > instead. > >> self.bmi = ImageTk.BitmapImage( image = self.pilim, >> foreground = 'black' ) > >> self.canvas = Canvas( width=100, >> height = 100, >> bg = 'white' ) >> self.quitButton = Button( self, >> text="Quit", >> command=self.quit ) >> self.quitButton.grid() >> self.canvas.grid() >> im_id = self.canvas.create_bitmap( 0, >> 0, >> anchor = 'nw', >> bitmap = self.bmi ) > > it's a terminology confusion: for historical reasons, Tkinter > distinguishes between > bitmaps and images (this separation comes from the X window system). > Bitmap- Image creates an image. > > changing to create_image should fix the problem. > > (if you're doing an image viewer, you may want to use PhotoImage > instead of BitmapImage, btw). > > That fixed the problem I was having and your right I was confused about how to create the image but I'm sure I'll be able to figure that out now that I'm getting some output. Thanks much. Tim From tim.golden at viacom-outdoor.co.uk Thu Jun 30 08:38:05 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Jun 2005 13:38:05 +0100 Subject: Store multiple dictionaries in a file Message-ID: <9A28C052FF32734DACB0A288A3533991EBB95F@vogbs009.gb.vo.local> [John Machin] | | bruno modulix wrote: | > Philipp H. Mohr wrote: | | >>My code currently produces a new dictionary every iteration and | >>passes it on to another peace of code. | > | > | > May this code rest in piece | | Perhaps it's the piece of code that passeth all understanding? That's really rather funny. I'm tickled. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From roccomoretti at hotpop.com Wed Jun 8 16:01:57 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 08 Jun 2005 15:01:57 -0500 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: Matt Warden wrote: > Jordan, > > On 8 Jun 2005 11:44:43 -0700, Jordan Rastrick > wrote: > >>But I explicitly provided a method to test equality. And look at the >>plain english meaning of the term "Not equals" I think its pretty >>reasonable > > > Indeed. Furthermore, it seems quite silly that these would be different: > > a != b > not (a == b) It's only "silly" if one sticks to strict Boolean semantics or implicitly assumes the law of the excluded middle (http://en.wikipedia.org/wiki/Excluded_middle), the principle of bivalence (http://en.wikipedia.org/wiki/Principle_of_bivalence), or the law of noncontradiction (http://en.wikipedia.org/wiki/Law_of_non-contradiction). Despite "law" status, it is possible (and useful) to imagine situations where they don't hold. (A'la non-euclidlean geometry). The main problem is that Python is trying to stick at least three different concepts onto the same set of operators: equivalence (are these two objects the same?), ordering (in a sorted list, which comes first?), and mathematical "size". This gives the wacky world where "[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't. Luckily another related concept, identity, has already been separated out (the 'is' operator). It would be nice (but I'm not hoding my breath) if the complete issue gets resolved with Python 3000. From kveretennicov at gmail.com Sat Jun 18 14:50:37 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 18 Jun 2005 20:50:37 +0200 Subject: What makes an object uncopyable? In-Reply-To: <1119048067.749297.23010@g49g2000cwa.googlegroups.com> References: <1119048067.749297.23010@g49g2000cwa.googlegroups.com> Message-ID: <4660fe30050618115057aedc89@mail.gmail.com> On 17 Jun 2005 15:41:07 -0700, tron.thomas at verizon.net wrote: > I am trying to make a copy of a certain Python object using the > copy.copy() function. When I try to perform this operation I get an > error like the following: > > copy.Error: un(shallow)copyable object of type ... > > What factors determine whether an object can be copied? You are probably trying to copy an instance of a class implemented in C extension. AFAIK, Python classes have copy support by default, but extension classes need to implement copy/pickle protocol. - kv From thomas.weholt at gmail.com Thu Jun 9 18:02:59 2005 From: thomas.weholt at gmail.com (Thomas W) Date: 9 Jun 2005 15:02:59 -0700 Subject: cx_freeze error : LookupError: no codec search functions registered:can't find encoding In-Reply-To: References: <1118337079.095493.117690@g43g2000cwa.googlegroups.com> Message-ID: <1118354579.351961.80600@g14g2000cwa.googlegroups.com> Ok, I'll post my findings here since there are allready several questions about this topic on the net allready : The solution was to do an explicit import in my module, like so : from encodings import ascii from encodings import idna This solved the problem, at least in my case. Regards, Thomas From bdesth.quelquechose at free.quelquepart.fr Wed Jun 1 16:38:00 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Jun 2005 22:38:00 +0200 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> Message-ID: <429e1745$0$28699$626a14ce@news.free.fr> Kristian Zoerhoff a ?crit : > On 1 Jun 2005 09:41:53 -0700, infidel wrote: > >>Why in the name of all that is holy and just would you need to do such >>a thing? > > > Is anyone else amused that this came from the mouth of someone named "Infidel"? I was just recovering from a ROFL attack when I noticed this too... Guess what was the result ? From xah at xahlee.org Tue Jun 21 07:32:19 2005 From: xah at xahlee.org (Xah Lee) Date: 21 Jun 2005 04:32:19 -0700 Subject: eval() in python Message-ID: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> is it possible to eval a string like the following? m=''' i0=[0,1] i1=[2,3] i2=[4,'a'] h0=[] for j0 in i0: h1=[] for j1 in i1: h2=[] for j2 in i2: h2.append(f(j0,j1,j2)) h1.append( h2[:] ) h0.append( h1[:] ) return h0''' perhaps i'm tired, but why can't i run: t='m=3' print eval(t) the doc seems to suggest that eval is only for expressions... it says uses exec for statements, but i don't seem to see a exec function? Xah xah at xahlee.org ? http://xahlee.org/ From bokr at oz.net Mon Jun 27 13:37:32 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 27 Jun 2005 17:37:32 GMT Subject: turn text lines into a list References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> <11c036grkf1d4d1@corp.supernews.com> <42c02fc2$0$20805$636a15ce@news.free.fr> Message-ID: <42c03758.352189852@news.oz.net> On 27 Jun 2005 16:56:34 GMT, "F. Petitjean" wrote: >[En-t?te "Followup-To:" positionn? ? comp.lang.python.] >Le Mon, 27 Jun 2005 14:27:28 -0000, Grant Edwards a ?crit : >> On 2005-06-27, Xah Lee wrote: >>> i have a large number of lines i want to turn into a list. >>> In perl, i can do >>> >>> @corenames=qw( >>> rb_basic_islamic >>> sq1_pentagonTile >>> sq_arc501Tile >>> sq_arc503Tile >>> ); >>> >>> use Data::Dumper; >>> print Dumper(\@corenames); >>> >>> ---------- >>> is there some shortcut to turn lines into list in Python? >> >> corenames = [ "rb_basic_islamic", >> "sq1_pentagonTile", >> "sq_arc501Tile", >> "sq_arc503Tile"] >> >Another way : (less typing of quotes) > >all_names = """ >rb_basic_islamic >sq1_pentagonTile >sq_arc501Tile >sq_arc503Tile >""" > >corenames = all_names.split() Of course, the lines better not have embedded spaces or they'll be split into several lines. For lines per se, probably I'd do corenames = """\ rb_basic_islamic sq1_pentagonTile sq_arc501Tile sq_arc503Tile """.splitlines() Note the \ to avoid a blank leading line. >>> """\ ... solid ... embedded space ... leading ... trailing ... both ... """.splitlines() ['solid', 'embedded space', ' leading', 'trailing ', ' both '] Regards, Bengt Richter From hancock at anansispaceworks.com Thu Jun 30 20:39:58 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 30 Jun 2005 19:39:58 -0500 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <42C40675.4050101@benjiyork.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1120141667.753928.40750@f14g2000cwb.googlegroups.com> <42C40675.4050101@benjiyork.com> Message-ID: <200506301939.58585.hancock@anansispaceworks.com> On Thursday 30 June 2005 09:49 am, Benji York wrote: > Graham Fawcett wrote: > > keep-your-stick-on-the-ice'ly yours, > > Is that a Red Green reference? Man, I didn't think this could get any > more off-topic. :) > > python-needs-more-duct-tape'ly yours, No silly, it's "duck typing", not duct taping! -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From flyingfred0 at gmail.com Thu Jun 9 22:55:05 2005 From: flyingfred0 at gmail.com (flyingfred0) Date: Fri, 10 Jun 2005 02:55:05 GMT Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: Renato Ramonda wrote: > Tim Roberts ha scritto: > >> Renato Ramonda wrote: >> >>> wxWidgets apps look ALMOST native on windows (combobox and similar >>> widgets are emulated, and look really bad), >> >> >> >> That just isn't true. They use the standard combo box. > > > > Then it has changed recently. Mind that most stable apps still use wx2.4 > >> wx uses "sizers" to do the same thing. Same purpose, different >> philosophy. >> I find sizers more natural, but people should certainly stick to whatever >> makes them comfortable. > > > I like sizers too, but in my experience wx apps do not use them. Are > they by chance something that came with the 2.5/2.6 development cycle? > That version is still pretty rare in real world applications. > I know sizers are in 2.4; I've been aware of them for quite some time. But it took awhile for me to learn them well and start using them religiously. Before that, I'd usually hardcoded positions because it was easier to get something done that way, but it eventually became a bitch to maintain. >>> And that's not even starting to consider the version mess: try to >>> install xCHM, Boa Constructor, aMule, VLC and some other app >>> together... instant madness. >> >> >> >> They why would you do it? gvim and wxPython do the job for me. No mess. > > > > Because i USE a chm reader. And I USE aMule, and I USE a multimedia player. > > I'm not talking about developing (don't get confused by my mention of > Boa), I'm talking about using. Only very recently wx introduced a > mechanism to keep different versions in parallel. > From d at e.f Mon Jun 13 22:36:23 2005 From: d at e.f (D H) Date: Mon, 13 Jun 2005 21:36:23 -0500 Subject: case/switch statement? In-Reply-To: References: Message-ID: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Peter Hansen wrote: > With a case statement, on the other hand, you *know* that it must be > just simple conditionals (a series of x == some_constant tests), so you > don't need to look at all the cases, just the one that interests you. Since you and Steve Holden agree that a case statement is useful, why don't you propose it for python, or add it to the wiki page for Python 3000. Here is the syntax the developers of your favorite language boo ( http://boo.codehaus.org/ ) are using: given x: when 1: ... when 2: ... otherwise: ... must-stop-hyphenating-ly y'rs From eurleif at ecritters.biz Mon Jun 20 02:56:11 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 20 Jun 2005 06:56:11 GMT Subject: Can we pass some arguments to system("cmdline")? In-Reply-To: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> References: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> Message-ID: Didier C wrote: > E.g in Perl, we can do something like: > > $dir="/home/cypher"; > > system("ls $dir"); > > Is there a way to reproduce the same thing in Python? system("ls %s" % dir) But you should really be using subprocess for security (so that if dir=="/home/foo; rm -rf /" nothing bad will happen): import subprocess subprocess.Popen(['ls', dir]) From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 29 16:42:50 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 29 Jun 2005 22:42:50 +0200 Subject: strange __call__ In-Reply-To: <1120076592.828106.301340@z14g2000cwz.googlegroups.com> References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> <1120062469.370984.130670@f14g2000cwb.googlegroups.com> <1120076592.828106.301340@z14g2000cwz.googlegroups.com> Message-ID: <3igfeaFl9iqgU1@individual.net> Rahul wrote: > If you do C = wrap(C) C no longer remains a class..it becomes a > function. Does that matter? Reinhold From Scott.Daniels at Acm.Org Tue Jun 14 11:21:49 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 14 Jun 2005 08:21:49 -0700 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42AED7B3.8060009@carmen.se> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <42AED7B3.8060009@carmen.se> Message-ID: <42aeeee1$1@nntp0.pdx.net> Magnus Lycka wrote: > It seems to me that *real* computer scientists are very rare. I suspect the analysis of algorithms people are among that group. It is intriguing to me when you can determine a lower and upper bound on the time for the best solution to a problem relatively independent of the particular solution. > Oh well, I guess it's a bit late to try to rename the Computer > Science discipline now. The best I've heard is "Informatics" -- I have a vague impression that this is a more European name for the field. --Scott David Daniels Scott.Daniels at Acm.Org From gary at modernsongs.com Wed Jun 1 09:58:38 2005 From: gary at modernsongs.com (Gary Poster) Date: Wed, 1 Jun 2005 09:58:38 -0400 Subject: Fredericksburg, VA ZPUG June 8 Message-ID: <13B00B79-3EB5-4548-BB71-A66A740891B6@modernsongs.com> Please join us June 8, 7:30-9:00 PM, for the inaugural meeting of the Fredericksburg, VA Zope and Python User Group ("ZPUG"). Tres Seaver, architect of the Zope Content Management Framework, will present. Further meetings are planned for the second Wednesday of every month. Location will be at the Zope Corporation offices. Further details below, and at http://www.zope.org/Members/poster/fxbgzpug_announce. Gary --------- Fredericksburg, VA ZPUG: second Wednesday of every month, 7:30-9:00 First meeting: June 8, 7:30. Speaker: Tres Seaver, architect of the Zope Content Management Framework (CMF). Topic: Selenium (automated cross-platform, cross-browser application browser tests, http://selenium.thoughtworks.com/index.html), as integrated with Zope 2 in Zelenium (http://www.zope.org/Members/ tseaver/Zelenium). Location: Zope Corporation offices (http://tinyurl.com/duoab or http://maps.google.com/maps?q=Zope+Corporation,+513+Prince+Edward +Street,+Fredericksburg,+VA +22401&ll=38.298600,-77.457900&spn=0.032410,0.068500&hl=en) Parking: Zope Corporation parking lot; entrance on Prince Edward Street. Future topics: As desired (and offered) by participants, within the constraints of having to do with Python. Possible topics include presentations referencing Zope 3, Zope 2, Twisted Framework, core Python topics, Python and XML, Zope Object Database (ZODB), Macintosh OS X application development with Python, etc. From thomas at eforms.co.nz Wed Jun 1 18:31:28 2005 From: thomas at eforms.co.nz (Thomas Thomas) Date: Thu, 2 Jun 2005 10:31:28 +1200 Subject: python socket error Message-ID: <00c201c566f9$a6cefcc0$bb64a8c0@eformswin> Is there any getaround for the following error .. This happens when uploading large files say>50MB.. Python version Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last): File "", line 1, in ? File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-116V_Z.py", line 87, in ? httpResult=httpUploadAsset('XXXXXX',filename,fileData) File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-116V_Z.py", line 12, in httpUploadAsset results=post_multipart(theURL,"/UploaderHttp/",fields,files); File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-116V_Z.py", line 30, in post_multipart h.send(body) File "C:\Python23\lib\httplib.py", line 579, in send self.sock.sendall(str) File "", line 1, in sendall socket.error: (10055, 'No buffer space available') Any help Thomas ----------below the code sample that i am using import os import httplib, mimetypes import os; def httpUploadAsset(serial,filename,data): _sessionID='xxxxxxx'; _baseURL='http://xxxxxx.com' fields = [('serial',serial),('sessionID',_sessionID)] file = ('file', filename, data) files = [file] protocol,theURL=_baseURL.split('http://'); results=post_multipart(theURL,"/UploaderHttp/",fields,files); print results; return results; def post_multipart(host, selector, fields, files): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page. """ content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.set_debuglevel(0) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() def encode_multipart_formdata(fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF = '\r\n' L = [] for (key, value) in fields: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: L.append('--' + BOUNDARY) L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) L.append('Content-Type: %s' % get_content_type(filename)) L.append('') L.append(value) L.append('--' + BOUNDARY + '--') L.append('') body = CRLF.join(L) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def get_content_type(filename): return mimetypes.guess_type(filename)[0] or 'application/octet-stream' def getFileData(filename): try: f = file(filename, "rb") data = f.read() f.close() except IOError: return['ERR'] return ['OK',data] filepath="c:/Documents and Settings/Administrator/Desktop/tmp/TM_A5_Bulk.pdf" #file with size >50MB fileResult=getFileData(filepath) filename='TM_A5_Bulk.pdf' fileData=None if (fileResult[0]=='OK'): fileData=fileResult[1]; httpResult=httpUploadAsset('XXXXXX',filename,fileData) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Fri Jun 24 17:51:13 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 25 Jun 2005 07:51:13 +1000 Subject: Favorite non-python language trick? In-Reply-To: <1119648577.754818.119530@z14g2000cwz.googlegroups.com> References: <1119648577.754818.119530@z14g2000cwz.googlegroups.com> Message-ID: <42BC8051.4010800@lexicon.net> James wrote: > Interesting thread ... > > 1.) Language support for ranges as in Ada/Pascal/Ruby > 1..10 rather than range(1, 10) Did you mean 1..9 or 1...10 or both or neither? Can this construct be used like this: (i+1)..n ? If not, what would you use? What is the frequency of range literals in the average piece of code? From spam.csubich+block at block.subich.spam.com Wed Jun 8 16:45:20 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 16:45:20 -0400 Subject: Annoying behaviour of the != operator In-Reply-To: <_JqdnZLLKdzIpTrfRVn-uA@powergate.ca> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <_JqdnZLLKdzIpTrfRVn-uA@powergate.ca> Message-ID: Peter Hansen wrote: > I can see only one comment that seems to describe that situation, where it refers to "IEEE 754 floating point numbers do not satisfy [== being the complement of !=]". > > (Though that may be justification enough for the feature...) To my naive eye, that possibility seems like justification for the language to not -enforce- that (not (a == b)) == (a != b), but for the vast majority of cases this is true. Perhaps the language should offer the sensible default of (!=) == (not ==) if one of them but not the other is overriden, but still allow overriding of both. This would technically break backwards compatibilty, because it changes default behavior, but I can't think of any good reason (from a python newbie perspective) for the current counterintuitive behavior to be the default. Possibly punt this to Python 3.0? From mwm at mired.org Mon Jun 13 22:51:57 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 13 Jun 2005 21:51:57 -0500 Subject: How to get/set class attributes in Python References: <0001HW.BED206D2002D2163F0407550@news.gmane.org> <0001HW.BED3BE5000197B71F0488550@news.individual.de> Message-ID: <86y89dy7jm.fsf@guru.mired.org> Kalle Anke writes: > On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote > (in article ): > >> 1) Assume the variables are of a sensible type (not >> necessarily the one you expected, though), and provide >> exception handling to catch the case where their interface >> does not match what you expect. > > The problem I have with this is that I might discover an error at runtime > instead of compile time, this means that I need to really exercise all > possible test cases to make sure that I've covered everything (which of > course is a good thing) but it would be easier to discover this at "compile > time". But static typing only catches *some* of the errors that might occur. Other errors will occur at run time even with static typing - so you need to really exercise all possible test cases to make sure you've covered everything in any case. > (note: I'm not trying to change Python, only that to me statically typing has > it advantages also) Static typing saves you some time by catching a small subset of programming errors at compile time. On the other hand, it costs you time by forcing you to declare a type for - well, everything that you're going to catch errors for. It's not clear which cost is larger. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jstroud at mbi.ucla.edu Thu Jun 30 17:00:31 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 30 Jun 2005 14:00:31 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1120164382.757002.18930@o13g2000cwo.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1120164382.757002.18930@o13g2000cwo.googlegroups.com> Message-ID: <200506301400.31995.jstroud@mbi.ucla.edu> Well--to take this as far OT as imaginable, yes I do have strange hearing problems. I have difficulty recognizing speech of any kind with my right ear. Amazing to think that this would be enhanced for British, but it would be consistent with my experience, which seems similar to yours. James On Thursday 30 June 2005 01:46 pm, Bill wrote: > James Stroud wrote: > > Frankly, I can't watch Shakespeare or movies like "the full monty" or > > "trainspotting" because I can't understand a damn word they say. British > > talk sounds like gibberish to me for the most part. > > Have you had your hearing checked recently? Seriously. I have a hearing > defect and speakers from the UK give me by far the most difficulty. > People speaking English as a second language are more understandable. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From peter at engcorp.com Fri Jun 17 08:40:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Jun 2005 08:40:47 -0400 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: Andrea Griffini wrote: > Is C++ a good first programming language ? > > BWHAHAHAHAHAHAHAHA :D > > But apparently some guru I greatly respect thinks so > (I'm not kidding, http://www.spellen.org/youcandoit/). With respect to the author, and an understanding that there is probably much that didn't go into his self-description (add "about.htm" to the above URL), it sounds as though he knows primarily, perhaps solely, C and C++, and has done relatively little serious development since he seems to have spent most of his time either teaching or writing (words, not source code). Does he even *know* any real high level languages such as Python? And the fact that he's teaching C++ instead of just C seems to go against your own theories anyway... (though I realize you weren't necessarily putting him forth as a support for your position). -Peter From jabel at plus.net Fri Jun 10 10:47:00 2005 From: jabel at plus.net (John Abel) Date: Fri, 10 Jun 2005 15:47:00 +0100 Subject: Basic questions about packages/modules. In-Reply-To: <2fdabf19.0506100638.119d604a@posting.google.com> References: <2fdabf19.0506100638.119d604a@posting.google.com> Message-ID: <42A9A7E4.6060303@plus.net> Negroup wrote: >Hi, first of all sorry for boring you with a such simple request. I'm >using Python since few days, and I like it even if I'm not yet in >confidence. I'd like to organize my programs in hierarchical >structures, thus I thought that packages could be the solution, >however I have some difficulties understanding their utilization (even >after reading chapter 6 of the tutorial, about modules). > >Now an example (silly) to clarify my doubts: > >This is the structure: >main.py >importers/ > __init__.py (empty) > importer1.py >config/ > __init__.py (empty) > parameters.py > >main.py >======= >from importers import importer1 >print importer1.display() > >importers/importer1.py >====================== >from config import parameters >def display(): > return '-' * parameters.counter > >config/parameters.py >==================== >counter = 5 > > >All works fine when I run "python main.py", while I get an error >trying to run "python importers/importer1.py": > >Traceback (most recent call last): > File "importers/importer1.py", line 1, in ? > from config import parameters >ImportError: No module named config > >Can you explain why does that happen? It prevents me to test >importer1.py alone. > >TIA, >negroup > > For your code to work, config would have to be a subdirectory under importers. Unless, config had been installed in the site-packages. J From tim.peters at gmail.com Thu Jun 23 00:11:20 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 23 Jun 2005 00:11:20 -0400 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <42BA2B05.8510740D@pauahtun.org> References: <11bh7ffsps4ea3@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> Message-ID: <1f7befae050622211154bf4f2@mail.gmail.com> [Tim Peters] ... >> Across platforms with a 754-conforming libm, the most portable way [to >> distinguish +0.0 from -0.0 in standard C] is via using atan2(!): >> >> >>> pz = 0.0 >> >>> mz = -pz >> >>> from math import atan2 >> >>> atan2(pz, pz) >> 0.0 >> >>> atan2(mz, mz) >> -3.1415926535897931 [Ivan Van Laningham] > Never fails. Tim, you gave me the best laugh of the day. Well, I try, Ivan. But lest the point be missed , 754 doesn't _want_ +0 and -0 to act differently in "almost any" way. The only good rationale I've seen for why it makes the distinction at all is in Kahan's paper "Branch Cuts for Complex Elementary Functions, or Much Ado About Nothing's Sign Bit". There are examples in that where, when working with complex numbers, you can easily stumble into getting real-world dead-wrong results if there's only one flavor of 0. And, of course, atan2 exists primarily to help convert complex numbers from rectangular to polar form. Odd bit o' trivia: following "the rules" for signed zeroes in 754 makes exponeniation c**n ambiguous, where c is a complex number with c.real == c.imag == 0.0 (but the zeroes may be signed), and n is a positive integer. The signs on the zeroes coming out can depend on the exact order in which multiplications are performed, because the underlying multiplication isn't associative despite that it's exact. I stumbled into this in the 80's when KSR's Fortran compiler failed a federal conformance test, precisely because the test did atan2 on the components of an all-zero complex raised to an integer power, and I had written one of the few 754-conforming libms at the time. They wanted 0, while my atan2 dutifully returned -pi. I haven't had much personal love for 754 esoterica since then ... From onurb at xiludom.gro Tue Jun 7 08:07:09 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 07 Jun 2005 14:07:09 +0200 Subject: If - Or statements In-Reply-To: References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> <42a40590$0$23331$636a15ce@news.free.fr> Message-ID: <42a58dee$0$24376$626a14ce@news.free.fr> Steven Bethard wrote: > bruno modulix wrote: (snip) >> ext = os.path.splitext(filename) > > Check the docs[1]. This should probably read: > _, ext = os.path.splitext(filename) Of course. Au temps pour moi. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From http Mon Jun 6 00:04:40 2005 From: http (Paul Rubin) Date: 05 Jun 2005 21:04:40 -0700 Subject: Tkinter: How can I update an image display? References: Message-ID: <7x4qcc2krr.fsf@ruckus.brouhaha.com> Terry Carroll writes: > I trimmed it down to a basic app indicating the problem and the code > is at the end of this message. It should display the three listed > sample images, one after another. > > The thing is, if I uncomment the raw_input call, it works. But I > don't want to have to hit ENTER after each image. Try using root.update()? From deets at web.de Wed Jun 22 19:59:49 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 23 Jun 2005 01:59:49 +0200 Subject: Is this a bug? I don't know where to start In-Reply-To: References: Message-ID: <3hucbmFiv5tjU1@uni-berlin.de> jim bardin wrote: > Is this a python bug, or do i not understand > something? > > http://www.linuxquestions.org/questions/showthread.php?s=&threadid=336118 > > It seems to me that this should output each value > once, but i get some seemingly random duplicates. Your targets contains duplicates - and these produce the problem. And as >>> print len(all) == len(set(all)) False shows your alleged " i checked the output of the combination generator and they're all unique values." is obvously wrong. Doing this targets=list(set([97,101,139,41,37,31,29,89,23,19,8,13,131,19,73,97,19,139,79,67,61,17,113,127])) as first line solves the problem. Diez From thomasbartkus at comcast.net Fri Jun 10 15:49:11 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 10 Jun 2005 14:49:11 -0500 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: "flyingfred0" wrote in message news:8B6qe.1742$pa3.909 at newsread2.news.atl.earthlink.net... > A small software team (developers, leads and even the manager when he's > had time) has been using (wx)Python/PostgreSQL for over 2 years and > developed a successful 1.0 release of a client/server product. > > A marketing/product manager has brought in additional management and > "architecture" experts to propose moving the entire thing to a Java > (application server) platform for the next release. They want a > "scalable, enterprise solution" (though they don't really know what that > means) and are going crazy throwing around the Java buzzwords (not to > mention XML). > > The developers (including myself) are growing uneasy; the management is > continuing to push their requirements and ignore the engineers. I think > there's still hope, but I'm at a loss for ideas beyond pointing out the > success stories of Python and Zope and language comparisons between > Python and Java. > > What experiences have those in the Python community had in these kinds > of situations? Sigh! > The developers (including myself) are growing uneasy; the management is > continuing to push their requirements and ignore the engineers. No - they are not pushing "requirements" here. They are trying to specify the tools that must be used in order to achieve those requirements. Sort of like me specifying the brand name and type of tools the repair shop must use when they replace my alternator. Well - not *quite* like that since I don't enjoy the power of a true employer/employee relationship with my repair shop. But you get the picture. It's a given that management has no way to reasonably evaluate on the technical merits. However, there is one legitimate reason they might want to do this. It is a non-technical yet nevertheless reasonable consideration. Management needs to know they have a reliable labor pool to draw upon for replacements. If that "small software team" decides to jump ship (or asks for more $, or already makes enough $ to be attractive targets for replacement) - would they be able hire the replacement expertise to carry on? Management is *always* looking to lose the high priced creative geniuses who brought them to the party. I know this from years as an independent consultant talking to those managers. I can't tell you how many times they were simply looking to replace the now highly paid guru(s) with younger/lower cost and more recently - offshored labor. That, my friend, is the real reason behind the "Java" buzzword. If that's what your up against, I'm sorry to say that there are simply hoards of Java underemployeds out there ready to flood human resources with resumes. Worse - there are hoards of underbidding (lying? scumsucking?) contractors with dozens of "Java" experts on the bench and no one with Python experience. I gaurantee that the likes of these are tripping over one another to get your employers attention. If this is the case, then management throws up blather like "scalable" and "enterprise solution" when they really mean they would like to reduce the cost and increase the reliability of the labor force available to develop and maintain the system. If *thats* what's bothering you bunky - I'm sorry to tell you that I am short on solutions. BUT understanding the problem is the first step on the path to a solution :-) Thomas Bartkus From grante at visi.com Wed Jun 29 10:05:44 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Jun 2005 14:05:44 -0000 Subject: python broadcast socket References: Message-ID: <11c5alob44cc3da@corp.supernews.com> On 2005-06-29, wrote: > I'm sort of new to both Python and socket programming so I > appologize ahead of time if this is a dumb question. I have > found that the following code works on windows but on linux I > get an exception. > > import socket > s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) > s.connect( ( '', 1617 ) ) > > The exception I get is: > > socket.error: (13, 'permission denied') Sending broadcast packets is a dangerous thing and not something a normal user should be able to do. In a real OS, it's a restricted operation and you need special privledges. Under Linux, you need to be root to send a broadcase packet. -- Grant Edwards grante Yow! How's the wife? Is at she at home enjoying visi.com capitalism? From newsgroups at jhrothjr.com Sat Jun 18 09:54:15 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 18 Jun 2005 07:54:15 -0600 Subject: Why is there no instancemethod builtin? References: Message-ID: <11b89s8rr096kaf@news.supernews.com> "John Reese" wrote in message news:slrndb6ct5.pho.jtr at ofb.net... > Why hello there ha ha. > > I have got in the habit of testing the types of variables with > isinstance and the builtin type names instead of using the types > module, as was the style back around Python 2.1. That is, rather than > > if type(x) == types.ListType: > > I now do: > > if isinstance(x, list): you need _both_ isinstance and the types module to do a correct check for any string type: isinstance(fubar, types.StringTypes). That's because both string and unicode are subtypes of one base. > It is my understanding that this is what people do nowadays. One > problem I have, though, is that not all type names are available as > builtins. Just looking through the types declared in types, the > following are builtins: > > bool, buffer, complex, dict, file, float, list, long, > object, slice, str, tuple, type, unicode, xrange, NoneType, > NotImplementedType > > And the following are not: > > dictproxy, ellipsis, frame, function, instancemethod, module, > traceback, instancemethod, NoneType, NotImplementedType You need to do your homework better. You have, for example NoneType and NotImplementedType in both lists. The basic answer to your question is that the types in builtins are there because they have uses other than type checks. Being useful for type checks is not the criterion for being in builtins. That's the function of the types module. The other point to be made here is that, in most cases, type checks are a design smell. That's not always true, but it's the first thing to check when you see one. John Roth From carroll at nospam-tjc.com Sun Jun 5 23:46:27 2005 From: carroll at nospam-tjc.com (Terry Carroll) Date: Sun, 05 Jun 2005 20:46:27 -0700 Subject: Tkinter: How can I update an image display? References: Message-ID: <4lh7a1d305tkq3auacls1a9jbp4b1ckcdg@4ax.com> On Sun, 05 Jun 2005 20:39:04 -0700, Terry Carroll wrote: >The thing is, if I uncomment the raw_input call, it works. But I >don't want to have to hit ENTER after each image. And the, just to be confusing, I posted the uncommented version. To make my example more consistent with my post, I should have said that, when the raw_input call is commented out, it no longer works. From daniel at dittmar.net Tue Jun 14 18:16:12 2005 From: daniel at dittmar.net (Daniel Dittmar) Date: Wed, 15 Jun 2005 00:16:12 +0200 Subject: MySQLDBAPI In-Reply-To: References: <2tqln2-6c3.ln1@news.interplanet.it> <312cfe2b05061408481a3e7de0@mail.gmail.com> Message-ID: <3h939qFfvmjfU1@uni-berlin.de> Gregory Pi?ero wrote: > building '_mysql' extension > gcc -pthread -shared build/temp.linux-i686-2.4/_mysql.o -lz > -lmysqlclient_r -o build/lib.linux-i686-2.4/_mysql.so > /usr/bin/ld: cannot find -lmysqlclient_r > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 Now search for mysqlclient_r.so or mysqlclient_r.a (probably in rpmmysql/usr/lib. A mysqlclient.so (without _r meaning without support for threading) will do as well if you use Python as a CGI program. Now enter the directory where you found mysqlclient to setup.py library_dirs = [''] If you found both .so and .a, rm the .so. The linker will then link the static library .a and you can copy the resulting _mysql.so everywhere. If there is only an .so, be sure to copy the mysqlclient*.so to the server together with _mysql.so. You probably have to inspect the environment in your CGI run for LD_LIBRARY_PATH for a directory where you can copy mysqlclient*.so. (That's why it is easier to use the static library) Daniel From lycka at carmen.se Fri Jun 10 06:26:38 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 10 Jun 2005 12:26:38 +0200 Subject: different time tuple format In-Reply-To: References: Message-ID: Maksim Kasimov wrote: > hi all, sorry if i'm reposting > > why time.strptime and time.localtime returns tuple with different DST (9 > item of the tuple)? I've been bitten by the quirks in the time modules so many times that I would advice against using it for any date handling. It's ok for time measurement as long as you understand the differences between time.clock and time.time on your particular platform. You should be aware that it's just a thin wrapper around the c libs, and they seem to disagree wildly among platforms on how things should be done. On NT 4 for instance, the C time libs was a few weeks off concerning when DST starts in Europe (but the win32 API was correct), time zone names vary among platforms etc. There is an inverse of localtime() in mktime(), but no inverse of gmtime() etc. Yuk! I would suggest that you either update Python to 2.4 (or 2.3) and use the datetime module, or that you get mxDateTime if you are stuck with 2.2. From mauriceling at acm.org Wed Jun 15 21:51:39 2005 From: mauriceling at acm.org (Maurice LING) Date: Thu, 16 Jun 2005 11:51:39 +1000 Subject: UML to Python/Java code generation Message-ID: Hi, Is there any UML tools that is able to take UML and generate Python codes? Cheers Maurice From lycka at carmen.se Fri Jun 3 09:24:16 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 03 Jun 2005 15:24:16 +0200 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> <0cadndgTMNDJtQLfRVn-gQ@telcove.net> Message-ID: Skip Montanaro wrote: > Glade is fine for building Gtk user interfaces. I have no idea if there are > similar tools for other widget sets, though I wouldn't be surprised if such > tools existed. Once the GUI is fairly stable, most of the development after > that occurs in the underlying functional part of the code (at least in my > recent experience). For that, no amount of Glade slinging will help. Here are a few... http://wxglade.sourceforge.net/ http://boa-constructor.sourceforge.net/ http://spe.pycs.net/ http://www.roebling.de/ http://thekompany.com/products/blackadder/ There's also something inspired by Visual FoxPro... http://www.dabodev.com/ From dalke at dalkescientific.com Tue Jun 14 15:12:42 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 14 Jun 2005 19:12:42 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Peter Maas wrote: > Yes, but what did you notice first when you were a child - plants > or molecules? I imagine little Andrew in the kindergarten fascinated > by molecules and suddenly shouting "Hey, we can make plants out of > these little thingies!" ;) One of the first science books that really intrigued me was a book on stars I read in 1st or 2nd grade. As I mentioned, I didn't understand the science of biology until I was in college. Teaching kids is different than teaching adults. The latter can often take bigger steps and start from a sound understanding of logical and intuitive thought. "Simple" for an adult is different than for a child. Andrew dalke at dalkescientific.com From ncoghlan at gmail.com Thu Jun 23 07:02:06 2005 From: ncoghlan at gmail.com (NickC) Date: 23 Jun 2005 04:02:06 -0700 Subject: case/switch statement? References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Message-ID: <1119524525.995376.128940@f14g2000cwb.googlegroups.com> Andrew Durdin wrote: > In this case the dictionary is obviously a better and clearer choice. > I've generally found for other circumstances where I've used switch > statements that the code ends up more readable if it's reorganised so > that the switch statements are all of the form above, or are > eliminated entirely--so I don't miss a switch/case statement in > Python. I find the lack of a switch statement encourages me to write data-driven programs (which is a god-send when I have to enhance them later to deal with additional cases). The thing I love most about Python is the fact that callables can be slung around at run-time, just like any other object. So, I set up (usually for command-line options) mappings from options to callables which define "how to perform action x". Then as the options are translated, I query the lookup tables, and store the results in appropriately named variables (e.g "create_connection", "connect_link" for a program I use to test serial data circuits with a variety of connections and links running over different hardware). The main body of the program is then comparatively trivial, because it just calls methods whose names describe (in a high-level way) what they do. A new connection or link type can be handled just by adding an entry to the appropriate dictionary. Basically, it's the GoF Strategy pattern, without all the pain that's required to set it up in static languages. Cheers, Nick. From lambacck at gmail.com Sun Jun 5 21:06:29 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Sun, 5 Jun 2005 21:06:29 -0400 Subject: GUI builders considered harmful (Was: anygui, anydb, any opinions?) In-Reply-To: <86fyvwa91z.fsf_-_@guru.mired.org> References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> <86fyvwa91z.fsf_-_@guru.mired.org> Message-ID: I think you missed looking at several GUI builders. I have not used a GUI builder in 5 years that had you nail down positions. Swing(for Java), GTK, Qt, and wxWidgets(to a lesser degree) all use a sizer metaphore. You lay out he sizers and put your widgets in various sizer layouts. This means that the scaling you speak of above, just works for you. Accordingly GUI builders for these toolkits work within that model(look at Glade for GTK and wxGlade for wxWidgets). I think you need to step out of the age of Motif and MFCs and look at what modern toolkits and GUI designers have to offer before you start in on a rant. -Chris On 6/5/05, Mike Meyer wrote: > "Thomas Bartkus" writes: > > "Paul Rubin" wrote in message > >> Are we talking about a drag-and-drop GUI builder? > > I am! > [...] > > I happen to be one - and I *know* I'm not alone - who thinks that building > > user interfaces is way too difficult and way too important. It is > > particularly frustrating in that we do seem to be moving backwards in this > > department. > > "What GUI builder should I use", or similar, is a common question on > c.l.python. I'm a curmudgeon, and don't like GUI builders - so I avoid > them. While normally that wouldn't cause me to encourage others to > avoid GUI builders, I think they have a worse problem: they encourage > the delivery of applications without flexible, robust user > interfaces. In short, the help produce inferior applications. While > this isn't strictly a python issue, c.l.python is where I run into it > - so I'm bringing it up here. > > Now, I'm not an expert on GUIs, GUI toolkits, or GUI builders. I've > used some of each, and draw my conclusions from that admittedly small > sampling. Possibly there are other samples that don't have the > problems I describe. Part of the point of posting this is to expose > these thoughts to others, and find out what I've overlooked. I'll > return to these points where appropriate. > > What the user deserves. > > I'm going to take a side trip into what constitutes a robust, flexible > user interface - which is what I believe the user deserves. Please > bear with me. By robust, I mean the user interface should adopt to the > environment it's being run in. Windows that don't fit on the screen > are simply unacceptable - but all to common if you use a very small > screen resolution. By flexible, I man the user should be able to > adjust the UI to suit their viewing conditions - the DPI on the > screen, the viewing distance, and their possibly aging eyesight. > > I use two systems with graphical interfaces, and both are a bit out of > the ordinary. You might even call them extreme. One is a 1600x1200 > desktop on a 21" monitor viewed from about 18" away. The other is a > 640x480 desktop on a 53" monitor viewed from about 10' away. Even > those these are on opposite sides of "normal" users systems, they both > suffer from the same problem - out of the box applications have UI > elements that are unreadably small. > > The obvious solution would be for the system to detect all these > environmental factors, and scale the applications > accordingly. However, things like viewing distance and the quality of > my eyesight are hard to detect automatically, and it would be a pain > to have to enter all those things manually. Since the end result of > all these is a single factor - a UI scale factor - a system wide knob > to scale applications would seem to be the solution. > > Note that this is *not* an easy thing to do. Anyone who's tried > scaling bit-mapped fonts will tell you you can't simply scale something > and expect it to look good. Scalable fonts have "hints" and other > goodies in them so they look good as you scale the fonts up/down. This > may be why, but most windowing systems don't seem to do provide a > global UI scale knob. X certainly doesn't. Windows has a limited > capability to scale fonts system-wide, but it doesn't work very > well. OSX seems to have a system-wide display DPI setting one can play > with, but it's not clear how well that works. NeWS and NeXT could > probably do this, but would seem to have a negligible to nonexistent > user bases. rio seems capable, but the typical rio UI is ugly even by > my admittedly low standards. > > Failing the single system-wide knob, a flexible application should > have allow the user to scale the application with a single knob. This > is hard to do with modern GUI toolkits. I do it by using text for > imagery in the UI, and having a scaling factor that is applied to the > font sizes. While I prefer text to graphics for UI elements, that's a > rant for a different time. I'll concede that such an interface is > probably unacceptable on a modern commercial application - users now > expect graphics. But how many GUI toolkits let you use a scalable > graphics format (SVG, PS, etc) for images in the UI? My predilections > have kept me from looking closely, but I certainly don't recall seeing > any in the GUI toolkits I've looked at. > > I claim it's obvious from this what's wrong with GUI builders. But I > want to look at what I, as a developer, want from GUI development > tools before going into details. > > What the developer wants. > > Ok, what I mean is what *I* want. But I don't think I'm that unusual, > so I'm going to generalize to other developers as well. I'll point out > what has to be different for this generalization to fail. > > First, I'm not a graphics designer. While I've studied page layout and > typographical design, and read Tufte's books on design, I'm a *long* > way from being a good graphics designer. I know even less about the > field of human-computer interactions. Hopefully, a good GUI library > will have had people on the development team who do know something > about these fields. In this - the desirable - case, the library should > have more knowledge about good UI design than I happen to posses. > > Given that, the more I can depend on the library to do for me - the > less I have to specify - the more likely I am to produce a good UI > with that library. Conversely, the more I have to specify in the GUI > development process, the more likely I am to screw things up. I claim > this statement should hold for most developers, unless they happen to > be experts in the fields of graphics design or human-computer > interactions. > > What's wrong with GUI builders. > > Ok, *now* we're ready to deal with GUI builders. > > The first, and most obvious, thing that GUI builders do is force the > developer to specify an exact position - if not size - for the > graphical elements of the UI. Better GUI libraries don't do > that. Instead they let the developer specify the position as part of > the overall structure, say as "the third button in the second toolbar > from the top", or "one of two buttons in a toolbar running across the > bottom of the window". This latter allows the knowledge of the library > designers to dominate the design, hopefully producing a better UI than > the you get from your typical software developer. > > The GUI builder might provide an advantage if it allowed the GUI > design to be cleanly separated from the underlying code, so that a > specialist in UI design could do the graphics design, and then the > developer could come and add the underlying code. However, the GUI > builders I've dealt with require specifying names for the various > elements of the UI, which names should make sense in both > environments. This would seem to defeat such a split design, but I've > never tried it, so I can't say for sure. > > Further, look at the kind of interface the GUI builder gives you. The > position of all the elements are nailed down. This makes it hard for > the GUI to adopt to the extremes of display environments that you find > in the wild. The GUI builders I've used made it hard, if not > impossible, to build an application that can scale the GUI to meet the > users needs. In other words, the GUI builder helps build applications > without flexible, robust user interfaces that are inferior to what can > be built using a GUI library. > > Typically, I don't find a GUI builder that much faster than a good GUI > library. If I have to specify pixel positing for elements, the builder > will be a win, but if not, then not. So I haven't examined all the GUI > builders in depth. Maybe there's one out there that will let the > application developer scale the GUI when the application is invoked, > and will re-arrange elements of the GUI so they fit on the screen > properly. If so, I'd love to hear about it. > > Thank you, > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From bartekgorny at interia.pl Thu Jun 2 10:46:35 2005 From: bartekgorny at interia.pl (Taki Jeden) Date: Thu, 02 Jun 2005 16:46:35 +0200 Subject: [python-gtk] problem with multiple inheritance Message-ID: Hi I'm trying to install a certain python program which uses gtk, and the following line: class view_tree_model(gtk.GenericTreeModel,gtk.TreeSortable): raises a "TypeError: multiple bases have instance lay-out conflict" Is this a bug in gtk, or python-gtk, or something? I know of people who run this program, so I guess sthg must be wrong in my system. I have Mdk 10.0, and in particular: pygtk2.0-wrapper-2.0.0-2mdk libgtk+1.2-1.2.10-38mdk gtk+2.0-2.4.9-9mdk pygtk2.0-2.0.0-2mdk libgtk+2.0_0-2.4.9-9mdk pygtk2.0-libglade-2.0.0-2mdk gtkdialogs-2.1-1mdk gtk-engines-0.12-8mdk Anybody can help? Thx Bartek -- Zamiast sensownej sygnatury...: | http://www.safetycam.pl | http://www.bpcc.org.pl/en,0,0.html | http://www.spoko.neostrada.pl | http://www.gorny.najlepsze.pl/imiona From max at alcyone.com Sun Jun 5 13:28:48 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 05 Jun 2005 10:28:48 -0700 Subject: method = Klass.othermethod considered PITA In-Reply-To: References: <87oeallp44.fsf@pobox.com> <6qmdnR7ry4wF0D_fRVn-hA@speakeasy.net> Message-ID: <5bqdnUeNoYXMqz7fRVn-gw@speakeasy.net> Steven Bethard wrote: > Well if you want these to work with subclasses that change verb_hello to > do something else, one option is to write a simple decorator, and then > your lines above become something like: Note I was just giving a use case for the general construct, not necessarily a use case for the pseudofeature the original poster was requesting. In my particular case, there isn't much need to make sure things are properly overridden in subclasses, since functionality tends to get added, rather than modified. (The "Why would you want to do that?" question was asked before he went on to show what wasn't working for him.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis To understand is to forgive, even oneself. -- Alexander Chase From martin.witte at gmail.com Tue Jun 7 14:55:07 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 7 Jun 2005 11:55:07 -0700 Subject: different time tuple format In-Reply-To: References: Message-ID: <1118170507.813276.84570@o13g2000cwo.googlegroups.com> http://docs.python.org/lib/module-time.html tells us the last element is the DST flag, on your computer that applies for localtime(). To get this with strptime() you have to tweak the %Z formatter - this is platform specific. From kay.schluehr at gmx.net Wed Jun 1 13:24:19 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Jun 2005 10:24:19 -0700 Subject: What's wrong with Zope 3 ? In-Reply-To: References: <1117581035.584193.310060@g47g2000cwa.googlegroups.com> Message-ID: <1117646659.949604.308920@z14g2000cwz.googlegroups.com> Wolfram Kraus wrote: > Kay Schluehr wrote: > > The last downloadable release is from november 2004. The Windows > > installer is configured for Python 2.3(!). The Zope.org main page > > announces Zope 2.8 beta 2. Is it stillborn? > > > > Kay > > > What you see is not Zope 3, it is Zope X 3. To quote from the X3 > information page: "Zope X3 3.0 is for developers. If you are expecting > an end-user application, this is not for you." Yes I noticed this almost 8 months ago, read a bit of the documentation and articles published that time, regarded it as interesting and considered it for future development. But since then absolutely nothing happened. No project plan, no time-schedule, no subsequent releases. > The current stable brance is Zope2.X If you want to incorporate some > functionalty from X3 in Zope 2.X, do a search for "Five" No, I do not want to migrate components from a new major release backwards, as well as I do not want to migrate applications from WinXP to Win98. This seems to be the wrong development process direction. Regards, Kay From steven.bethard at gmail.com Sat Jun 4 17:30:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 15:30:48 -0600 Subject: how to get name of function from within function? In-Reply-To: References: <42a17a49$1_1@newspeer2.tds.net> Message-ID: Christopher J. Bottaro wrote: > Kent Johnson wrote: >>class C(object): >> @in_try >> def func_a(self): >> print "func_a" >> >> @in_try >> def func_b(self): >> print "func_b" >> raise Exception >> >>You could probably create a metaclass to apply the wrappers automatically >>but I like having it explicit as above. > > Another good solution, thank you. Maybe a reason to upgrade to 2.4...=) If you can't upgrade, you can write Kent's code like: class C(object): def func_a(self): print "func_a" func_a = in_try(func_a) def func_b(self): print "func_b" raise Exception func_b = in_try(func_b) STeVe From kent37 at tds.net Wed Jun 22 17:59:32 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Jun 2005 17:59:32 -0400 Subject: import search path In-Reply-To: <86acli13kh.fsf@guru.mired.org> References: <86acli13kh.fsf@guru.mired.org> Message-ID: <42b9dea7$1_1@newspeer2.tds.net> Mike Meyer wrote: > "SHELTRAW, DANIEL" writes: >>If a Python program has an import statement like: >> >>import FFT >> >>how do I determine the path to the imported file? > > > guru% python > Python 2.4.1 (#2, Apr 25 2005, 21:42:44) > [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5 > Type "help", "copyright", "credits" or "license" for more information. > py> import FFT > py> import sys > py> sys.modules['FFT'].__file__ > '/usr/opt/lib/python2.4/site-packages/Numeric/FFT/__init__.pyc' No need for the detour through sys: >>> import FFT >>> FFT.__file__ 'C:\\Python24\\lib\\site-packages\\Numeric\\FFT\\__init__.pyc' Kent From UNIEMFXHWQZB at spammotel.com Mon Jun 27 23:16:12 2005 From: UNIEMFXHWQZB at spammotel.com (BORT) Date: 27 Jun 2005 20:16:12 -0700 Subject: Which kid's beginners programming - Python or Forth? Message-ID: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Please forgive me if this is TOO newbie-ish. I am toying with the idea of teaching my ten year old a little about programming. I started my search with something like "best FREE programming language for kids." After MUCH clicking and high-level scanning, I am looking at Python and Forth. Both have advocates that say each is a great approach to learning computers. My programming classes were a long, long time ago in a land far, far away. My programming muscles, which were never truly developed, have atrophied even so. That said, I want to learn this as we go. The PROCESS of research and using net resources for a self-learning adventure is almost as much of the goal as learning a programming skill. That said, a good learning goal for my kid would be to create a spelling tutor for his little brother. My (simple) vision would be: 1. an input file of this week's word list 2. use a free text-to-speech engine to call out one word at a time 3. in turn, monitor each key press as a particular word is being typed, beeping on an incorrect keystroke and going to the next word if correct I don't care if it takes a year or two to get to this level, I just want a vehicle that will take us there. I told my son, who wants to learn how to compute probabilities, that we have to start with some boring stuff so we can learn how to do the cool stuff. Adding and subtracting aren't really fun, but figuring odds on rolling dice IS fun. Learning to program will be kind of like that. He accepted that explantion. So, that said... In ~simplest~ terms for the stated goal -- Forth or Python? ...the goal is NOT the spelling tutor... it is learning how to use a tool to solve a problem. I am asking which tool is more suited to an otherwise arbitrary direction of "spelling tutor program." [NOTE: This is not a troll. I'm geting ready to bark up a tree and I prefer to avoid the wrong one. I am cross-posting.] Thanks From jatinder at textualanalytics.com Mon Jun 6 01:18:00 2005 From: jatinder at textualanalytics.com (Jatinder Singh) Date: Mon, 6 Jun 2005 00:18:00 -0500 Subject: No subject In-Reply-To: References: <1117875121.42a16bb150ac2@mailbox.textualanalytics.com> Message-ID: <1118035080.42a3dc88558e4@mailbox.textualanalytics.com> I am reading a only. But what if I want read write and execute that file. -- Regards, Jatinder Singh ? Everyone needs to be loved... especially when they do not deserve it.? XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX Quoting Tiago St?rmer Daitx : > That depends on what "using" a file means. You could check the thread > "executing a command" ( > http://mail.python.org/pipermail/python-list/2005-June/283963.html) and see > if there's something related there, otherwise it would help if you could > post what exactly you are trying to do (execute a file, open a file, write > into a file, etc). > > Regards, > Tiago S Daitx > > On 6/4/05, Jatinder Singh wrote: > > > > Hi guys > > I am working in a complex directory structure. I want to use a file (not > > .py) > > which is in some other directory. I couldn't do it.but if I copy the file > > in > > the same directory then it is working fine. Can anybody guide me how and > > where > > to add the path of the file. I have tried it with sys.path but it is not > > for > > that. > > > > > > -- > > Regards, > > Jatinder Singh > > > > " Everyone needs to be loved... especially when they do not deserve it." > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From bokr at oz.net Sun Jun 26 18:48:14 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 22:48:14 GMT Subject: Rebindings [was Re: Favorite non-python language trick?] References: <42bdcd82.194023771@news.oz.net> Message-ID: <42bf2aa4.283401449@news.oz.net> On Sun, 26 Jun 2005 14:36:42 +1000, Steven D'Aprano wrote: >On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote: > >>>Using := and = for assignment and equality is precisely as stupid as using >>>= and == for assignment and equality. Perhaps less stupid: why do we use >>>== for equals, but not ++ for plus and -- for minus? >>> >> I agree, but I think := would be nice in python for RE-binding an existing >> binding, wherever it is seen from the local context. Thus you could >> write >> >> def foo(): x:=123 oops, for below example, needs global declaration def foo(): global x x:=123 #note that x:=123 searches outward through nested scopes, #not including globals unless explicitly declared, whereas # x=456 would always {re}bind the global x, as usual with a global x declared. >> >> and >> x = 456 >> def bar(): >> x = 789 >> foo() # finds and rebinds local x >> print x >> bar() # -> 123 >> print x # -> 456 >> foo() # finds and rebinds the global x oops, not so, unless foo has correction above >> print x # -> 123 >> >> but >> del x >> foo() #-> NameError exception, can't find any x to rebind >> >> hm, wandered a bit OT there, ;-/ > >Given how much the use of global variables are discouraged, is it a >good idea to allow even more inter-namespace interactions? > I forgot some of my previous thoughts on this. It's not as wild as it appears ;-) I forgot to mention that of course a symbol found in __builtins__ by way of the usual default lookup should not be rebound. And only globals explicitly declared should be rebound (error in code above, since foo doesn't have global x). So that limits it to the local scope and nested scopes and declared globals not preempted by nearer nested scope variable names. This is motivated by currently not being able to rebind a closure variable in a nested scope, and the requirement of pre-existence within a limited range of namespaces that can (I think ;-) be statically analyzed for is meant to prevent new accidental collision problems. Regards, Bengt Richter From kveretennicov at gmail.com Thu Jun 23 19:07:13 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Fri, 24 Jun 2005 01:07:13 +0200 Subject: string capitalize sentence In-Reply-To: References: Message-ID: <4660fe300506231607796a4c2f@mail.gmail.com> On 6/24/05, dimitri pater wrote: > a = 'harry is a strange guy. so is his sister, but at least she is not a > guy. i am.' > b = a.replace('. ', '.') > splitlist = b.split('.') > newlist = [] > for i in range(len(splitlist)): > i = ''.join(splitlist[i].capitalize() + '.' > newlist.append(i) > cap = ' '.join(newlist).replace(' .', '') > print cap A simpler version would be: >>> s = 'harry is a strange guy. so is his sister, but at least she is not a guy . i am.' >>> a = s.split('. ') # you can split at multicharacter strings >>> b = (x.capitalize() for x in a) # you can use generator expressions to generate lists >>> '. '.join(b) 'Harry is a strange guy. So is his sister, but at least she is not a guy. I am.' > it doesn't work with: > is harry a strange guy? so is his sister, but at least she is not a guy. i > am. I believe you'll need re.split to accomplish that. Regards, - kv From venkatasubramanian at gmail.com Sun Jun 5 13:14:01 2005 From: venkatasubramanian at gmail.com (venkata subramanian) Date: Sun, 5 Jun 2005 22:44:01 +0530 Subject: If - Or statements Message-ID: I'm sorry if this mail (also) sidetracks the primary theme of this thread. But, it was a moment of "shock and awe" seeing the use of list for checking among multiple options ... which is usually done using a name=opt1 or name=op2 etc., I started as a C programmer and hence, that style of thinking has stuck with me for this particular case( and now, i feel like banging my head on the wall for times i have not used the "list like multiple option" when possible(bang, bang)). It just reminds me that the most important thing about learning a language is also to learn its style and "paradigm" and not just its syntax and semantics. Or one might end up wrenching in "C-like-thinking" into a python program where it might not look necessarily pretty. Also, I strongly feel that one can get acquainted to the style and "paradigm" of a language only by reading the works of better coders. From jmeile at hotmail.com Wed Jun 8 12:52:44 2005 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 08 Jun 2005 18:52:44 +0200 Subject: how to export data from ZODB to text files In-Reply-To: References: Message-ID: <42A7225C.6030506@hotmail.com> Hi Lukasz, > Yes, I'm traing to escape from Zope-land, to be more clarify I want to > migrate from Plone to PHP Application, which uses MySQL database > engine, so I have to move all data from ZODB to MySQL. I suppose that > python script shouldn`t be so complex. I need just iterate ZODB and > write attributes like "Intro", "Body" of article to file for example. > I need export Plone content hierarchy like > > > Home > | > | - - - Folder 1 (Title, Intro, Body) > | | - - - Article (Title, Intro, Body) > | > | - - - Folder 2 (Title, Intro, Body) I haven't done that with Plone, but with CMF, which is the base of Plone. So, I guess it would be almost the same. You even don't need the product Peter suggested; you could do a python script inside your plone site, which searches all the objects you want and print it in form of a pipe '|' delimited list. Then, once you define your tables in mysql, you can import the data by copying the output of your script and saving it into a text file. This is how my script looks like: catalog=context.portal_catalog jobs=catalog( { 'meta_type' : 'Internship' } ) OID = 1 for metaJob in jobs: jobData=catalog.getobject(metaJob.data_record_id_) print "%i|%s|%s|%s|%s|%s|%s|%s|" % \ (OID, jobData.companyName, jobData.companyVision, jobData.description, jobData.positionOffered, jobData.jobProfile, jobData.contact, jobData.country) OID += 1 return printed Off course, this only work assuming that your fields aren't files like images or PDFs. Regards, Josef From hancock at anansispaceworks.com Wed Jun 29 22:37:58 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 29 Jun 2005 21:37:58 -0500 Subject: Modules for inclusion in standard library? In-Reply-To: <8c7f10c605062902556b1ed5af@mail.gmail.com> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <8c7f10c605062902556b1ed5af@mail.gmail.com> Message-ID: <200506292137.58724.hancock@anansispaceworks.com> On Wednesday 29 June 2005 04:55 am, Simon Brunning wrote: > On 6/28/05, John Roth wrote: > > I'd definitely like to see ctypes. I can agree with the segfault > > issue, but I think that some design work would eliminate that. > > I'm not sure that it would. Ctypes allows you, as one colleague > memorably put it, to "poke the operating system with a stick". You are > always going to be able to use ctypes to provoke spectacular crashes > of the kind that you can never get with 'ordinary' Python. Gosh, I didn't know or care about ctypes, but now I'm interested! ;-D -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From benjamin.scott at gmail.com Wed Jun 1 13:31:00 2005 From: benjamin.scott at gmail.com (benjamin.scott at gmail.com) Date: 1 Jun 2005 10:31:00 -0700 Subject: PyTables Error: ...import * Message-ID: <1117647060.843928.286740@f14g2000cwb.googlegroups.com> Hello, I am using an XP box and Python 2.3 (Enthought Edition). I am getting the same error with both of the .exe's listed on sourceforge: tables-1.0.win32-py2.3.exe tables-1.0.LB.win32-py2.3.exe Note that the installation seems to go fine. Although, when I run the test_all.py file it seems to fall over due to references to numarray; I am using Numeric. I am trying to follow the PyTables User Guide: http://pytables.sourceforge.net/html-doc/ Per installation instructions I copied the 3 prereq files as noted here: http://pytables.sourceforge.net/html-doc/x420.html#subsection2.2.1 I am getting an error in the following section: http://pytables.sourceforge.net/html-doc/c474.html#subsection3.1.1 In particular, "from tables import *" gives the following error: Traceback (most recent call last): File "", line 1, in -toplevel- from tables import * File "...\site-packages\tables\__init__.py", line 33, in -toplevel- from tables.hdf5Extension import\ ImportError: No module named hdf5Extension Note that the only file with the name "hdf5Extension" in the "...\site-packages\tables\" directory has the extension ".pyd", not ".py" or ".pyc". Suggestions? Thanks in advance, -Ben From fuzzyman at gmail.com Tue Jun 7 04:02:23 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 7 Jun 2005 01:02:23 -0700 Subject: help with sending mail in Program In-Reply-To: References: Message-ID: <1118129698.948140.58340@f14g2000cwb.googlegroups.com> Ivan Shevanski wrote: > Hey i'm new here and relatively new to python. I've made a few small > programs and now I'm making a program for my friends that at the end has a > feedback form. I want to send the feedback back to my email adress. I know > I should use the SMTP module and I have figured out how to send with it, but > I can't figure out how to include my variables in it, such as the questions > I ask them. Can someone explain this to me? > -Ivan > If you look at the cgiutils module at : http://www.voidspace.org.uk/python/recipebook.shtml It contains a couple of different functions for sending emails from Python. One using SMTP (either with a login or without), or using the sendmail program. You pass the body of the message to them as a string - so it will be easy enough to construct the string in the way you want. Regards, Fuzzy http://www.voidspace.org.uk/python > _________________________________________________________________ > On the road to retirement? Check out MSN Life Events for advice on how to > get there! http://lifeevents.msn.com/category.aspx?cid=Retirement From penguin_archer at yahoo.com Tue Jun 14 05:52:13 2005 From: penguin_archer at yahoo.com (Denis WERNERT) Date: Tue, 14 Jun 2005 11:52:13 +0200 Subject: sudo open() ? (python newbee question) References: Message-ID: <42aea8cd$0$9912$636a15ce@news.free.fr> The script could be SUID Root, and you could use os.setuid immediately after having performed the task to switch to a non-priviledged user. May be a big security risk, if someone can alter the script, he gains root access to the system... slava at crackpot.org wrote: > hello, > > i am writing a python script that will be run by a non root user > the script needs to open a file in write mode that is owned by root > > file = open('/etc/apt/sources.list', 'r+') > > returns permission error > > how can i call sudo on open()? > > thanks alot > slava From cjw at sympatico.ca Wed Jun 1 09:29:52 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 01 Jun 2005 09:29:52 -0400 Subject: Generalized Linear Least Squares Problems In-Reply-To: References: <1117534369.263476.120510@o13g2000cwo.googlegroups.com> Message-ID: Tim Leslie wrote: > On 31 May 2005 03:12:49 -0700, venkat wrote: > >>Hi, >> >>I want to solve linear least sqaure problem( min||c-Ax||2 subject to >>Bx=d ). How do I do it in python. lapack has a routine for doing this >>(DGGLSE). Can I access this from python? >> > > > Check out scipy, in particular the linear algebra package. > > http://www.scipy.org/documentation/apidocs/scipy/scipy.linalg.html > > Cheers, > > Tim > Or you could try numarray, available for use with Python 2.4 http://sourceforge.net/project/showfiles.php?group_id=1369&package_id=32367&release_id=329948 Colin W. > >>TIA, >>venkat. >> >>-- >>http://mail.python.org/mailman/listinfo/python-list >> From gilles.lenfant at nospam.com Tue Jun 14 09:31:26 2005 From: gilles.lenfant at nospam.com (Gilles Lenfant) Date: Tue, 14 Jun 2005 15:31:26 +0200 Subject: [OT ?] (Pythonic) detection word protected files In-Reply-To: References: <42ada90e$0$14696$636a15ce@news.free.fr> Message-ID: <42aeddf9$0$9144$636a15ce@news.free.fr> Gerald Klix a ?crit : > Perhaps you can use OpenOffice and it's python UNO Bindings? > I only know about their existence, but perhaps this will be a starting > point: http://udk.openoffice.org/ Thanks, I already considered this but didn't find the way to get the encryption information (protected or not) in the UNO API. Anyway UNO is somehow overkill to get something like a pair of bytes at some position in the file (4 or 5 python lines with the standard packages). Many thanks -- Gilles From dalke at dalkescientific.com Tue Jun 14 03:20:06 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 14 Jun 2005 07:20:06 GMT Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: Ron Adam wrote: > True, but I think this is considerably less clear. The current for-else > is IMHO is reversed to how the else is used in an if statement. As someone else pointed out, that problem could be resolved in some Python variant by using a different name, like "at end". Too late for anything before P3K. > I'm asking if changing the current 'else' in a for statement to 'also' > would make it's current behavior clearer. It's been stated before here > that current behavior is confusing. "It's been stated" is the passive tense. You are one, and I saw a couple others. But it isn't the same as "many people say that the current behavior is confusing." If memory serves, I don't even recall an FAQ on this, while there is a FAQ regarding the case statement. > You are correct that the 'else' behavior could be nested in the if:break > statement. I think the logical non-nested grouping of code in the > for-also-else form is easier to read. The block in the if statement > before the break isn't part of the loop, IMO, being able to move it to > after the loop makes it clear it evaluates after the loop is done. There is a tension with code coherency. In my version the code that occurs a result of the condition is only in one place while in yours its in two spots. If all (>1) break statements in the loop have the same post-branch code then it might make some sense. But as I said, I don't think it occurs all that often. Given the Python maxim of There should be one-- and preferably only one --obvious way to do it. which of these is the preferred and obvious way? while f(): print "Hello!" if g(): break else: print "this is a test" also: print "this is not a pipe" -or- while f(): print "Hello!" if g(): print "this is a test" break else: print "this is not a pipe" I prefer the second over the first. Which of these is preferred? while f(): print "Hello" if g(): a = 10 print "world", a break if h(): a = 12 print "world",a break -or- while f(): print "Hello" if g(): a = 10 break if h(): a = 12 break else: # your else, not std. python's print "world", a The latter is fragile, in some sense. Suppose I added if hg(): a = 14 print "there" break Then I have to change all of the existing code to put the "else:" block back into the loop. That for me makes it a big no. >> That is ... funky. When is it useful? > > Any time you've writen code that repeats a section of code at the end of > all the if/elif statements or sets a variable to check so you can > conditionally execute a block of code after the if for the same purpose. Let me clarify. When is it useful in real code? Most cases I can think of have corner cases which treat some paths different than others. > My thinking is that this would be the type of thing that would be used > to argue against more specialized suggestions. ie... No a new suggested keyword here> isn't needed because the also-else form > already does that. ;-) An argument for 'X' because it prevents people from asking for some theoretical 'Y' isn't that strong. Otherwise Python would have had a goto years ago. > An example of this might be the case statement suggestions which have > some support and even a PEP. The if-alif-also-else works near enough to > a case statement to fulfill that need. 'alif' (also-if) could be > spelled 'case' and maybe that would be clearer as many people are > already familiar with case statements from other languages. Assuming you are talking about PEP 275 ("Switching on Multiple Values"), how does this fulfill that need any better than the existing if/elif/else chain? > Vetoing a suggestion on grounds of it can be done in another way, is > also not sufficient either as by that reasoning we would still be using > assembly language. So the question I'm asking here is can an inverse to > the 'else' be useful enough to be considered? I disagree. Given the "one -- and preferably only one -- obvious way to do it" there is already a strong bias against language features which exist only to do something another way but not a notably better way. > I'll try to find some use case examples tomorrow, it shouldn't be too > hard. It probably isn't the type of thing that going to make huge > differences. But I think it's a fairly common code pattern so shouldn't > be too difficult to find example uses from pythons library. My guess is that it will be be hard. There's no easy pattern to grep for and I don't think the use case you mention comes up often, much less often enough to need another control mechanism. Andrew dalke at dalkescientific.com From theller at python.net Tue Jun 28 11:06:37 2005 From: theller at python.net (Thomas Heller) Date: Tue, 28 Jun 2005 17:06:37 +0200 Subject: whois like functionality on Windows? References: Message-ID: <64vyed1e.fsf@python.net> Gerrit Muller writes: > I am migrating a website from a UNIX based machine to an Windows > machine. In the logfiles I got from the old machine I mostly got > domain names and sometimes only IP addresses. The Windows machine > seems to produce only IP addresses. > > Somehow I cannot find a windows solution to translate an IP address > back into a domain-name. Searching with Google shows that more people > have been wrestling with this problem. > > I did find working whois scripts, but unfortunately: > - the verbose whois registrar information often forbids automated access > - the information is rather distributed, so you have to somehow access > sufficient servers > - you still have to find the domain name in the sea of details returned > > I also found socket based solutions, but these solutions crash with > the message "host not found" :-( > > Anyone suggestions? This? C:\>py23 Python 2.3.5 (#62, Feb 8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.gethostbyaddr("194.109.137.226") ('fang.python.org', [], ['194.109.137.226']) >>> Thomas From paul at boddie.org.uk Thu Jun 2 04:37:47 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Jun 2005 01:37:47 -0700 Subject: Python as client-side browser script language References: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> <7xk6leylhi.fsf@ruckus.brouhaha.com> <3g79esFb0jkrU1@individual.net> Message-ID: <5339b60d.0506020037.4d106f09@posting.google.com> Greg Ewing wrote in message news:<3g79esFb0jkrU1 at individual.net>... > > If the DOM objects are implemented as built-in Python > types, there shouldn't be any difficulty with that. > Python objects have complete control over which attributes > can be read or written by Python code. > > That, together with restricting what the open() function > can do, ought to provide a pretty good sandbox. Is that really enough, though? Previous discussions [1] suggested that the problem was pretty extensive, and the topic has been proposed [2] for the Summer of Code thing [3], although $4500 may not be a lavish enough amount if the work requires a complete overhaul of CPython. But on the subject of Python as a browser *extension* language where you download extensions from trusted sources and run them from the browser, PyKDE can be used with Konqueror to explore this area, although it does require a very recent PyKDE to work fully - see the kpartplugins on this page for more information: http://www.boddie.org.uk/david/Projects/Python/KDE/index.html It would also be great to unify Konqueror and Mozilla in some way by providing a common API for Python extensions - this could be done by wrapping Mozilla's DOM, presumably exposed via PyXPCOM [4], in a way similar to qtxmldom [5], and then making sure the boilerplate (initialising the extension, getting initial references to browser documents) is separated out from the actual extension code. Paul [1] http://www.amk.ca/python/howto/rexec/rexec.html [2] http://wiki.python.org/moin/RestrictedExecution [3] http://code.google.com/summerofcode.html [4] http://www.mozilla.org/catalog/architecture/xpcom/pyxpcom/ [5] http://www.python.org/pypi/qtxmldom From apardon at forel.vub.ac.be Thu Jun 23 06:05:53 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Jun 2005 10:05:53 GMT Subject: Loop until condition is true References: Message-ID: Op 2005-06-22, Michael Hoffman schreef : > Remi Villatel wrote: >> Fredrik Lundh wrote: >>> checking if a logical expression is true by comparing it to True is bad >>> style, and comparing values using "is" is also bad style. >> >> I wrote it this way because, first, it's perfectly valid Python code and, > > second and most important, it's also a valid english sentence. > > As others have pointed out, it's not perfectly valid code. In fact it is > frequently incorrect. That the same code would be incorrect in other circumstances doesn't make it invalid as it was used in a specific situation. I have written code my self with an "if var is True" statement and that is exactly what I wanted. Replacing it with "if var" would have broken the the program. -- Antoon Pardon From Bill at SynectixLtd.com Wed Jun 29 07:17:22 2005 From: Bill at SynectixLtd.com (Bill Davy) Date: Wed, 29 Jun 2005 11:17:22 +0000 (UTC) Subject: Python/IDLE - text in different colours References: <42c19a13$0$7025$b9fe7a78@news.usenetrevolution.com> Message-ID: Thank you Nathan, but that does not quite address my question. I want to have code in Python so make_the_prompt_string(Red) make_print_output(Green) while True: s = raw_input("This prompt (which is really several lines long) will be in red: ") Foo(s) print "And the result is in Green so the user can see it" "Nathan Pinno" wrote in message news:42c19a13$0$7025$b9fe7a78 at news.usenetrevolution.com... > > > Bill. > > The way is the click on view, then click script checker, or something > like > that. It will color code the text for you. > > Nathan > "Bill Davy" wrote in message > news:d9rfb9$ob7$1 at nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com... > > To make life easier for my users, I'd like to colour my prompt string > (as > > handed to raw_input()) a different colour to that produced by print. > I'm > > using Python 2.4.1 and IDLE 1.1.1 on Windows XP. Is it possible, and > if > so, > > how? > > tia, > > Bill > > > > > > > > -- > > > ---------------------------------------------------------------- > Posted via UsenetRevolution.com - Revolutionary Usenet > ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** > http://www.UsenetRevolution.com From brettk at gmail.com Thu Jun 23 19:48:43 2005 From: brettk at gmail.com (brettk at gmail.com) Date: 23 Jun 2005 16:48:43 -0700 Subject: Listening for a Keypress (Console, not GUI) References: <1119570015.859996.231510@z14g2000cwz.googlegroups.com> Message-ID: <1119570523.640445.170110@g47g2000cwa.googlegroups.com> Ok, I should really read my messages more carefully before posting, I apologize. This is what i'm envisioning "Python Mail Service is running..." Status is printed like: "Current Statistics" Messages retrieved : 12345 Errors: 123 Total Files Written: 12345 Like that - again, apologies for my lack of detail in the first message From peter at engcorp.com Wed Jun 29 16:33:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 29 Jun 2005 16:33:11 -0400 Subject: Boss wants me to program In-Reply-To: References: Message-ID: Harry George wrote: > "Adriaan Renting" writes: >>Both VB and Python are easier to learn as the more powerful >>languages, the price is that they lack features that make it easier to >>manage large and complex projects. > > What is a large project, and what is Python missing that C++ and Java > have for such tasks? But C++ and Java have features that *management* likes, thus making it "easier to manage large projects". (That says nothing about whether or not it makes it easier to produce quality code, successful projects, happy customers, large profits, or any such silly things... just that it's "easier to manage". ;-) Less facetiously: I have managed a large Python project or three, and several large C++ projects (and, thankfully, no large Java projects) and found Python quite up to the task. In fact, if anything the C++ projects ended up more in danger of succumbing to the sheer weight of the code than did the Python projects. But I attribute this more to the fact that we had evolved to using agile approaches with the Python projects than to any of those special features either present or lacking in C++. Ultimately, manageability of a project is far and away more about the people involved and the techniques used than it is about any single technology involved. -Peter From rodriwOh at gmail.com Mon Jun 6 21:57:37 2005 From: rodriwOh at gmail.com (Rod Castellanos) Date: 6 Jun 2005 18:57:37 -0700 Subject: PSP / mod_python ... how to get POST vars on .psp ? Message-ID: Ive been looking everywhere, I need to get a var in my .psp file from another one, I managed to send it with a form and I can read it with "req.read" but it reads all of the variables together separated by a "&" like all POST/GET vars. How do I store each one in a python var, Im looking for something like $_POST and $_GET from php. Thanx. From peter at engcorp.com Mon Jun 13 10:52:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Jun 2005 10:52:52 -0400 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Message-ID: <0q-dnXbbdaJNAzDfRVn-gA@powergate.ca> Steven D'Aprano wrote: > When you read a Windows text file using "r" mode, what happens to the \r > immediately before the newline? Do you have to handle it yourself? Or will > Python cleverly suppress it so you don't have to worry about it? > > And when you write a text file under Python using "w" mode, will the > people who come along afterwards to edit the file in Notepad curse your > name? Notepad expects \r\n EOL characters, and gets cranky if the \r is > missing. This is Python. Fire up the interactive interpreter and try it out! It will take all of two or three minutes... > How does this behaviour differ from "universal newlines"? If you open a text file created with a different line-ending convention than that used on your own platform, you may get "interesting" results. If you use "rU" instead, you will receive only \n line endings and not have anything to worry about. (For example, reading a Windows text file on Linux will give you lines that have \r\n endings in them... not what you really want. Using "rU" will give you just \n line endings whether you are on Linux or Windows.) -Peter From greg at example.invalid Wed Jun 15 09:14:15 2005 From: greg at example.invalid (Greg Krohn) Date: Wed, 15 Jun 2005 13:14:15 GMT Subject: FAQ: __str__ vs __repr__ In-Reply-To: <42b021ba$1@griseus.its.uu.se> References: <42b021ba$1@griseus.its.uu.se> Message-ID: Basically __repr__ should return a string representaion of the object, and __str__ should return a user-friendly pretty string. So maybe: class Person: ... def __repr__(self): return '' % (self.name, self.age, self.sign) def __str__(self): return self.name See this for a better explanation: http://www.faqts.com/knowledge_base/view.phtml/aid/1331/fid/241 From steve.horsley at gmail.com Wed Jun 22 19:01:55 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Thu, 23 Jun 2005 00:01:55 +0100 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: <1119474582.891149.32740@g14g2000cwa.googlegroups.com> References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: Eloff wrote: > Hi Paul, > >>If the 100 threads are blocked waiting for the lock, they shouldn't >>get awakened until the lock is released. So this approach is >>reasonable if you can minimize the lock time for each transaction. > > > Now that is interesting, because if 100 clients have to go through the > system in a second, the server clearly is capable of sending 100 > clients through in a second, and it doesn't matter if they all go > through "at once" or one at a time so long as nobody gets stuck waiting > for much longer than a few seconds. It would be very simple and > painless for me to send them all through one at a time. It is also > possible that certain objects are never accessed in the same action, > and those could have seperate locks as an optimization (this would > require carefull analysis of the different actions.) It is my understanding that Pythons multithreading is done at the interpteter level and that the interpreter itself is single threaded. In this case, you cannot have multiple threads running truly concurrently even on a multi-CPU machine, so as long as you avoid I/O work while holding the lock, I don't think there should be any performance hit using a single lock. The backup thread may be an issue though. Steve From xah at xahlee.org Sun Jun 12 19:55:38 2005 From: xah at xahlee.org (Xah Lee) Date: 12 Jun 2005 16:55:38 -0700 Subject: count string replace occurances Message-ID: <1118620538.711624.237680@z14g2000cwz.googlegroups.com> if i have mytext.replace(a,b) how to find out many many occurances has been replaced? Xah xah at xahlee.org ? http://xahlee.org/ From spam at be.gone Mon Jun 13 03:05:39 2005 From: spam at be.gone (Andy) Date: Mon, 13 Jun 2005 07:05:39 GMT Subject: new string function suggestion Message-ID: <7fare.27429$J12.6708@newssvr14.news.prodigy.com> What do people think of this? 'prefixed string'.lchop('prefix') == 'ed string' 'string with suffix'.rchop('suffix') == 'string with ' 'prefix and suffix.chop('prefix', 'suffix') == ' and ' The names are analogous to strip, rstrip, and lstrip. But the functionality is basically this: def lchop(self, prefix): assert self.startswith(prefix) return self[len(prefix):] def rchop(self, suffix): assert self.endswith(suffix) return self[:-len(suffix] def chop(self, prefix, suffix): assert self.startswith(prefix) assert self.endswith(suffix) return self[len(prefix):-len(suffix] The assert can be a raise of an appropriate exception instead. I find this to be a very common need, and often newbies assume that the strip/lstrip/rstrip family behaves like this, but of course they don't. I get tired of writing stuff like: if path.startswith('html/'): path = path[len('html/'):] elif s.startswith('text/'): path = path[len('text/'):] It just gets tedious, and there is duplication. Instead I could just write: try: path = path.lchop('html/') path = path.lchop('text/') except SomeException: pass Does anyone else find this to be a common need? Has this been suggested before? Andy From tjreedy at udel.edu Thu Jun 9 12:14:00 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Jun 2005 12:14:00 -0400 Subject: Extending Python References: <42a80841@news.wineasy.se> Message-ID: "Johannes" wrote in message news:42a80841 at news.wineasy.se... >I am thinking of replacing Lua as internal script controller and I know >how to extend/embed python but is > there a way of limiting what functionality can be actually be accessible > to the user, f.e. I don't want the script to be able > to read/write files? There have been various threads on script security (see Google). Summary: you can do various things to enhance security, such as replacing builtins (like file() and open()), but, especially with new-style classes and associated features, there is no known way to absolutely control access. Besides which, 'while True: pass', in all its guises, is also hard to stop. Terry J. Reedy From gsakkis at rutgers.edu Sat Jun 25 09:44:22 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Jun 2005 06:44:22 -0700 Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: <1119707062.260303.185590@g47g2000cwa.googlegroups.com> "Roy Smith" wrote: > I just re-read the documentation on the dict() constructor. Why does it > support keyword arguments? > > dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"} > > This smacks of creeping featurism. Is this actually useful in real code? > It took me several readings of the doc to understand what this was doing. > Essentially, it's Perl's bareword syntax, and once I realized that, I > simultaneously understood what was happening and was revolted that Python > seems to have picked up one of Perl's most bizarre and confusing features. The worst thing about this form of the dict constructor it's not the syntax; I think this becomes obvious after you've seen it once. More annoying is that it "wastes" keyword arguments that could otherwise be used to determine the characteristics of the dict. Perhaps the most common desired feature is setting a default value for the dict, that would allow for instance: wordCount = dict(default=0) wordPos = dict(default=[]) for pos,word in enumerate(text): wordCount[word] += 1 wordPos[word].append(pos) Other candidate optional arguments would allow type checking (e.g. dict(keys=int, values=list)) or performance fine-tuning (e.g. dict(minsize = 10, maxsize = 10000, average = 200)). I hope the decision for this form of the constructor is reconsidered for python 3K. George From dvanhorn at cs.uvm.edu Tue Jun 21 10:27:14 2005 From: dvanhorn at cs.uvm.edu (David Van Horn) Date: Tue, 21 Jun 2005 10:27:14 -0400 Subject: tree functions daily exercise: Table In-Reply-To: <1119344080.480368.161850@o13g2000cwo.googlegroups.com> References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> Message-ID: Xah Lee wrote: > here's the Python spec for the Table function: ... > References: > > ? for a context of this message, see: http://xahlee.org/tree/tree.htm Here is a Scheme implementation of Table. As noted on your web page and the Mathematica documentation, the first argument of Table "evaluates in a non-standard way". Thus we use Scheme macros to control the evaluation of this expression. The first three clauses in this syntax definition take care to fill in the default values for i, imin, and di when they are not provided. The fourth clause iterates over one variable constructing a list. Notice this is done tail-recursively. The last clause handles the multiple variable case by rewriting the term into a simpler form. (define-syntax table (syntax-rules () ((table exp (imax)) (table exp (i 1 imax 1))) ((table exp (i imax)) (table exp (i 1 imax 1))) ((table exp (i imin imax)) (table exp (i imin imax 1))) ((table exp (i imin imax di)) (let loop ((n imin) (accum '())) (if (< imax n) (reverse accum) (loop (+ n di) (cons ((lambda (i) exp) n) accum))))) ((table exp i j ...) (table (table exp j ...) i)))) ;; Examples (table #t (0)) ;; => '() (table #t (5)) ;; => '(#t #t #t #t #t) (table i (i 5)) ;; => '(1 2 3 4 5) (table i (i 2 5)) ;; => '(2 3 4 5) (table i (i 2 5 2)) ;; => '(2 4) (table i (i 2 6 2)) ;; => '(2 4 6) (table (add1 i) (i 2 6 2)) ;; => '(3 5 7) (table (- i j) (i 2) (j 2)) ;; => '((0 -1) (1 0)) (table (list i j k) (i 2) (j 100 200 100) (k 5 6)) ;; => '((((1 100 5) (1 100 6)) ((1 200 5) (1 200 6))) (((2 100 5) (2 100 6)) ((2 200 5) (2 200 6)))) From bokr at oz.net Sat Jun 25 20:43:37 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 00:43:37 GMT Subject: trouble subclassing str References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> <1119587240.799959.287180@o13g2000cwo.googlegroups.com> Message-ID: <42bdf930.205205870@news.oz.net> On 23 Jun 2005 21:27:20 -0700, "Paul McGuire" wrote: >Dang, that class should be: > >class PaddedStr(str): > def __new__(cls,s,l,padc=' '): > if l > len(s): > s2 = "%s%s" % (s,padc*(l-len(s))) > return str.__new__(cls,s2) > else: > return str.__new__(cls,s) > Or you could write >>> class PaddedStr2(str): ... def __new__(cls,s,l,padc=' '): ... return str.__new__(cls, s+padc*(l-len(s))) ... Which gives >>> print '>%s<' % PaddedStr2('xxx',5,'.') >xxx..< >>> print '>%s<' % PaddedStr2('xxx',3,'.') >xxx< >>> print '>%s<' % PaddedStr2('xxx',2,'.') >xxx< (Taking advantage of multipliers <=0 working like 0 for strings): >>> for i in xrange(-3,4): print '%2s: >%s<'% (i, 'xxx'+'.'*i) ... -3: >xxx< -2: >xxx< -1: >xxx< 0: >xxx< 1: >xxx.< 2: >xxx..< 3: >xxx...< Regards, Bengt Richter From agriff at tin.it Sat Jun 4 08:24:13 2005 From: agriff at tin.it (Andrea Griffini) Date: Sat, 04 Jun 2005 12:24:13 GMT Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> <3g5tlqFaq4meU1@news.dfncis.de> <927s915p5t5l302u8vcbpmvrokdm64hb39@4ax.com> <3g6n98Faps91U1@news.dfncis.de> Message-ID: On Wed, 01 Jun 2005 23:25:00 +0200, Matthias Buelow wrote: >Of course it is a language, just not a standardized one (if you include >Borland's extensions that make it practical). The history of "runtime error 200" and its handling from borland is a clear example of what I mean with a product. You are of course free to call even Microsoft Access a language (and make long term investment on it) if you want. Andrea From d at e.f Sun Jun 19 22:12:19 2005 From: d at e.f (D H) Date: Sun, 19 Jun 2005 21:12:19 -0500 Subject: case/switch statement? In-Reply-To: References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Message-ID: Peter Hansen wrote: > D H wrote: > >> Peter Hansen wrote: > > [some stuff Doug didn't like] > Actually, this is what you snipped, stuff you didn't like, because the very mention of "boo" causes you such fits: > Since you and Steve Holden agree that a case statement is useful, why > don't you propose it for python, or add it to the wiki page for Python > 3000. > > Here is the syntax the developers of your favorite language boo ( > http://boo.codehaus.org/ ) are using: > > given x: > when 1: > ... > when 2: > ... > otherwise: > ... From bedouglas at earthlink.net Sat Jun 11 13:27:26 2005 From: bedouglas at earthlink.net (bruce) Date: Sat, 11 Jun 2005 10:27:26 -0700 Subject: Dealing with marketing types... In-Reply-To: Message-ID: <19cf01c56eaa$d7048320$0301a8c0@Mesa.com> i don't know what the original thread is/was... but.. if you are part of an initial project.. get in writing what your role is!!!! if you're as a partner, get it in writing... if you're as a hired gun.. get it in writing... if you can't get anything in writing.. then make sure you have your own copies of any/all code that you're created/been a part of... in this day/age, you need to protect yourself.... and trust me, if your code is valuable, and you walk away with it because you feel you've been treated in an unfair manner (assuimng no written statement of your role), then let the other guy come after you... things get resolved in a much more equitable manner when the concerned parties are reasonably equal... -bruce -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of tom Sent: Saturday, June 11, 2005 9:51 AM To: python-list at python.org Subject: Re: Dealing with marketing types... On Fri, 10 Jun 2005 21:57:40 -0700, fuzzylollipop wrote: > I was completely serious, he is _NOT_ going to win this one. He has > already lost. I have been on both sides of this scenario, the "new guys" > were brought in and will win since they are the new "experts from out of > town". Not only do I take you seriously - I agree! I also have been on both sides of this scenario although my take on it is slightly different. It's not so much the "experts from out of town" as it is the tendency to dump the guy(s) that brought them to the party. The sequence goes like this: 1) When there is little or no money to be made, you start out with an implied status as a partner. This means you work long + extra hours for little pay on the promise that you will be rewarded when/if success comes. 2) Then the product gets out the door and it's more long hours with little pay. Much massaging and tweaking and still little money incoming. 3) Success & money start to roll in. Now your status drops from partner to hired hand. An overpaid hired hand at that. Now that the heavy lifting is done, managment is wondering whether they need to actually reward the guy(s) who brought them to the party. The rational parts of their brains shut down while every fiber of their larcenous beings wants them to believe they can now dispense with the high priced talent (you!) for some low bucks commodity labor. There scads of outsourcing firms tripping over one another to sell them the latter. > There may be some other _VALID_ business reason that management has > already made up their mind to hire these Java people. Probably because > they want to sell the company or merge with someone or something and > having a Java product would make them more attractive. Yes, there is a possible _VALID_ reason. That would be the perception, probably accurate, that a technology like Java will shelter them from total dependency on some individual developer (you!). In other words, there is a greater likelihood that they can find replacement talent should they need it. Thats the optimistic view. More often it sinks to the sleazy when they decide to stiff the original guys who did all the extra work up front. If they can replace them, there will be no need to "pay off" on the extra work they did up front. I have had this happen to me as an employee. Later, as an outside consultant, I was frequently disgusted to realize how many manager/owners were merely seeking to avoid the payoff for the guys who went the extra mile to give them a profitable product. Tis business in the USA, sad to say. > There are 2 things he can do. > > 1. Get your resume ready and approach the CEO or whomever and say. Why > is this happening? Since I can guarantee you they have already decided > to port this app to Java. Resume ready is certainly wise and I concur with your gaurantee. > 2. Be quiet, keep his head down, learn Java fasssstt, start agreeing > with the new party line and get on the bandwagon if he really wants to > stay at this company ( I wouldn't ) I disgree here. The party line is nothing but a cover. The goal is to break the dependency on the guru(s) who did the developement or worse, outright replacement. The likelihood of staying on is slim and will become increasingly unpleasant unless the employer is so lacking in concience as to fire him outright. Let me add an Item #3 - If you have some entrepeneurial savvy and can keep your emotions out of it tou can simply tell them you have decided strike out on your own and tell them that you will be available. They will be happy to hear you are leaving and happier still to hear you can be available for backup. Their goals and fears are addressed at the same time. AND there is a very high possibility that they will *need* you at a later date for which you can charge them dearly. That last item #3 has actually worked for me with (2) prior employers. I did have to eat my indignation and keep it friendly but it did pay off in the end. Thomas Bartkus -- http://mail.python.org/mailman/listinfo/python-list From mfranklin1 at gatwick.westerngeco.slb.com Tue Jun 7 04:25:04 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 07 Jun 2005 09:25:04 +0100 Subject: SMTP help please In-Reply-To: References: Message-ID: Ivan Shevanski wrote: > I really can't figure out anything about the SMTP module. . .I think I'm > in over my head( Im pretty new to python). Can someone show me a > really(and I mean REALLY) basic tutorial for smtp or explain it? > > program: > I want to make my program have a feedback form attached to it at the end > which sends me the form when they're done. I don't especially want them > to have to input all the needed details though. . .Just thought I'd put > this in so you'd know what its for. > > > > -Ivan > > _________________________________________________________________ > Don?t just search. Find. Check out the new MSN Search! > http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > Ivan, import smtplib server = smtplib.SMTP("mailserver.somewhere.com") server.set_debuglevel(3) fromaddr = "myemail at address.org" toaddrs = ["first at somewhere.com", "second at smewhere.com"] msg = """Subject: Hi I'm great Thats right I really am """ server.sendmail(fromaddr, toaddrs, msg) server.quit() HTH Martin From syed_saqib_ali at yahoo.com Tue Jun 14 11:58:47 2005 From: syed_saqib_ali at yahoo.com (syed_saqib_ali at yahoo.com) Date: 14 Jun 2005 08:58:47 -0700 Subject: Tough Scrolling question with Tkinter Message-ID: <1118764727.767060.189130@o13g2000cwo.googlegroups.com> Please take a look at and run the code snippet shown below. It creates a canvas with vertical & Horizontal scroll-bars. If you shrink the window to smaller than the area of the canvas, the scroll-bars work as advertised. That's great. However, if you click the Left Mouse button, it calls code which expands the width of the canvas by 100 pixels. The area being viewed expands correspondingly..... BUT I DON'T WANT IT TO!! I want to know how to expand the size of a canvas without changing the area/size of what is currently shown by the scroll bars. I would like to find code that expands the width of the canvas and simply adjusts the H-Scrollbar without changing what is shown on in the area of the canvas being displayed. I have tried seemingly every combination of messing with the canvas.config and scrollregion parameters to no avail. Can someone out there show me how its done?? -Saqib ----------------------------------------- import Tkinter def _b1PressEvt(event): print "B1" _canvas.config(width=300) tkRoot = Tkinter.Tk() _canvas = Tkinter.Canvas(tkRoot, background="white", width=200, height=200,) # Scroll Bars vScrollbar = Tkinter.Scrollbar(tkRoot) vScrollbar.pack(side=Tkinter.RIGHT, expand=True, fill=Tkinter.Y) hScrollbar = Tkinter.Scrollbar(tkRoot) hScrollbar.pack(side=Tkinter.BOTTOM, expand=True, fill=Tkinter.X) _canvas.config( width=200, height=200, scrollregion=(0,0,100,100), yscrollcommand=vScrollbar.set, xscrollcommand=hScrollbar.set, ) vScrollbar.config(orient=Tkinter.VERTICAL, command=_canvas.yview) hScrollbar.config(orient=Tkinter.HORIZONTAL, command=_canvas.xview) #tkRoot.pack() _canvas.pack(expand=Tkinter.NO) vScrollbar.pack(side=Tkinter.RIGHT, expand=True, fill=Tkinter.Y) hScrollbar.pack(side=Tkinter.BOTTOM, expand=True, fill=Tkinter.X) # Function Bindings _canvas.bind("", _b1PressEvt) tkRoot.mainloop() From "myname" at example.invalid Thu Jun 2 07:12:29 2005 From: "myname" at example.invalid (VK) Date: Thu, 02 Jun 2005 13:12:29 +0200 Subject: How to restrict lenght of entry widget to certain number of character In-Reply-To: References: <1117396149.334908.238580@g14g2000cwa.googlegroups.com> <1117700375.764690.305820@g44g2000cwa.googlegroups.com> Message-ID: <3g87tnFb1qrlU1@news.dfncis.de> Peter Otten wrote: > Michael Onfrek wrote: > > >>import Tkinter as tk >> >>Hi! Can you explain what line above mean? >> >>I also found : http://effbot.org/zone/tkinter-entry-validate.htm >> >>It works for me, but I not really understand how? :) > > >>>import Tkinter as tk > > > Make objects defined in Tkinter available under the tk prefix. > E. g. to access an Entry you can do 'tk.Entry'. Had you imported it > 'import Tkinter' you would have to do 'Tkinter.Entry' instead. So you > are saving a few keystrokes. Doing 'from Tkinter import *' saves you still > more keystrokes but is considered bad style except for demonstration > purposes. > > >>>var = tk.StringVar() >>>entry = tk.Entry(root, textvariable=var) > > > Create a StringVar and connect it to the Entry widget. Any changes the user > makes in the Entry are reflected in the StringVar's value which can be > accessed with its get() method. > > >>>max_len = 5 >>>def on_write(*args): >>> s = var.get() >>> if len(s) > max_len: >>> var.set(s[:max_len]) > > > Define a function that doesn't care about the arguments passed to it. It > reads the current value of the StringVar 'var' and, if necessary, trims it > to 'max_len_' characters. > > >>>var.trace_variable("w", on_write) > > > Tell the StringVar to call the function on_write() every time its value is > changed. So every time the user edits the data in the Entry, in turn the > Entry changes the data of the StringVar, which calls the on_write() > function which may or may not change the StringVar -- and that change is > reflected in what the Entry displays. This smells like an endless loop, but > so far we seem to be lucky... > > If you look again at Fredrik Lundh's ValidatingEntry, you will find all the > elements explained above packed nicely into one class, with the extra > refinement that he keeps another copy of the value which is used to restore > the old state when the new value is found to be invalid. > > Peter > Thank you, man! You should write an tutorial to Tkinter or something like that. From lycka at carmen.se Tue Jun 14 09:12:19 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 14 Jun 2005 15:12:19 +0200 Subject: What is different with Python ? (OT I guess) In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: <42AED7B3.8060009@carmen.se> Andrew Dalke wrote: > Andrea Griffini wrote: > >>This is investigating. Programming is more similar to building >>instead (with a very few exceptions). CS is not like physics or >>chemistry or biology where you're given a result (the world) >>and you're looking for the unknown laws. In programming *we* >>are building the world. This is a huge fundamental difference! > > Philosophically I disagree. Biology and physics depends on > models of how the world works. The success of a model depends > on how well it describes and predicts what's observed. > > Programming too has its model of how things work; you've mentioned > algorithmic complexity and there are models of how humans > interact with computers. The success depends in part on how > well it fits with those models. And this is different from building? I don't disagree with the other things you say, but I think Andrea is right here, although I might have said construction or engineering rather than building. To program is to build. While scientists do build and create things, the ultimate goal of science is understanding. Scientists build so that they can learn. Programmers and engineers learn so that they can build. There is a big overlap between science and engineering. I hope we can embrace each other's perspectives and see common goals, but I also think the distinction is useful. It seems to me that a lot of so called science is really more focused on achieving a certain goal than to understand the world. I think Richard Feynman said something like "disciplines with the word 'science' in their names aren't", and I feel that he had a point. I find the idea of computer science a bit odd. Fields like civil engineering or electronics rely solidly on science and the laws of nature. We must, or else our gadgets fail. We work closely with field such as physics and chemistry, but we're not scientists, because we learn to build, not vice versa. Our goal is problem solving and solutions, not knowledge and understanding. As you said: "The success of a model depends on how well it describes and predicts what's observed." It's quite obvious that this is as true when we build houses, airplanes or bridges, and when we build programs. Right? It seems to me that *real* computer scientists are very rare. I suspect that the label computer scientist comes from a lack of a better word. Erh, computer engineering without engineering? What do we call this? I don't mean to offend anyone. I have all respect for both the education and the students of the discipline called computer science, and I think it's vital that there is a foundation of science and mathematics in this field, but most practitioners aren't scientists any more than engineers are scientists. Ok, my degree is "Master of Science" in English, but my academic discipline is electronic engineering, not electronic science--because the goal with the education is to be able to use scientific knowledge to solve practical problems, which is, by definition, what engineers do. Oh well, I guess it's a bit late to try to rename the Computer Science discipline now. From bogus@does.not.exist.com Fri Jun 10 13:55:02 2005 From: bogus@does.not.exist.com () Date: Fri, 10 Jun 2005 17:55:02 -0000 Subject: No subject Message-ID: #! rnews 1443 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: python bytecode grammar X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 29 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <1118406741.403982.319720 at g44g2000cwa.googlegroups.com> <1118408680.008103.203670 at g49g2000cwa.googlegroups.com> Mime-Version: 1.0 Date: Fri, 10 Jun 2005 17:32:15 GMT Xref: news.xs4all.nl comp.lang.python:381172 "M1st0" writes: > Ops yes is BNF :P Bacus Normal Form if I am not wrong... > > However...... > > I'am tryng to recognizing patterns in a bytecoded file in orderd to > optimize... > > But I would like to "parse" i.e reconstruct it in something like a > tree.. > in order to apply rules on a tree recursively. > > I have seen compile.c in the Python dist... > I've never looked, but I'm assuming it is defined in the compiler and in the interpreter, and hopefully documented elsehwere, like: http://python.fyxm.net/peps/pep-0330.html Related: http://mail.python.org/pipermail/python-dev/2004-December/050542.html http://search.cpan.org/search?query=python%3A%3Abytecode&mode=all -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From tim.golden at viacom-outdoor.co.uk Mon Jun 27 08:20:07 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 27 Jun 2005 13:20:07 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB937@vogbs009.gb.vo.local> [Greg Miller] | I have a .DLL that I am extracting the file version from using wmi.py. | The specific code is: | | c = wmi.WMI() | for f in | c.CIM_DataFile(Name="c:\\glossersdmsservices\\bin\\glosscmanag | er.dll"): | sdmsver = f.Version | | this works fine when running the application as a python file, when I | build the application into an executable, using py2exe, I get the | following error: | | Traceback (most recent call last): | File "autoStart.pyc", line 241, in test | File "wmi.pyc", line 138, in ? | File "win32com\client\gencache.pyc", line 540, in EnsureDispatch | File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass | KeyError: '{D2F68443-85DC-427E-91D8-366554CC754C}' You could try using the tweaked version 0.6b from: http://timgolden.me.uk/python/downloads/wmi-0.6b.py which doesn't use the EnsureDispatch and so doesn't (I think) need the type library. If you do decide to try, let me know if it works; it was designed for someone else's py2exe-wmi issue, but I never heard back as to whether he'd tried it. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From superprad at gmail.com Wed Jun 1 21:20:59 2005 From: superprad at gmail.com (PyPK) Date: 1 Jun 2005 18:20:59 -0700 Subject: Performance Issues please help In-Reply-To: <429E59C2.8010405@lexicon.net> References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> <429E59C2.8010405@lexicon.net> Message-ID: <1117675259.678036.18340@f14g2000cwb.googlegroups.com> >Info req'd for discussing algorithm changes: >1. How much free memory do you have? - Memory is not a problem but I am working on some timing constraints.Thats is the reason I am a bit concerned abt these 30 seconds > 2. What can you tell us about the distribution of "e"? - the distribution of e is not fixed.It changes based on what comes first in the scan of the list. > 3. Is "m" a rectangle, or are the rows of variable length? - m is not a restnagle .its of varied dimensions. > 4. Do you have control over "m" i.e. are you stuck with that data structure, or can we design a different one? -I can use 'm' as an array or a list. Other than that I am stuck. I am suspecious abput dictionary approach here. Is this slower than if i do it with arrays or lists with index of array as my key ? From kent37 at tds.net Sat Jun 4 21:47:27 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 21:47:27 -0400 Subject: csv and iterator protocol In-Reply-To: References: Message-ID: <42a2596f$1_2@newspeer2.tds.net> Philippe C. Martin wrote: > Can I initialize csv with input data stored in RAM (ex: a string) ? - so far > I cannot get that to work. Or to rephrase the question, what Python "RAM" > structure supports the "iterator protocol" ? Many, including strings, lists and dicts. For your needs, a list of strings will work, or a cStringIO initialized from your data. Kent From donn at u.washington.edu Thu Jun 2 15:23:34 2005 From: donn at u.washington.edu (Donn Cave) Date: Thu, 02 Jun 2005 12:23:34 -0700 Subject: calling ksh script from python References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: In article , claird at lairds.us (Cameron Laird) wrote: > In article , > Donn Cave wrote: > . > . > . > >Meanwhile, it might be worthwhile to reconsider the use > >of ksh here, if you have any choice in the matter. Ksh > >is fine for interactive use, but has some unfortunate > >flaws as a programming shell, and due to proprietary issues > >one commonly encounters an alternative implementation that's > >even worse. On most modern platforms, sh will have a pretty > >good programming feature set, and will be more reliable > >(especially if it isn't just ksh by another name.) > . > . > . > Infidel. While I sure feel that way about csh(1), it > surprises me you'd criticize ksh(1) so. 'Fact, 'mong > all the *sh-s, I *recommend* ksh for programming. May- > be the two of us see things differently. ----? Portability "ksh" means ? -? ksh88 ? ?(AIX 5.2, ...) ? -? ksh93 ? ?(MacOS X 10.4, ...) ? -? pdksh ? ?(Redhat Linux, NetBSD 2.0, ...) ? -? (nothing) (Older BSDs, ...) ? Plus, I have seen differences that evidently come from ? build options that can be exercised by the platform vendor. ? For example, the effect of ksh -p varies, and "echo" seems ? to mimic the behavior of sh on its host platform. ----? Reliability Interactive ksh users depend on ENV=$HOME/.kshrc for per-shell transient customization, like aliases, but unlike bash or even csh, this file isn't loaded for an interactive shell startup, but any shell startup.? So if I write a program in ksh, and you run it, my script is exposed to your aliases. ----? Feature over-saturation The Bourne shell is pretty fair for UNIX programming, all things considered, but it's a miserable programming language in a more general context, I mean you can hardly do worse (except, as you mention, csh.)? The Korn shell does nothing to really improve the language, yet it adds myriad features as if catering to some kind of full time ksh programmer.? And that's ksh88, I understand 93 takes it to a whole new level. Modern shells - ash, bash, etc. - implement?a?POSIX/XPG4 shell specification that has plenty of these?features.? That's the obvious target for shell scripts written today. Programs that can't get by with that should probably be written in some other language - Python comes to mind, for example, though I usually try awk first for simplicity of deployment. ?? ?Donn Cave,?donn at u.washington.edu From invalid at invalid.com Sun Jun 12 17:42:42 2005 From: invalid at invalid.com (copx) Date: Sun, 12 Jun 2005 23:42:42 +0200 Subject: How to use 8bit character sets? Message-ID: For some reason Python (on Windows) doesn't use the system's default character set and that's a serious problem for me. I need to process German textfiles (containing umlauts and other > 7bit ASCII characters) and generally work with strings which need to be processed using the local encoding (I need to display the text using a Tk-based GUI for example). The only solution I managed to find was converting between unicode and latin-1 all the time (the textfiles aren't unicode, the output of the program isn't supposed to be unicode either). Everything worked fine until I tried to run the program on a Windows 9x machine.. It seems that Python on Win9x doesn't really support unicode (IIRC Win9x doesn't have real unicode support so that's not suprising). Is it possible to tell Python to use an 8bit charset (latin-1 in my case) for textfile and string processing by default? copx From jan.danielsson at gmail.com Wed Jun 1 12:49:33 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 01 Jun 2005 18:49:33 +0200 Subject: Question about mutexes In-Reply-To: <3g64fdFatsvjU1@individual.net> References: <429dda0a$1@griseus.its.uu.se> <3g64fdFatsvjU1@individual.net> Message-ID: <429de5c8$1@griseus.its.uu.se> Reinhold Birkenfeld wrote: [---] >>How would I go about doing that in Python? > > I think you will want to create a threading.Lock object. It would seem so. Thanks for the tip! From Scott.Daniels at Acm.Org Wed Jun 29 11:33:58 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 29 Jun 2005 08:33:58 -0700 Subject: map vs. list-comprehension In-Reply-To: References: <42c27238$0$26269$626a14ce@news.free.fr> Message-ID: <42c2b7cd$1@nntp0.pdx.net> Mandus wrote: > 29 Jun 2005 10:04:40 GMT skrev F. Petitjean: > >>Le Wed, 29 Jun 2005 09:46:15 +0000 (UTC), Mandus a ?crit : >> >>res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] > > seem to be a tad slower than the map, but nothing serious. Guess it's > the extra zip. You could try timing it using itertools.izip rather than zip. --Scott David Daniels Scott.Daniels at Acm.Org From compositions at anthonygroup.net Wed Jun 8 19:51:28 2005 From: compositions at anthonygroup.net (Michael) Date: Thu, 9 Jun 2005 01:51:28 +0200 Subject: Software for System Builders, Resellers, and Hardware Purchasers Only. Message-ID: <85605111084.12872619018@80-58-14-235.proxycache.rima-tde.net> GET latest softwares, 99% savings. http://djjnjs.b0fqeab48lt0qub.risalafe.com There is a fullness of all things, even of sleep and love. Be not ashamed of mistakes and thus make them crimes. From jello at comics.com Thu Jun 2 08:56:41 2005 From: jello at comics.com (rzed) Date: Thu, 02 Jun 2005 08:56:41 -0400 Subject: Newbie question: Allocation vs references References: <429efdbf$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote in news:429efdbf$1 at griseus.its.uu.se: > Hello all, > > Behold: > > ---------- > a = [ 'Foo', 'Bar' ] > b = [ 'Boo', 'Far' ] > q = [ a, b ] > > print q[0][0] > print q[1][1] > > a[0] = 'Snoo' > b[1] = 'Gnuu' > > print q[0][0] > print q[1][1] > ---------- > > This will output: > Foo > Far > Snoo > Gnuu > > I assume it does so because q stores _references_ to a and b. > How > would do I do if I want to copy the list? I.e. I want the output > from the code above to be: > If your original assigment to q were: q = [ a[:], b[:] ] ... you would have copies of a and b, so that: >>> a = [ 'Foo', 'Bar' ] >>> b = [ 'Boo', 'Far' ] >>> q = [ a[:], b[:] ] >>> print q[0][0] Foo >>> print q[1][1] Far >>> >>> a[0] = 'Snoo' >>> b[1] = 'Gnuu' >>> >>> print q[0][0] Foo >>> print q[1][1] Far > Foo > Far > Foo > Far > > ..even if a[0] = 'Snoo' and b[1] = 'Gnuu' remain where they are. > > Or, better yet, how do I store a and b in q, and then tell > Python > that I want a and b to point to new lists, without touching the > contents in q? That's easier: >>> a = [ 'Foo', 'Bar' ] >>> b = [ 'Boo', 'Far' ] >>> q = [a,b] >>> a = ['Splee','Hoongk'] >>> b = ['Blik','Poit'] >>> print q[0][0] Foo >>> print q[1][1] Far You've stuck the 'a' and 'b' labels on new objects this way. The original objects would vanish except that there is still a reference to them through the 'q' list. > > C equivalent of what I want to do: > ----------- > a = calloc(n, size); > prepare(a) > > q[0] = a; > > a = calloc(n, size); // new list; 'q' is unaffected if I change > 'a' ----------- -- rzed From lycka at carmen.se Tue Jun 14 06:54:34 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 14 Jun 2005 12:54:34 +0200 Subject: python bytecode grammar In-Reply-To: <1118408680.008103.203670@g49g2000cwa.googlegroups.com> References: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> <1118408680.008103.203670@g49g2000cwa.googlegroups.com> Message-ID: M1st0 wrote: > Ops yes is BNF :P Bacus Normal Form if I am not wrong... Backus Naur Form. John Backus and Peter Naur first used it to describe ALGOL around 1960. See e.g. http://cui.unige.ch/db-research/Enseignement/analyseinfo/AboutBNF.html From steven.bethard at gmail.com Sat Jun 25 18:36:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Jun 2005 16:36:25 -0600 Subject: python-dev Summary for 2005-05-16 through 2005-05-31 Message-ID: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-05-16_2005-05-31.html] ===================== Summary Announcements ===================== ---- QOTF ---- We have our first ever Quote of the Fortnight (QOTF), thanks to the wave of discussion over `PEP 343`_ and Jack Diederich: I still haven't gotten used to Guido's heart-attack inducing early enthusiasm for strange things followed later by a simple proclamation I like. Some day I'll learn that the sound of fingernails on the chalkboard is frequently followed by candy for the whole class. See, even threads about anonymous block statements can end happily! ;) .. _PEP 343: http://www.python.org/peps/pep-0343.html Contributing thread: - `PEP 343 - Abstract Block Redux `__ [SJB] ------------------ First PyPy Release ------------------ The first release of `PyPy`_, the Python implementation of Python, is finally available. The PyPy team has made impressive progress, and the current release of PyPy now passes around 90% of the Python language regression tests that do not depend deeply on C-extensions. The PyPy interpreter still runs on top of a CPython interpreter though, so it is still quite slow due to the double-interpretation penalty. .. _PyPy: http://codespeak.net/pypy Contributing thread: - `First PyPy (preview) release `__ [SJB] -------------------------------- Thesis: Type Inference in Python -------------------------------- Brett C. successfully defended his masters thesis `Localized Type Inference of Atomic Types in Python`_, which investigates some of the issues of applying type inference to the current Python language, as well as to the Python language augmented with type annotations. Congrats Brett! .. _Localized Type Inference of Atomic Types in Python: http://www.drifty.org/thesis.pdf Contributing thread: - `Localized Type Inference of Atomic Types in Python `__ [SJB] ========= Summaries ========= --------------------------- PEP 343 and With Statements --------------------------- The discussion on "anonymous block statements" brought itself closer to a real conclusion this fortnight, with the discussion around `PEP 343`_ and `PEP 3XX`_ converging not only on the semantics for "with statements", but also on semantics for using generators as with-statement templates. To aid in the adaptation of generators to with-statements, Guido proposed adding close() and throw() methods to generator objects, similar to the ones suggested by `PEP 325`_ and `PEP 288`_. The throw() method would cause an exception to be raised at the point where the generator is currently suspended, and the close() method would use throw() to signal the generator to clean itself up by raising a GeneratorExit exception. People seemed generally happy with this proposal and -- believe it or not -- we actually went an entire eight days without an email about anonymous block statements!! It looked as if an updated `PEP 343`_, including the new generator functionality, would be coming early the next month. So stay tuned. ;) .. _PEP 288: http://www.python.org/peps/pep-0288.html .. _PEP 325: http://www.python.org/peps/pep-0325.html .. _PEP 343: http://www.python.org/peps/pep-0343.html .. _PEP 3XX: http://www.python.org/peps/pep-0346.html Contributing threads: - `PEP 343 - Abstract Block Redux `__ - `Simpler finalization semantics (was Re: PEP 343 - Abstract Block Redux) `__ - `Example for PEP 343 `__ - `Combining the best of PEP 288 and PEP 325: generator exceptions and cleanup `__ - `PEP 343 - New kind of yield statement? `__ - `PEP 342/343 status? `__ - `PEP 346: User defined statements (formerly known as PEP 3XX) `__ [SJB] ----------- Decimal FAQ ----------- Raymond Hettinger suggested that a decimal FAQ would shorten the module's learning curve, and drafted one. There were no objections, but few adjustments (to the list, at least). Raymond will probably make the FAQ available at some point. Contributing thread: - `Decimal FAQ `__ [TAM] --------------------- Constructing Decimals --------------------- A long discussion took place regarding whether the decimal constructor should or should not respect context settings, and whether matching the standard (and what the standard says) should be a priority. Raymond Hettinger took the lead in the status-quo (does not) corner, with Tim Peters leading the opposition. Tim and Guido eventually called in the standard's expert, Mike Cowlishaw. He gave a very thorough explanation of the history behind his decisions in this matter, and eventually weighed in on Raymond's side. As such, it seems that the status-quo has won (not that it was a competition, of course ). For those that need to know, the unary plus operation, as strange as it looks, forces a rounding using the current context. As such, context-aware construction can be written:: val = +Decimal(string_repr) Contributing threads: - `Adventures with Decimal `__ - `Decimal construction `__ - `[Python-checkins] python/nondist/peps pep-0343.txt, 1.8, 1.9 `__ [TAM] ------------------------ Handling old bug reports ------------------------ Facundo Batista continued with his progress checking the open bug reports, looking for bugs that are specific to 2.2.1 or 2.2.2. The aim is to verify whether these bugs exist in current CVS, or are old-of-date. There are no longer any bugs in the 2.1.x or 2.2.x categories, and Facundo wondered whether removing those categories would be a good idea. The consensus was that there was no harm in leaving the categories there, but that changing the text to indicate that those versions are unmaintained would be a good idea. Raymond Hettinger reminded us that care needs to be taken in closing old bug reports. Particularly, a bug report should only be closed if (a) there are no means of reproducing the error, (b) it is impossible to tell what the poster meant, and they are no longer contactable, or (c) the bug is no longer present in current CVS. Contributing threads: - `Deprecating old bugs, now from 2.2.2 `__ - `Closing old bugs `__ - `Old Python version categories in Bug Tracker `__ [TAM] ------------------ Exception chaining ------------------ Ka-Ping Yee has submitted `PEP 344`_, which is a concrete proposal for exception chaining. It proposes three standard attributes on trackback objects: __context__ for implicit chaining, __cause__ for explicit chaining, and __traceback__ to point to the traceback. Guido likes the motivation and rationale, but feels that the specification needs more work. A lot of discussion about the specifics of the PEP took place, and Ka-Ping is working these into a revised version. One of the major questions was whether there is no need for both __context__ and __cause__ (to differentiate between explicit and implicit chaining). Guido didn't feel that there was, but others disagreed. Discussion branched off into whether which attributes should be double-underscored, or not. Guido's opinion is that it depends who "owns" the namespace, and with "magic" behaviour caused (or indicated) by the presence of the attribute. He felt that the underscores in the proposed exception attributes should remain. .. _PEP 344: http://www.python.org/peps/pep-0344.html Contributing threads: - `PEP 344: Exception Chaining and Embedded Tracebacks `__ - `PEP 344: Implicit Chaining Semantics `__ - `PEP 344: Explicit vs. Implicit Chaining `__ - `Tidier Exceptions `__ [TAM] ------------------------------------ Adding content to exception messages ------------------------------------ Nicolas Fleury suggested that there should be a standard method of adding information to an existing exception (to re-raise it). Nick Coghlan suggested that this would be reasonably simple to do with PEP 344, if all exceptions were also new-style classes, but Nicolas indicated that this wouldn't work in some cases. Contributing threads: - `Adding content to exception messages `__ [TAM] =============== Skipped Threads =============== - `Loading compiled modules under MSYS/MingGW? `__ - `RFC: rewrite fileinput module to use itertools. `__ - `Multiple interpreters not compatible with current thread module `__ - `Weekly Python Patch/Bug Summary `__ - `Request for dev permissions `__ - `python-dev Summary for 2005-05-01 through 2005-05-15 [draft] `__ - `AST manipulation and source code generation `__ - `Weekly Python Patch/Bug Summary `__ - `AST branch patches (was Re: PEP 342/343 status?) `__ - `[Python-checkins] python/dist/src/Lib/test test_site.py, 1.6, 1.7 `__ - `Split MIME headers into multiple lines near a space `__ ======== Epilogue ======== ------------ Introduction ------------ This is a summary of traffic on the `python-dev mailing list`_ from May 16, 2005 through May 31, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the fourth summary written by the python-dev summary cabal of Steve Bethard, Tim Lesher, and Tony Meyer. To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tim Lesher (tlesher at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. I do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow me to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/ .. _original text file: http://www.python.org/dev/summary/2005-05-16_2005-05-31.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From codedivine at gmail.com Wed Jun 29 12:27:49 2005 From: codedivine at gmail.com (Rahul) Date: 29 Jun 2005 09:27:49 -0700 Subject: strange __call__ References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> Message-ID: <1120062469.370984.130670@f14g2000cwb.googlegroups.com> Hi. well if you do dir(a) just after defining 'a' then it does show '__call__'. the reason i wanted to do it is that i wanted to see if theres a uniform way to wrap a function and callable objects so that for example i can get some message printed whenever a function or a function-like-object is called. then i could simply do : def wrapper(obj): g = obj.__call__ def f(*args,**kwargs): for arg in args:print arg return g(*args,**kwargs) obj.__call__=f but it seems this will not work for functions :( Andreas Kostyrka wrote: > Just a guess, but setting "__X__" special methods won't work in most cases > because these are usually optimized when the class is created. > > It might work if a.__call__ did exist before (because class a: contained > a __call__ definition). > > Andreas > > On Wed, Jun 29, 2005 at 09:15:45AM +0100, Michael Hoffman wrote: > > Rahul wrote: > > > Consider the following: > > > def a(x): > > > return x+1 > > > > > > def b(f): > > > def g(*args,**kwargs): > > > for arg in args: > > > print arg > > > return f(*args,**kwargs) > > > return g > > > > > > a.__call__ = b(a.__call__) > > > > > > now calling a(1) and a.__call__(1) yield 2 different results!! > > > i.e. for functions a(1) doesnt seem to be translated to a.__call__ if > > > you assign a new value to a.__call__? > > > > I don't know why this happens, but setting the __call__ attribute of a > > is a pretty strange thing to do. Why not just set a instead? The > > original function a(x) will still be stored as a closure in what is > > returned from b(). > > > > If this is of purely academic interest then the answer is I don't know. :) > > -- > > Michael Hoffman > > -- > > http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Sat Jun 11 16:03:01 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 11 Jun 2005 22:03:01 +0200 Subject: identifying 64-bit Windows from 2.3.5? In-Reply-To: References: Message-ID: <42AB4375.6000006@v.loewis.de> Steven Knight wrote: > Can some Windows-savvy Pythonista point me to some way to distinguish > between these two? I would look at the environment variable PROCESSOR_ARCHITECTURE. On the Win64 machine I use, its value is "IA64". Regards, Martin From peter at engcorp.com Tue Jun 28 14:48:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Jun 2005 14:48:26 -0400 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: Message-ID: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> ???? ???????? wrote: > There is a syntactic sugar for item access in > dictionaries and sequences: > > o[e] = v <-> o.__setitem__(e, v) > o[e] <-> o.__getitem__(e) > > where e is an expression. > > There is no similar way for set/get attribute for objects. > If e is a given name, then > > o.e = v <-> o.__setattr__(e, v) > o.e <-> o.__getattr__(e) > > Anybody thought about this issue? Perhaps not, but now that you've pointed it out they've taken the time machine back and fixed the problem before it arose: >>> class C: ... def __setattr__(self, e, v): ... print 'setting %s to %s' % (e, v) ... self.__dict__[e] = v ... >>> o = C() >>> v = 'mystring' >>> o.e = v setting e to mystring >>> o.e 'mystring' >>> -Peter From grante at visi.com Tue Jun 28 23:14:26 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Jun 2005 03:14:26 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <11c44giis2f5fa8@corp.supernews.com> On 2005-06-28, James Stroud wrote: > I think James Bond did it for Americans. He always wore a > dinner jacket and played a lot of backarack--which is only > cool because you have to bet a lot of money. Anyway, if you > insist on making distinctions between the backwoods of > apalachia and european aristocracy, What, you think they sound the same? > I should remind you of the recessive genetic diseases that > have historically plagued europe's nobility. If don't think the English are willing to laugh at the nobility, you must not have seen the "Twit of the Year" skit or the election skit with what's-his-name (pronounced "mangrove throatwarbler"). -- Grant Edwards grante Yow! I wonder if I should at put myself in ESCROW!! visi.com From calfdog at yahoo.com Fri Jun 10 16:28:21 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 10 Jun 2005 13:28:21 -0700 Subject: Using PAMIE to upload and download files...is it possible? In-Reply-To: <1118427453.108199.135860@g14g2000cwa.googlegroups.com> References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> <1118256512.379934.292780@z14g2000cwz.googlegroups.com> <1118427453.108199.135860@g14g2000cwa.googlegroups.com> Message-ID: <1118435301.748143.288780@g14g2000cwa.googlegroups.com> Yes, you should be able uploads and downloads, but you have to import modaltest which uses WinGuiAuto to do this. This also handles pop-ups ModalTest.py is in the files section of the Pamie Users Group http://pamie.sourceforge.net. You have to sign up as a member to access the file. Membership is free. It uses threading to allow you to upload and download and then continue on with your test. I will be incorporated into PAMIE 1.6 Let me know if you runn into any problems! RL Marchetti scrimp wrote: > Thank you. I will try to come up with something I will post more if I > have any other questions. Thanks From pdemb at gazeta.pl Sat Jun 4 05:52:37 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sat, 04 Jun 2005 11:52:37 +0200 Subject: idiom for constructor? References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <87acm6e9ei.fsf@hector.domek> Steven Bethard writes: > Mac wrote: >> Is there a nice Python idiom for constructors which would expedite >> the following? >> class Foo: >> def __init__(self, a,b,c,d,...): >> self.a = a >> self.b = b >> self.c = c >> self.d = d >> ... > > py> class Foo(object): > ... def __init__(self, a, b, c, d): > ... params = locals() > ... del params['self'] > ... self.__dict__.update(params) > ... > py> vars(Foo(1, 2, 3, 4)) > {'a': 1, 'c': 3, 'b': 2, 'd': 4} > > Just make sure that "params = locals()" is the first line in > __init__ method. (Otherwise you might have other local variables > slip in there.) Or write it like this, using Python's dynamic code execution: #v+ class A: def __init__(self, a, b, c, d): initial = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} for param in initial.keys(): exec "self.%s = initial['%s']" % (param, param) #v- -- http://www.peter.dembinski.prv.pl From gerard.vermeulen at grenoble.cnrs.fr Sat Jun 18 13:50:53 2005 From: gerard.vermeulen at grenoble.cnrs.fr (Gerard Vermeulen) Date: Sat, 18 Jun 2005 19:50:53 +0200 Subject: [PyKDE] Static (why?) PyDateTimeAPI and SIP In-Reply-To: <20050618195220.1a5db406@ods.pravda.rfn.ru> References: <20050618195220.1a5db406@ods.pravda.rfn.ru> Message-ID: <20050618195053.048649d6.gerard.vermeulen@grenoble.cnrs.fr> On Sat, 18 Jun 2005 19:52:20 +0400 "Denis S. Otkidach" wrote: > I use datetime C API in extension module generated with SIP. But SIP > break the code into several .cpp files compiled separately and > PyDateTimeAPI used by all macros constituting public interface is > declared static. > > The current solution is to define my own functions in main module as > workaround: > > %ModuleHeaderCode > PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, > int hour, int minute, int seconds, > int usecs); > %End > > %ModuleCode > PyObject * mxo_PyDateTime_FromDateAndTime(int year, int month, int day, > int hour, int minute, int seconds, > int usecs) { > return PyDateTime_FromDateAndTime(year, month, day, hour, minute, seconds, > usecs); > } > // and so on for each macro used > %End > > %PostInitialisationCode > PyDateTime_IMPORT; > %End > > But I wonder why PyDateTimeAPI is declared static, and is the a better > solution? To prevent namespace pollution. Numeric and numarray have a different solution. From Numeric/arrayobject.h: /* C API address pointer */ #if defined(NO_IMPORT) || defined(NO_IMPORT_ARRAY) extern void **PyArray_API; #else #if defined(PY_ARRAY_UNIQUE_SYMBOL) void **PyArray_API; #else static void **PyArray_API; #endif which lets you use whatever you like and even rename the C API address pointer. However, keep in mind that SIP can concatenate all C++ files which breaks clever #defines that work if SIP generates separate C++ source files. In fact, I use your method, when wrapping the Numeric and numarray files for PyQwt. The only difference is that I put all access to the C-API in handwritten C++ files to use the conflicting APIs of Numeric and numarray in the same Python extension. Gerard From tojuso at hotmail.com Mon Jun 6 17:53:28 2005 From: tojuso at hotmail.com (Dan) Date: 6 Jun 2005 14:53:28 -0700 Subject: Controlling source IP address within urllib2 References: <1117839742.510669.245420@g14g2000cwa.googlegroups.com> <87slzxlppj.fsf@pobox.com> Message-ID: <1118094808.095632.134210@z14g2000cwz.googlegroups.com> John, Thanks for your input. I can kind of see the light in this, but I'm having difficulty knowing where the "do_open" method comes from. Also, I'll need to follow redirects, so I assume then I would add a HTTPRedirectHandler instance to the urllib2.build_opener. (?) Thanks again for your help. -Dan From pmaupin at gmail.com Thu Jun 23 00:53:19 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 22 Jun 2005 21:53:19 -0700 Subject: PEP 304 - is anyone really interested? In-Reply-To: References: Message-ID: <1119502399.641440.325050@z14g2000cwz.googlegroups.com> Skip Montanaro wrote: > I wrote PEP 304, "Controlling Generation of Bytecode Files": ... > If someone out there is interested in this functionality > and would benefit more from its incorporation into the > core, I'd be happy to hand it off to you. I am quite interested in this PEP. What, exactly, would the recipient of this "hand-off" have to do? Does it primarily have to do with resolution of the issues listed in the PEP? BTW, my use case for this PEP is different than the PEP's given rationale -- in general, I (and the people I work with) keep our source trees completely separate from (and parallel to) our object trees. This obviates the need for .cvsignore, makes "make clean" a much easier proposition, makes it easier to generate and test/compare slightly different object sets (just use an environment variable to change the build target directory), and reduces the filtration required to get usable output from simple source file greps. The main fly in the ointment right now is .pyc files -- they tend to pop up whereever there is a little script (or more accurately, of course, whereever there is a multiple-module script :), and the current choices for dealing with them as special cases, e.g. zip files, copying all sub-modules over to the build tree before importing them, manually reading the files and compiling them, etc., are all rather unappealing. >From my perspective, the lack of PEP 304 functionality in the standard distribution is hampering World Domination, since the littering of source directories with compiled .pyc files is yet another excuse for some of my compatriots to keep using Perl. In fact, I have to be very careful how I introduce Python scripts into this environment lest I anger someone by polluting their source tree. Note that for my current purposes (as described above, and in contrast to the original rationale behind the PEP) sys.bytecodebase is much more important than PYTHONBYTECODEBASE (because my few scripts can set up sys.bytecodebase quite easily themselves). Since it would seem that most of the security concerns would derive from the PYTHONCODEBASE environment variable, it would be an interesting exercise to try to figure out how many potential users of this PEP want it for my purposes and how many want it for the original purpose. I would think not adding the environment variable would be less contentious from a security/backward-compatibility standpoint, but possibly more contentious from a lack-of-new-useful-functionality-that-could-not-be-easily-implemented-in-an-add-on-package standpoint. Regards, Pat From dstanek at dstanek.com Fri Jun 3 16:47:24 2005 From: dstanek at dstanek.com (David Stanek) Date: Fri, 3 Jun 2005 16:47:24 -0400 Subject: Python interest group software Message-ID: <20050603204724.GB8195@goliath.ag.com> Is there already any software out there to manage a Python Interest Group? Something that can register users, take RSVPs for meetings, etc. -- David Stanek www.roninds.net GPG keyID #6272EDAF on http://pgp.mit.edu Key fingerprint = 8BAA 7E11 8856 E148 6833 655A 92E2 3E00 6272 EDAF -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rkern at ucsd.edu Mon Jun 13 08:35:09 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 13 Jun 2005 05:35:09 -0700 Subject: Learning more about "The Python Way" In-Reply-To: References: <0001HW.BED2700A0044BB0FF0284550@news.gmane.org> Message-ID: Neuruss wrote: [Me:] >>As someone else mentioned, get a copy of the 2nd edition of the Python >>Cookbook. It's full of gold. > > Or you can read the recipes online here: > http://aspn.activestate.com/ASPN/Python/Cookbook/ While most (all?) of the recipes are there, the book is still worth buying for the discussion about each recipe that will help the reader learn more deeply how the code fits into "The Python Way." -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dalke at dalkescientific.com Mon Jun 6 16:02:40 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 06 Jun 2005 20:02:40 GMT Subject: About size of Unicode string References: Message-ID: Frank Abel Cancio Bello wrote: > Can I get how many bytes have a string object independently of its encoding? > Is the "len" function the right way of get it? No. len(unicode_string) returns the number of characters in the unicode_string. Number of bytes depends on how the unicode character are represented. Different encodings will use different numbers of bytes. >>> u = u"G\N{Latin small letter A with ring above}" >>> u u'G\xe5' >>> len(u) 2 >>> u.encode("utf-8") 'G\xc3\xa5' >>> len(u.encode("utf-8")) 3 >>> u.encode("latin1") 'G\xe5' >>> len(u.encode("latin1")) 2 >>> u.encode("utf16") '\xfe\xff\x00G\x00\xe5' >>> len(u.encode("utf16")) 6 >>> > Laci look the following code: > > import urllib2 > request = urllib2.Request(url= 'http://localhost:6000') > data = 'data to send\n'.encode('utf_8') > request.add_data(data) > request.add_header('content-length', str(len(data))) > request.add_header('content-encoding', 'UTF-8') > file = urllib2.urlopen(request) > > Is always true that "the size of the entity-body" is "len(data)" > independently of the encoding of "data"? For this case it is true because the logical length of 'data' (which is a byte string) is equal to the number of bytes in the string, and the utf-8 encoding of a byte string with character values in the range 0-127, inclusive, is unchanged from the original string. In general, as if 'data' is a unicode strings, no. len() returns the logical length of 'data'. That number does not need to be the number of bytes used to represent 'data'. To get the bytes you must encode the object. Andrew dalke at dalkescientific.com From eurleif at ecritters.biz Wed Jun 15 21:01:21 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 16 Jun 2005 01:01:21 GMT Subject: splitting delimited strings In-Reply-To: References: Message-ID: Mark Harrison wrote: > What is the best way to process a text file of delimited strings? > I've got a file where strings are quoted with at-signs, @like this at . > At-signs in the string are represented as doubled @@. >>> import re >>> _at_re = re.compile('(?>> def split_at_line(line): ... return [field.replace('@@', '@') for field in ... _at_re.split(line)] ... >>> split_at_line('foo at bar@@baz at qux') ['foo', 'bar at baz', 'qux'] From davecook at nowhere.net Fri Jun 24 21:17:23 2005 From: davecook at nowhere.net (Dave Cook) Date: Sat, 25 Jun 2005 01:17:23 GMT Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: On 2005-06-24, infidel wrote: > dict((x, None) for x in alist) Whoa, I thought dictionary comprehensions were still planned feature. I guess I gotta start paying closer attention. Dave Cook From greg_miller at nexpress.com Wed Jun 29 09:15:32 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 29 Jun 2005 06:15:32 -0700 Subject: COM problem .py versus .exe In-Reply-To: References: Message-ID: <1120050932.705873.215100@f14g2000cwb.googlegroups.com> Unfortunately I have a "fire" to put out with a patch to the existing machine code, I'll get back to looking into the problem a little later. Thanks very much for you assistance with this! I really didn't look into the GetFileVersionInfo, can I assume that is a cytypes function? From jtanis at pycoder.org Tue Jun 14 12:23:35 2005 From: jtanis at pycoder.org (James Tanis) Date: Tue, 14 Jun 2005 12:23:35 -0400 (EDT) Subject: collect data using threads In-Reply-To: <42AF02BD.9080809@bellsouth.net> References: <42aeeef3$1_1@newspeer2.tds.net> <42AF02BD.9080809@bellsouth.net> Message-ID: Previously, on Jun 14, Jeremy Jones said: # Kent Johnson wrote: # # > Peter Hansen wrote: # > # > > Qiangning Hong wrote: # > > # > > # > > > A class Collector, it spawns several threads to read from serial port. # > > > Collector.get_data() will get all the data they have read since last # > > > call. Who can tell me whether my implementation correct? # > > > # > > [snip sample with a list] # > > # > > # > > > I am not very sure about the get_data() method. Will it cause data lose # > > > if there is a thread is appending data to self.data at the same time? # > > > # > > That will not work, and you will get data loss, as Jeremy points out. # > > # > > Normally Python lists are safe, but your key problem (in this code) is # > > that you are rebinding self.data to a new list! If another thread calls # > > on_received() just after the line "x = self.data" executes, then the new # > > data will never be seen. # > > # > # > Can you explain why not? self.data is still bound to the same list as x. At # > least if the execution sequence is x = self.data # > self.data.append(a_piece_of_data) # > self.data = [] # > # > ISTM it should work. # > # > I'm not arguing in favor of the original code, I'm just trying to understand # > your specific failure mode. # > # > Thanks, # > Kent # > # Here's the original code: # # class Collector(object): # def __init__(self): # self.data = [] # spawn_work_bees(callback=self.on_received) # # def on_received(self, a_piece_of_data): # """This callback is executed in work bee threads!""" # self.data.append(a_piece_of_data) # # def get_data(self): # x = self.data # self.data = [] # return x # # The more I look at this, the more I'm not sure whether data loss will occur. # For me, that's good enough reason to rewrite this code. I'd rather be clear # and certain than clever anyday. # So, let's say you a thread T1 which starts in ``get_data()`` and makes it as # far as ``x = self.data``. Then another thread T2 comes along in # ``on_received()`` and gets as far as ``self.data.append(a_piece_of_data)``. # ``x`` in T1's get_data()`` (as you pointed out) is still pointing to the list # that T2 just appended to and T1 will return that list. But what happens if # you get multiple guys in ``get_data()`` and multiple guys in # ``on_received()``? I can't prove it, but it seems like you're going to have # an uncertain outcome. If you're just dealing with 2 threads, I can't see how # that would be unsafe. Maybe someone could come up with a use case that would # disprove that. But if you've got, say, 4 threads, 2 in each method....that's # gonna get messy. # And, honestly, I'm trying *really* hard to come up with a scenario that would # lose data and I can't. Maybe someone like Peter or Aahz or some little 13 # year old in Topeka who's smarter than me can come up with something. But I do # know this - the more I think about this as to whether this is unsafe or not is # making my head hurt. If you have a piece of code that you have to spend that # much time on trying to figure out if it is threadsafe or not, why would you # leave it as is? Maybe the rest of you are more confident in your thinking and # programming skills than I am, but I would quickly slap a Queue in there. If # for nothing else than to rest from simulating in my head 1, 2, 3, 5, 10 # threads in the ``get_data()`` method while various threads are in the # ``on_received()`` method. Aaaagghhh.....need....motrin...... # # # Jeremy Jones # I may be wrong here, but shouldn't you just use a stack, or in other words, use the list as a stack and just pop the data off the top. I believe there is a method pop() already supplied for you. Since you wouldn't require an self.data = [] this should allow you to safely remove the data you've already seen without accidentally removing data that may have been added in the mean time. --- James Tanis jtanis at pycoder.org http://pycoder.org From noreply at gunnar.cc Mon Jun 27 06:45:32 2005 From: noreply at gunnar.cc (Gunnar Hjalmarsson) Date: Mon, 27 Jun 2005 12:45:32 +0200 Subject: turn text lines into a list In-Reply-To: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> Message-ID: <3ia3mfFk3168U1@individual.net> Xah Lee wrote: > i have a large number of lines i want to turn into a list. > In perl, i can do > > @corenames=qw( > rb_basic_islamic > sq1_pentagonTile > sq_arc501Tile > sq_arc503Tile > ); Impractical to mix code and data, isn't it? chomp( my @corenames = ); __DATA__ rb_basic_islamic sq1_pentagonTile sq_arc501Tile sq_arc503Tile -- Gunnar Hjalmarsson Email: http://www.gunnar.cc/cgi-bin/contact.pl From peter at engcorp.com Fri Jun 10 07:52:25 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Jun 2005 07:52:25 -0400 Subject: Any way to not create .pyc files? In-Reply-To: References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> <8cGdnaHABLhlEzXfRVn-oQ@powergate.ca> <1118350114.634141.95920@g49g2000cwa.googlegroups.com> Message-ID: <2LCdnaLtfdK9HTTfRVn-pg@powergate.ca> Terry Hancock wrote: > The user with write access would run the script, causing the pyc files > to be generated for that interpreter. Then a normal user, running an > older Python tries to load the modules. Since a .pyc file exists, it gets > used instead, but *oops* it's for a later version of the interpreter and > stuff breaks. > > A better solution than getting rid of the pyc files would be to put good > ones there --- use the version of python that users are expected to be > using and generate them. If you delete the pyc files, you create an > unnecessary drag on performance and the hazard remains to mess you > up again. If the pyc files are generated, though, I *think* they will be > used and work for both the expected python and (fingers crossed) the > later version. Sorry Terry, but both assumptions are wrong. Different versions of Python store different "magic numbers" in the .pyc files, and they will not use a .pyc file with a wrong number. I believe you'll actually get an error about "bad magic number" if you do manage to force a bad .pyc to be loaded (probably by having no matching .py from which to recompile). If the .py does exist, it will be recompiled and the newly generated bytecode will be used, whether or not the .pyc file can be written to cache it for next time. Your suggestion about pre-generating the .pyc files (using compileall) is a good one in general for this sort of setup (shared libraries), though it really won't help if there are different versions of Python in use. (If that's true, nothing will really help except perhaps PEP304 and the time machine. Well, having the two versions use two different copies of the library files would help, but the OP doesn't think there are different versions in use.) -Peter From philippe at philippecmartin.com Mon Jun 13 15:07:26 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 13 Jun 2005 19:07:26 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: > So you're arguing that a CS major should start by learning electronics > fundamentals, how gates work, and how to design hardware(*)? Because > that's what the concrete level *really* is. Start anywhere above that, > and you wind up needing to look both ways. Some very good schools still believe that Mike Meyer wrote: > Andrea Griffini writes: >> On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen >> wrote: >> Also concrete->abstract shows a clear path; starting >> in the middle and looking both up (to higher >> abstractions) and down (to the implementation >> details) is IMO much more confusing. > > So you're arguing that a CS major should start by learning electronics > fundamentals, how gates work, and how to design hardware(*)? Because > that's what the concrete level *really* is. Start anywhere above that, > and you wind up needing to look both ways. > > Admittedly, at some level the details simply stop mattering. But where > that level is depends on what level you're working on. Writing Python, > I really don't need to understand the behavior of hardware > gates. Writing horizontal microcode, I'm totally f*cked if I don't > understand the behavior of hardware gates. > > In short, you're going to start in the middle. You can avoid looking > down if you avoid certain classes of problems - but not everyone will > be able to do that. Since you can only protect some of the students > from this extra confusion, is it really justified to confuse them all > by introducing what are really extraneous details early on? > > You've stated your opinion. Personally, I agree with Abelson, Sussman > and Sussman, whose text "The Structure and Interpretation of Computer > Programs" was the standard text at one of the premiere engineering > schools in the world, and is widely regarded as a classic in the > field: they decided to start with the abstract, and deal with concrete > issues - like assignment(!) later. > > > *) "My favorite programming langauge is solder." - Bob Pease > From mwm at mired.org Sun Jun 5 20:46:03 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 05 Jun 2005 19:46:03 -0500 Subject: For review: PEP 343: Anonymous Block Redux and GeneratorEnhancements References: <7xmzq49v5f.fsf@ruckus.brouhaha.com> Message-ID: <86fyvw8g8k.fsf@guru.mired.org> Paul Rubin writes: > "Delaney, Timothy C (Timothy)" writes: >> Be sure to read the referenced PEPs (and the ones referenced from them) >> - they contain a lot of history. Also read PEP 346 for a competing PEP >> to PEPs 340 and 343 that gradually converged to PEP 343 - most >> importantly, it contains the rejected options (that seem to have been >> lost from PEPs 340 and 343). > > There was an interesting proposal (later rejected) from Raymond > Hettinger a while back, that allowed passing arguments into a > suspended generator, where they could be seen by the yield statement. > I don't remember specifics and it doesn't seem to be in any of those PEP's. > > Anyone remember more? I wonder whether 343 could somehow resurrect > the good parts of that. It sounds like you're remembering PEP 342. 343 references that, but doesn't include much of it. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From guettli at thomas-guettler.de Fri Jun 3 10:45:02 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 03 Jun 2005 16:45:02 +0200 Subject: Formatting Time References: Message-ID: Am Fri, 03 Jun 2005 09:29:41 +0100 schrieb Ognjen Bezanov: > I never thought id need help with such a thing as time formatting > (admittadly i never did it before) but ok, i guess there is a first for > everything. > > I have a float variable representing seconds, and i want to format it > like this: > > 0:00:00 (h:mm:ss) Hi, Does this work? (not well tested) i=12009 # Number of seconds res=[] # d h, m for d in [24*60*60, 60*60, 60]: res.append("%02d" % (i/d)) i=i%d res.append("%02d" % i) print ":".join(res) # --> 00:03:20:09 (d:h:m:s) -- Thomas G?ttler, http://www.thomas-guettler.de/ From deets at web.de Thu Jun 2 10:51:20 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 02 Jun 2005 16:51:20 +0200 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: rbt wrote: > Peter Hansen wrote: > >> Philosophy not entirely aside, you should note that object code in any >> language can "easily" be reverse-engineered in the same way, with the >> only difference being the degree of ease involved. If the code is >> worth enough to someone that they are willing to risk violating your >> license terms, they *will* be able to recover enough source code >> (whether it was Python, C, or assembly) to do what they need. > > > Don't intend to hijack this thread, but this bit interests me. I know > several accomplished C/assembly programmers who have told me that > reverse engineering object code from either of these two languages is > anything but trivial. Yet, I *hear* and *read* the opposite all of the > time. Can anyone actually demonstrate a decompile that mirrors the > original source? I give you one example: Online/Multiplayer GTA 3 or 4 (http://gta3mta.tk/) A C-App never intended to work that way - but skillfully patched so that it works! And that even only as OSS - no commercial interest (and thus funding). So I day Peter's statement has full validity - it's a question of interest. Diez From donald.welch at NOSPAM.hp.com Wed Jun 15 12:08:03 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Wed, 15 Jun 2005 09:08:03 -0700 Subject: Python in Games (was RE: [Stackless] Python in Games) References: <1118787883.193470.125620@f14g2000cwb.googlegroups.com> <42af69ad$0$96347$e4fe514c@news.xs4all.nl> Message-ID: <42b0538e@usenet01.boi.hp.com> Irmen de Jong wrote: > Patrick Down wrote: >> My understanding is that the upcoming Civilization IV will have python >> scripting. >> > > Also, alledgedly the new BattleField II uses Python in a way... > because I heard that you had to comment out a certain line > in a certain .py file to remove the time limit of the demo :-) > > --Irmen http://developers.slashdot.org/article.pl?sid=05/02/11/1439230&tid=156&tid=204 -Don From opengeometry at yahoo.ca Mon Jun 20 12:07:41 2005 From: opengeometry at yahoo.ca (William Park) Date: Mon, 20 Jun 2005 12:07:41 -0400 Subject: Python choice of database References: Message-ID: Philippe C. Martin wrote: > Hi, > > I am looking for a stand-alone (not client/server) database solution > for Python. > > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K > > As I start with Python objects, I thought of using shelve, but looking > at the restrictions (record size + potential collisions) I feel I > should study my options a bit further before I get started. Possible approach might be: 1. 5000 files -- my personal favourite. 2. GDBM 3. SQLite -- William Park , Toronto, Canada ThinFlash: Linux thin-client on USB key (flash) drive http://home.eol.ca/~parkw/thinflash.html BashDiff: Full featured Bash shell http://freshmeat.net/projects/bashdiff/ From thomasbartkus at comcast.net Mon Jun 27 16:48:08 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 27 Jun 2005 15:48:08 -0500 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: "Brian" wrote in message news:IjZve.10296$hK3.8182 at newsread3.news.pas.earthlink.net... > Hi Xeys, > > Even though I absolutely love Python... > > Microsoft Visual Basic (.NET) would be your best bet for this type of > software development. It allows you to create GUI apps that can work > with a variety of database options, such as Access or MS SQL Server. > > My personal opinion is this: > ---------------------------- > 1) Python shines the best on the server realm. > 2) VB.net shines the best on the client-computer realm. > I would modify that. 1) VB shines in the MS Windows/Office realm. 2) Python shines everywhere else. Thomas Bartkus From rrr at ronadam.com Tue Jun 28 19:59:45 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 28 Jun 2005 23:59:45 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: <86y88um4y3.fsf@bhuda.mired.org> References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <86y88um4y3.fsf@bhuda.mired.org> Message-ID: Mike Meyer wrote: > Riccardo Galli writes: > > >>On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote: >> >> >>>>Bo Peng wrote: >>>> >>>> >>>>>I need to pass a bunch of parameters conditionally. In C/C++, I can >>>>>do func(cond1?a:b,cond2?c:d,.....) >>>>> >>>>>Is there an easier way to do this in Python? >>>> >>>> >>>The answer is simply no, just use an if statement instead. >> >>That's not true. >>One used form is this: >>result = cond and value1 or value2 >> >>which is equal to >>if cond: >> result=value1 >>else: >> result=value2 >> >> >>another form is: >> >>result = [value2,value1][cond] >> >> >>the first form is nice but value1 must _always_ have a true value (so not >>None,0,'' and so on), but often you can handle this. > > > Note that [value2, value1][cond] doesn't do exactly what cond ? value1 : value2 > does either. The array subscript will always evaluate both value2 and > value1. The ?: form will always evaluate only one of them. So for > something like: > > [compute_1000_digits_of_pi(), compute_1000_digits_of_e][cond] > > you'd really rather have: > > cond ? compute_1000_digits_of_e() : compute_1000_digits_of_pi() > > There are other such hacks, with other gotchas. > > References: <311b5ce105062723167e892833@mail.gmail.com> <42C188F3.7010704@rt.sk> Message-ID: <311b5ce1050628002075da2e3@mail.gmail.com> Thank you, it works~~ On 6/29/05, Peter Szinek wrote: > Hi, > > What about this: > > import os,zipfile > from os.path import join > > > zip = zipfile.ZipFile("myzipfile.zip", 'w') > for root, dirs, files in os.walk('.'): > for fileName in files: > zip.write(join(root,fileName)) > zip.close() > > Maybe it zips also the myzipfile.zip ;-) > Probably this is not needed, so an additional test (something like > fileName != 'myfile.zip' would be needed. > > HTH, > Peter > > could ildg wrote: > > I want to compress a folder and all of its sub files including empty folders > > into a zip file. what's the pythonic way to do this? > > > > Thanks in advance. > > From Scott.Daniels at Acm.Org Sat Jun 4 13:10:45 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 04 Jun 2005 10:10:45 -0700 Subject: Walking through a mysql db In-Reply-To: References: <200506040924.25574.jeffelkins@earthlink.net> Message-ID: <42A1E095.6080905@Acm.Org> Jeff Elkins wrote: > On Saturday 04 June 2005 09:24 am, Jeff Elkins wrote: ... >>Now, how do I step through the dataset one row at a time? My form has >>'next' and 'back' buttons, and I'd like them to step forward or back, >>fetching the appropriate row in the table. I've tried setting >>cursor.rownumber by incrementing it prior to the fetchone() w/o effect. Conceptually RDB queries produce sets, not lists. The "row number" is more an artifact than a property, and (in general) the only way to get to the fifty-third is to step through the first fifty-two. If you need to go forward and back, pull the results into a python list (using fetchmany or fetchall) and walk through that list. > Within this same app, I've got a search function working, but I need the > rownumber when a record is fetched. > > sql = """select * from address where %s = %%s""" % arg1.lower() > cursor.execute(sql, (arg2,)) > item = cursor.fetchone () > index = cursor.rownumber > > At this point, the record is on the screen, but cursor.rownumber doesn't > reflect the actual rownumber...it always returns 1. How can I obtain the > actual row number for the displayed record? The "normal" way to do this is to make sure your query includes the key of the table you are querying. It is generally considered bad style (in the DB world) to use "SELECT *" above. Name the fields you are grabbing, and your code will survive more schema changes. The contents of the table's key column(s) _is_ the unique identifier of that row, not a "row number" (which may well change on a backup-restore for example). --Scott David Daniels at Acm.Org Scott.Daniels at Acm.Org From kveretennicov at gmail.com Wed Jun 22 07:07:25 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Wed, 22 Jun 2005 14:07:25 +0300 Subject: suggestions invited In-Reply-To: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> Message-ID: <4660fe3005062204072cf4243@mail.gmail.com> On 22 Jun 2005 02:47:06 -0700, Aditi wrote: > i have to make a system used by the IT department of a company which > contains 31 applications and their details which are being used in a > company ...the details are... > Application sub application catagory platform language version IT > owner functional owner remarks source code documentation last updated > dates > i want to design a system such that it lets the it employee enter the > name of the application and gives him all the details about it...please > suggest an appropriate design Ahem... Create a directory "appmon". In this directory create a text file for each application. Put application details in file and name it after application name. Users will be able to view details of a particular application by using "cat appname" on unix or "type appname" on windows, thus it is a portable solution. I believe this design fits your requirements :) - kv From sjmachin at lexicon.net Fri Jun 24 15:33:34 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 25 Jun 2005 05:33:34 +1000 Subject: autoconfigure vss python question In-Reply-To: References: Message-ID: <42BC600E.2080901@lexicon.net> lode leroy wrote: > Hi folks, > > I'm trying to build a python module using MINGW on MSYS > the "configure" script is determining where python is installed as follows: > > python.exe -c 'import sys; print sys.prefix' > c:\Python24 > > which is good on native windows (i.e. when invoked from CMD.EXE) > > Is there a way to configure something in python or in the environment > so that when invoked from MSYS, it would behave as follows: (note the > '/' vss '\') > > python.exe -c 'import sys; print sys.prefix' > c:/Python24 Any good reason for not using distutils? See this: http://www.python.org/doc/2.4.1/inst/tweak-flags.html#SECTION000622000000000000000 From onurb at xiludom.gro Tue Jun 28 10:53:22 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 28 Jun 2005 16:53:22 +0200 Subject: Dictionary to tuple In-Reply-To: References: Message-ID: <42c16464$0$26260$626a14ce@news.free.fr> Odd-R. wrote: > I have a dictionary, and I want to convert it to a tuple, > that is, I want each key - value pair in the dictionary > to be a tuple in a tuple. > > If this is the dictionary {1:'one',2:'two',3:'three'}, > then I want this to be the resulting tuple: > ((1,'one'),(2,'two'),(3,'three')). > > I have been trying for quite some time now, but I do not > get the result as I want it. Can this be done, or is it not > possible? It's of course possible, and even a no-brainer: dic = {1:'one',2:'two',3:'three'} tup = tuple(dic.items()) The bad news is that dict are *not* ordered, so you'll have to sort the result yourself if needed :( The good news is that sorting a sequence is a no-brainer too !-) > I must also add that I'm new to Python. Welcome on board. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jacob at cd.chalmers.se Mon Jun 20 20:06:44 2005 From: jacob at cd.chalmers.se (Jacob Hallen) Date: 21 Jun 2005 00:06:44 GMT Subject: Europython 2005 - last call Message-ID: Europython 2005 will start on Monday 27 June! If you haven't preregistered for Europython 2005, you still have a few hours to do so. You can register and pay by credit card until 21 June 18.00 CEST. Payment by SWIFT/IBAN is closed, since we would not receive your payment before the conference starts. On-site registration is also possible, though at a somewhat higher cost. Pyment on-site is in cash, SEK or Euro. Please bring even money since we can't have a big pile of change at the conference. All details are found at http://www.europython.org. -- From smadim2 at grads.ece.mcmaster.ca Tue Jun 28 14:41:36 2005 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Tue, 28 Jun 2005 14:41:36 -0400 Subject: ethereal parser Message-ID: <42C199E0.5070700@grads.ece.mcmaster.ca> hi; i am looking for 802.11 prism header parser for an ethereal text dump. any body aware of something like already in place? thanks m.smadi From newsuser at stacom-software.de Tue Jun 21 09:15:32 2005 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 21 Jun 2005 15:15:32 +0200 Subject: Howto access a enumeration in a COM TypeLib In-Reply-To: References: Message-ID: Thanks, thats it. Konstantin Veretennicov schrieb: >>>>import myserver >>>>print myserver.constants. P_OK > 0 > > Maybe you can access constants without makepy, I don't know. > > - kv From kveretennicov at gmail.com Thu Jun 23 05:46:35 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 23 Jun 2005 12:46:35 +0300 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: <7xslz93nh2.fsf@ruckus.brouhaha.com> References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> <7xslz93nh2.fsf@ruckus.brouhaha.com> Message-ID: <4660fe300506230246771ebf78@mail.gmail.com> On 22 Jun 2005 17:50:49 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Even on a multiprocessor > system, CPython (because of the GIL) doesn't allow true parallel > threads, ... . Please excuse my ignorance, do you mean that python threads are always scheduled to run on the same single CPU? Or just that python threads are often blocked waiting for GIL? - kv From cdkrug at worldnet.att.net Tue Jun 21 09:18:59 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Tue, 21 Jun 2005 13:18:59 GMT Subject: Loop until condition is true References: Message-ID: <7tUte.999671$w62.936895@bgtnsc05-news.ops.worldnet.att.net> On Tue, 21 Jun 2005 12:05:25 +0200, Magnus Lycka wrote: > Remi Villatel wrote: >> while True: >> some(code) >> if final_condition is True: >> break >> # >> # >> >> What I don't find so "nice" is to have to build an infinite loop only to >> break it. > > This is a common Python idiom. I think you will get used to it. > > >> Is there a better recipe? > > final_condition = False > while not final_condition: > some(code) To the OP, don't get hung up on the syntax we use to implement a loop. I took my first programming class long enough ago that we had to do things like this (roughly translating the FORTRAN IV I remember into p-code) To do: while TrueCondition (loop body) we'd have to write: TopOfLoop: if not TrueConditional goto loopEnd (loop body) goto TopOfLoop loopEnd: We were even required to write our source twice: The first pass was "structured" and had to be proven correct. The second pass was translated into something our compiler supported. We still called it a "while loop" even though the syntax was icky. When C came out with its built in looping, it was an unbelievable luxury. From rogerb at rogerbinns.com Fri Jun 10 13:08:48 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Fri, 10 Jun 2005 10:08:48 -0700 Subject: Generating HTML from python References: Message-ID: <45uon2-fb9.ln1@home.rogerbinns.com> "Philippe C. Martin" wrote in message news:HPWpe.2034$I14.173 at newssvr12.news.prodigy.com... > Hi, > > I wish to use an easy way to generate reports from wxPython and feel > wxHtmlEasyPrinting could be a good solution. > > I now need to generate the HTML wxHtmlEasyPrinting can print: I need to have > a title followed by lines of text that do not look too ugly. If possible I > would like to use an existing module. > > Q1) Is there such a module ? > Q2) Is my approach fairly good ? There is one huge problem with wxHtml and consequently wxHtmlEasyPrinting. It doesn't understand stylesheets in any way. There are many packages that generate HTML, but they all expect a lot of the styling to be handled by CSS. It is also a lot easier to write that way. I would absolutely love a piece of code that could take CSS and HTML and apply the CSS to the HTML to get the right appearance, but without any CSS left. For example it would turn CSS formatting for class/div/span into HTML attributes, as well as overal formatting instructions. I did do something similar for BitPim but it requires the HTML to be perfect and the CSS is actually a Python data structure expressing the attributes and how they get applied. I'd love to replace it with something better. But ultimately it does work. Roger From bvande at po-box.mcgill.ca Tue Jun 21 04:00:59 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 21 Jun 2005 04:00:59 -0400 Subject: A tool for Python - request for some advice In-Reply-To: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> Message-ID: <42B7C93B.4030306@po-box.mcgill.ca> TPJ said unto the world upon 21/06/2005 02:00: > First I have to admit that my English isn't good enough. I'm still > studying and sometimes I just can't express what I want to express. I've graded essays in Philosophy at my university that were written by native speakers of English yet were substantially less clear and well written than your post. I don't think you will need to lead with an apology for your language skills in the future :-) > A few weeks ago I've written 'Python Builder' - a bash script that > allows anyone to download, compile (with flags given by user) and > install Python and some external modules (e.g. wxPython, PyGTK, > kind. My need is very special - I want to have Python, it's modules and > sometimes documentation installed in particular place; usually > somewhere in my home directory. My script installs some additional > I've written this script in bash, because I thought it would be better > to have a script which would run in environment without Python (it all > was about installing Python anyway!). I used bash, dialog, wget... And > now someone suggested, that I shuld use Python. That using Python would > lead to clearer and - probably - smaller code. (I have to admit it - my > code in bash is just messy.) > > And now I'm considering this idea. Python is already present on > (almost?) every distribution today, so why worry about it's presence? > But, on the other hand, I'm thinking that writing in bash is more > universal solution. I mean that requirements to run bash scripts are > lower than requirements to run Python scripts. Could this requirements > be decisive for some users (or is it only my imagination)? Sometimes > users just have no access to Python (e.g. LFS, some stages of Gentoo, > some rescue and specialized distros). > Well, what do you think? I'm not a sophisticated programmer (I wouldn't know a bash script if it bit me). So, to make sure I've understood (the issue is my level of knowledge, not your level of English): you want to provide a specialized install script for Python (3rd party modules, non-standard locations, etc.) You started in bash to deal with minority cases without an extant Python install. But clearly, there will be a Python install by the time your bash script is done, or something will have gone very wrong. That suggests implementing the custom installation work in Python, and having a bash script that will 1) determine if there is an existing Python install, 2) if there is not, install Python in the standard way, 3) using the now guaranteed to be there installation of Python, run your Python script that does all of your custom installation, and 4) if step (2) added a Python installation other than the one added by step (3), perhaps remove it. Am I missing some reason why that wouldn't be a satisfactory option? (This is entirely possible :-) Best, Brian vdB From steve at REMOVETHIScyber.com.au Sat Jun 25 14:36:51 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 04:36:51 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote: > On 6/25/05, Mandus wrote: >> It is really a consensus on this; that >> removing map, filter, reduce is a good thing? It will render a whole lot >> of my software unusable :( > > I think you'll be able to use "from __past__ import map, filter, > reduce" or something like that :) They don't have to be built-in. More likely they will be moved to something like itertools than "__past__". Or just define them yourself: def map(f, seq): return [f(x) for x in seq] def filter(p, seq): return [x for x in seq if p(x)] def reduce(f, seq, zero): r = zero for x in seq: r = f(r, x) return r -- Steve. From duncan.booth at invalid.invalid Tue Jun 21 09:39:54 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jun 2005 13:39:54 GMT Subject: tree functions daily exercise: Table References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119357221.467207.149480@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > '''Table(f,[iStart,iEnd,iStep]) returns a list of f applied to the > range range(iStart,iEnd,iStep). Example: Table(f,[3,10,2]) returns > [f(3),f(5),f(7),f(9)] Table(f,[iStart,iEnd,iStep], > [jStart,jEnd,jStep], ...) returns a nested list of f(i,j,...) applied > thru the iterators. Example: Table(f,[1,3,1],[2,6,2]) returns > [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]]''' How does it know when to skip the end value (i.e. act as for the rest of Python) and when to include it? Or did you mean: Table(f,[1,3,1],[2,7,2]) returns [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]] Wouldn't it be more sensible just to take the iterators directly as arguments, so for this example you would do: Table(f, range(1,3), range(2,7,2)) That way you have more flexibility (e.g. to do out-of-order ranges such as [1,3,2,0,4]), and the code for Table is much simpler since it just has to manipulate the lists it was given. From seefeld at sympatico.ca Thu Jun 9 22:56:16 2005 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Thu, 09 Jun 2005 22:56:16 -0400 Subject: Announcement: Synopsis 0.8 Message-ID: I'm pleased to announce the release of Synopsis 0.8. Synopsis is a multi-language source code introspection tool that provides a variety of representations for the parsed code, to enable further processing such as documentation extraction, reverse engineering, and source-to-source translation. While this release mainly focusses on an internal redesign, there are nevertheless a number of major enhancements and new features: * Synopsis contains a new C Parser. * The C++ parser contains lots of bug fixes. * The HTML formatter contains a number of bug fixes. Synopsis' internals have been largely redesigned, to eventually expose public C++ and python APIs to the lower-level code representations such as parse trees or symbol tables. It currently contains experimental code to use synopsis as a scriptable source-to-source compiler, though these APIs are still in development. Source and documentation is available at http://synopsis.fresco.org. For contact information, see http://synopsis.fresco.org/contact.html. From roy at panix.com Fri Jun 17 19:11:35 2005 From: roy at panix.com (Roy Smith) Date: 17 Jun 2005 19:11:35 -0400 Subject: What is different with Python ? References: <6lg6b1568j7lu52g18kcmrsks48saib0rj@4ax.com> Message-ID: Andrea Griffini wrote: > Add to the picture the quality of [C++] compile time error messages > from the primitive template technology and even compile time errors > often look like riddles; Yeah, but what they lack in quality, they make up for in quantity. > if you forget a "const" you don't get "const expected"... you get > two screens full of insults pointing you in the middle of a system > header. Python and C++ complement each other quite nicely. For example, one of the first things I did when I was learning C++ was to write a Python program which parsed and re-formatted C++ compiler error messages so they were easier to read :-) From steven.bethard at gmail.com Fri Jun 17 23:19:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Jun 2005 21:19:08 -0600 Subject: Why is there no instancemethod builtin? In-Reply-To: References: Message-ID: John Reese wrote: > I now do: > if isinstance(x, list): [snip] > > I'm not saying I do it a lot, but sometimes it's useful to write > methods with interfaces like, well, isinstance's, whose second argument > can be a single type object or a sequence of class objects. Personally, I'd just write these functions with a *args instead, e.g.: def my_isinstance(obj, *types): return isinstance(obj, types) Sure, it's not an option if you need multiple type lists, but how often does that happen? STeVe From simon.brunning at gmail.com Wed Jun 22 04:00:23 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 22 Jun 2005 09:00:23 +0100 Subject: getting an object name In-Reply-To: References: Message-ID: <8c7f10c605062201007c79db0d@mail.gmail.com> On 6/22/05, David Bear wrote: > Let's say I have a list called, alist. If I pass alist to a function, > how can I get the name of it? The effbot put it beautifully: "The same way as you get the name of that cat you found on your porch: the cat (object) itself cannot tell you its name, and it doesn't really care -- so the only way to find out what it's called is to ask all your neighbours (namespaces) if it's their cat (object) ... and don't be surprised if you'll find that it's known by many names, or no name at all!" -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From philippe at philippecmartin.com Mon Jun 27 19:48:20 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 27 Jun 2005 23:48:20 GMT Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Message-ID: <8f0we.368$Ox3.299@newssvr12.news.prodigy.com> Hi, I had the exact opposite problem :-) Hope this helps Regards, Philippe #******************************************************************** def Mail(self,p_data): #data is string of text you = wx.GetTextFromUser('EMAIL ADDRESS','ID') if len(you) == 0: return self.__m_config = Config() self.__m_config.Load() me = self.__m_config.dict['ACCOUNT'] host = self.__m_config.dict['SMTP'] s = smtplib.SMTP() s.connect(host) s.login(me,self.__m_config.GPW()) the_text = p_data msg = MIMEText(the_text) # ***************GET RID OF THIS LINE TO HAVE PLAIN TEXT ************************************ msg.replace_header('Content-Type', 'text/html') # ***************GET RID OF THIS LINE TO HAVE PLAIN TEXT ************************************ #msg.add_header('Content-Type', 'text/html') msg['To'] = you msg['Subject'] = self.__m_title msg['From'] = self.__m_config.dict['FROM'] s.sendmail(me, [you], msg.as_string()) self.__m_list = [] Inkiniteo wrote: > Hi guys. I have a script that sends the info by email, but i'd like to > avoid the convertion to HTML by the email client or Gmail, because it > ruins all the formatting i did (with tabs, mostly). Briefing, i wanna > be able to send SMTP mail and the receiver only get it in plain text. From kveretennicov at gmail.com Wed Jun 22 17:32:55 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Wed, 22 Jun 2005 23:32:55 +0200 Subject: No subject In-Reply-To: <54D46A9CCE56F04D802E186634F8BCA701E58050@pros-mail.prosrm.com> References: <54D46A9CCE56F04D802E186634F8BCA701E58050@pros-mail.prosrm.com> Message-ID: <4660fe30050622143249850ebf@mail.gmail.com> On 6/22/05, Doug Ly wrote: > Is there a good IDE for Python? See http://tinyurl.com/8jqjc - kv From http Wed Jun 1 14:34:33 2005 From: http (Paul Rubin) Date: 01 Jun 2005 11:34:33 -0700 Subject: Python as client-side browser script language References: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> Message-ID: <7xk6leylhi.fsf@ruckus.brouhaha.com> Magnus Lycka writes: > Of course, one might suggest that it's the task of the browser, > and not of the scripting language, to provide a safe sandbox > where scripts can mess around and without causing havoc on > your computer. Such a system in the browser could be used to > grant different rights to different parts of the net, regardless > of what kind of scripting language the resources on those parts > of the net use. When Firefox has something like that, it's time > to start marketing Python for client side scripting I think. Huh? The language itself has to provide the sandbox. If the browser's control over the script language is so fine-grained as to control every attribute access then the browser and the language are no longer separate. Remember that scripts have to be able to see certain DOM elements but not others, and some of them have to be read-only, etc. From ironfroggy at gmail.com Wed Jun 1 12:36:05 2005 From: ironfroggy at gmail.com (ironfroggy) Date: 1 Jun 2005 09:36:05 -0700 Subject: metaclass that inherits a class of that metaclass? Message-ID: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> Hoping this isn't seeming too confusing, but I need to create a metaclass and a class using that metaclass, such that one of the bases of the metaclass is the class created with that metaclass. I can't figure out a way to do this, even after trying to add the class as a base after the classes have been created. Is there some way I can get this to work properly? From meren at uludag.org.tr Fri Jun 24 05:29:31 2005 From: meren at uludag.org.tr (A. Murat Eren) Date: Fri, 24 Jun 2005 12:29:31 +0300 Subject: zipfile + symlink [Solved].. In-Reply-To: <200506232343.33577.meren@uludag.org.tr> References: <200506232343.33577.meren@uludag.org.tr> Message-ID: <200506241229.35497.meren@uludag.org.tr> Hi again, On Thursday 23 June 2005 23:43, A. Murat Eren wrote: > I have a problem about zipfile. I solved the problem and want to share my solution for archiving purposes (Hi Googlers ;)).. > -------8<-------------------8<--------------------8<------------------8<--- > def add_file(self, fileName): > """add file or directory to a zip file""" > if os.path.isdir(fileName): > self.zip.writestr(fileName + '/', '') > for f in os.listdir(fileName): > self.add_file(fileName + '/' + f) > else: > if os.path.islink(fileName): > dest = os.readlink(fileName) > self.zip.writestr(fileName, dest) > #do something here to set 'fileName's attributes > #to write it as a symlink into the zip > else: > self.zip.write(fileName, fileName, zipfile.ZIP_DEFLATED) > > ------->8------------------->8-------------------->8------------------>8--- >-- > > But here is a problem raising for symlinks (at the commented section of > the code passage).. If i don't perform any special process for symlinks in > the function, function produces zip files without symlinks, naturally; > symlinks become regular files with the 'dest' content.. I have to set the > attribute of the symlinks in the zip to make them a real symlink for the > 'dest', how can i do that? Here is the solution for adding properly both dir and file symlinks into a zipfile: -------8<-------------------8<--------------------8<------------------8<--- def add_file(self, fileName): """Add file or directory to a zip file""" if os.path.isdir(fileName) and not os.path.islink(fileName): self.zip.writestr(fileName + '/', '') for f in os.listdir(fileName): self.add_file(fileName + '/' + f) else: if os.path.islink(fileName): dest = os.readlink(fileName) attr = zipfile.ZipInfo() attr.filename = fileName attr.create_system = 3 attr.external_attr = 2716663808L # long type of?hex val # of '0xA1ED0000L' # say, symlink attr magic.. self.zip.writestr(attr, dest) else: self.zip.write(fileName, fileName, zipfile.ZIP_DEFLATED) ------->8------------------->8-------------------->8------------------>8--- When you trying to unpack this zipfile (or any zip file which contains symlinks), you have to check this value instead of directly reading from zip and writing to the file system: -------8<-------------------8<--------------------8<------------------8<--- info = zip.getinfo(fileName) if hex(info.external_attr) == 2716663808L: target = zip.read(fileName) os.symlink(target, ofile) ------->8------------------->8-------------------->8------------------>8--- Ciao, -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - A. Murat Eren meren at uludag.org.tr http://cekirdek.uludag.org.tr/~meren/ 0x527D7293, 7BCD A5A1 8101 0F6D 84A4 BD11 FE46 2B92 527D 7293 - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- Alan Cox sounds as if he hasn't followed the development of programming languages and compilers for the last 10 years (exa). - -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From skromta at gmail.com Mon Jun 13 16:50:56 2005 From: skromta at gmail.com (Kalle Anke) Date: Mon, 13 Jun 2005 22:50:56 +0200 Subject: How to get/set class attributes in Python References: <0001HW.BED206D2002D2163F0407550@news.gmane.org> Message-ID: <0001HW.BED3BE5000197B71F0488550@news.individual.de> On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote (in article ): > 1) Assume the variables are of a sensible type (not > necessarily the one you expected, though), and provide > exception handling to catch the case where their interface > does not match what you expect. The problem I have with this is that I might discover an error at runtime instead of compile time, this means that I need to really exercise all possible test cases to make sure that I've covered everything (which of course is a good thing) but it would be easier to discover this at "compile time". (note: I'm not trying to change Python, only that to me statically typing has it advantages also) > Let's face it -- should it matter if you "are a programmer" > or only if you "can program"? This is the difference in > philosophy behind a dynamically-typed language like > Python and a statically typed one like Java. I don't really understand what you're meaning (English isn't my native language as you probably already have discovered) From dalke at dalkescientific.com Sun Jun 5 08:46:18 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 05 Jun 2005 12:46:18 GMT Subject: any macro-like construct/technique/trick? References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <86oeala1mq.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > I've never tried it with python, but the C preprocessor is available > as 'cpp' on most Unix systesm. Using it on languages other than C has > been worthwhile on a few occasions. It would certainly seem to > directly meet the OP's needs. Wouldn't that prohibit using #comments in the macro-Python code? I suppose they could be made with strings, as in "here is a comment" do_something() but it's ... strange. Andrew dalke at dalkescientific.com From rkern at ucsd.edu Fri Jun 10 14:32:37 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 10 Jun 2005 11:32:37 -0700 Subject: Python Developers Handbook In-Reply-To: <42A9DAC3.2010306@anvilcom.com> References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <42A9DAC3.2010306@anvilcom.com> Message-ID: phil wrote: > Not taking a position for or against the original post: > > Everytime this comes up, on any group, one little annoying > post results in and endless discussion and sometimes > hurtful flame war. Ah, USENET! > Perhaps the rest of us should let the moderator handle it > and get back to something interesting, like Python. There is no moderator. We are all moderators. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jzgoda at gazeta.usun.pl Mon Jun 27 15:38:39 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 27 Jun 2005 21:38:39 +0200 Subject: delphi to python converter In-Reply-To: References: Message-ID: Thys Meintjes napisa?(a): > I have need of a Delphi/pascal to python converter. Googling didn't > suggest any obvious leads so I'm trying here... Don't think something like that even exists... -- Jarek Zgoda http://jpa.berlios.de/ From hancock at anansispaceworks.com Tue Jun 14 03:32:59 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 14 Jun 2005 02:32:59 -0500 Subject: "also" to balance "else" ? In-Reply-To: References: Message-ID: <200506140232.59605.hancock@anansispaceworks.com> On Tuesday 14 June 2005 12:07 am, Ron Adam wrote: > Terry Hancock wrote: > > On Monday 13 June 2005 11:09 pm, Ron Adam wrote: > >>My suggestion is to use, also as the keyword to mean "on normal exit" > >>'also' do this. > > Unfortunately, "also" is also a bad keyword to use for this, IMHO. > > I don't find it any more intuitive than "else". (And since your idea > > would break if-else code, I don't think it would be allowed, anyway). > > How would it break the current if-else? I meant "for-else". Typo, sorry. The point is though, that there is a fairly strict rule against breaking old code, AFAICT. Which makes the issue academic, "for-else" will continue to mean what it currently does. > > I can't think of what would be a better keyword, though. :-/ > > Well there's 'not-else' or 'nelse' Ack! Just kidding of course. No, I know what it should be. It should be "finally". It's already a keyword, and it has a similar meaning w.r.t. "try". ISTM, that it would have to be a synonym for "else" though to be accepted on the backwards-compatibility criterion, and then it would be "more than one way to do it" which breaks the Zen. ;-) Personally, though, "for-finally" would make a lot more sense to me than "for-else" (and I don't have enough "for-else" code to worry about it breaking). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tzot at sil-tec.gr Mon Jun 27 19:02:56 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 02:02:56 +0300 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Message-ID: On 27 Jun 2005 15:38:59 -0700, rumours say that "Inkiniteo" might have written: >Hi guys. I have a script that sends the info by email, but i'd like to >avoid the convertion to HTML by the email client or Gmail, because it >ruins all the formatting i did (with tabs, mostly). Briefing, i wanna >be able to send SMTP mail and the receiver only get it in plain text. Please tell us what you do more precisely: * do you send the "info" as an attachment using the email package? * do you create alternative text and HTML parts for the body? I have never managed to send plain text email and receive it as HTML. Perhaps you mean that some "smart" client does something stupid with your text, eg. it removes line-breaks you have in your message? Try this: import smtplib def send(server, from_whom, to_whom_list): smtp = smtplib.SMTP(server) smtp.sendmail(from_whom, to_whom_list, """From: %s To: %s Subject: test email This is a test. It has line breaks. Does it come as three separate lines?""") I tried it as send('localhost', 'tzot at sil-tec.gr', ['tzot at sil-tec.gr']) and I had no problem. What happens for you (substitute other server and email addresses, obviously :) ? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From cam.ac.uk at mh391.invalid Wed Jun 29 04:17:01 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 29 Jun 2005 09:17:01 +0100 Subject: How to compare two directories? In-Reply-To: References: Message-ID: could ildg wrote: > I want to compare 2 directories, > and find If all of theire sub-folders and files and sub-files are identical. > If not the same, I want know which files or folders are not the same. > I know filecmp moudle has cmpfiles function and a class named dircmp, > they may help, but I wonder if there is a ready-to-use function in python libs? That's a good start. Why doesn't dircmp work for you? -- Michael Hoffman From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Mon Jun 27 03:43:52 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Mon, 27 Jun 2005 09:43:52 +0200 Subject: Sorting part of a list In-Reply-To: <94bob15coj5gd3kp8k0c8fcram2jm80n95@4ax.com> References: <3i29tfFjgph8U1@news.dfncis.de> <94bob15coj5gd3kp8k0c8fcram2jm80n95@4ax.com> Message-ID: <3i9p1oFkio5rU1@news.dfncis.de> Dennis Lee Bieber schrieb: > On Fri, 24 Jun 2005 13:42:39 +0200, Sibylle Koczian > declaimed the following in > comp.lang.python: > > > ll[2:] = ... > > is not an object creation, merely an access into an existing object. > That's what I hadn't understood. Although it's the same with ll[2]. > > I'm still running 2.3.x -- did "sorted()" make it into 2.4? As I > recall the discussion, the idea was to have a sort operation that would > return the sorted data, instead of the current in-place sort and return > of None. That would allow for: > > ll[2:] = ll[2:].sorted() > It's not a list method, but it's a function: >>> ll = [3, 1, 4, 2] >>> ll[2:] = ll[2:].sorted() Traceback (most recent call last): File "", line 1, in -toplevel- ll[2:] = ll[2:].sorted() AttributeError: 'list' object has no attribute 'sorted' >>> but this works: >>> ll = [3, 1, 4, 2] >>> ll[2:] = sorted(ll[2:]) >>> ll [3, 1, 2, 4] I'm using 2.4, but didn't look carefully at the changes. Thanks to all who answered! Sibylle -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From sun.aries at gmail.com Sat Jun 25 01:23:06 2005 From: sun.aries at gmail.com (sun.aries at gmail.com) Date: 24 Jun 2005 22:23:06 -0700 Subject: How does one write a function that increments a number? In-Reply-To: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> Message-ID: <1119676986.613202.315140@g47g2000cwa.googlegroups.com> Hi, please refer to the sections about the augments passing in Python tutorial. Python?s pass-by-assignment scheme isn?t the same as C++?s reference parameters, but it turns out to be very similar to C?s arguments in practice: ? Immutable arguments act like C's "by value" mode. Objects such as integers and strings are passed by object reference (assignment), but since you can't change immutable objects in place anyhow, the effect is much like making a copy. ? Mutable arguments act like C's "by pointer" mode. Objects such as lists and dictionaries are passed by object reference, which is similar to the way C passes arrays as pointers?mutable objects can be changed in place in the function, much like C arrays. Let?s have a try: >>> def incr(counters): counters[0] += 1 >>> counters =[100] >>> incr(counters) >>> print counters [101] >>> From kent37 at tds.net Fri Jun 10 12:20:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Jun 2005 12:20:06 -0400 Subject: Changing entities In-Reply-To: <1118416101.261858.306910@f14g2000cwb.googlegroups.com> References: <1118235783.224018.281490@g44g2000cwa.googlegroups.com> <42a6ed6e$1_1@newspeer2.tds.net> <1118416101.261858.306910@f14g2000cwb.googlegroups.com> Message-ID: <42a9bd5a$1_2@newspeer2.tds.net> Daniel wrote: > Hi Kent > > This isn't work with the following line: > FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 > BYTES) > > >>>>byter = re.compile(r'SIZE \((\d+) BYTE\)') Because the string doesn't match the pattern, can you see the difference? Do you understand what the regex is looking for? Another good way to learn about regexes is with the Regex Demo program distributed with Python. Look for Tools\Scripts\redemo.py Kent From dlc at io.frii.com Tue Jun 21 13:10:39 2005 From: dlc at io.frii.com (Dennis Clark) Date: Tue, 21 Jun 2005 17:10:39 -0000 Subject: Embedded Systems Python? References: <11bdnto1au02i63@corp.supernews.com> <3hol9dFi5e6lU2@uni-berlin.de> Message-ID: <11bgigfpu3i3s04@corp.supernews.com> Guys, Thanks, that was all information that I wanted to hear. I have a Cirrus Logic Linux port for the ARM9. I've no idea what the code base is, I've not figured that out yet. I should just need to re- compile on the platform. thanks, DLC -- ============================================================================ * Dennis Clark dlc at frii.com www.techtoystoday.com * * "Programming and Customizing the OOPic Microcontroller" Mcgraw-Hill 2003 * ============================================================================ From Nicholas.Vaidyanathan at asu.edu Fri Jun 17 11:17:17 2005 From: Nicholas.Vaidyanathan at asu.edu (Nicholas.Vaidyanathan at asu.edu) Date: Fri, 17 Jun 2005 08:17:17 -0700 (MST) Subject: Help implementing an idea Message-ID: <1119021437.42b2e97d54297@webmail.asu.edu> Well, I'm a total python n00b, but I was playing around with exception handling yesterday, and was stricken by how incredibly easy it is to use the op system to create nice scripts... I did the following: import sys lines = sys.stdin.readlines() lines.sort() for stuff in lines: print stuff , just to copy stuff from one file to another, and was quite impressed with the results. Now, I was thinking today, I'd really like to create a program that can go to a specific directory and upload all the files in the directory to a specific url for backup purposes, and I have the feeling that the python implementation would be ruthlessly small and efficient, like the above....anyone who could point me in the right direction as to how to actually do it? From future_retro at yahoo.co.uk Wed Jun 22 11:35:11 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 22 Jun 2005 08:35:11 -0700 Subject: python create WMI instances In-Reply-To: References: Message-ID: <1119454511.871522.117990@g44g2000cwa.googlegroups.com> Win32_Printer doesn't work with the Create method and AddPrinterConnection only lets me add a connection to a share. I'll try and work out how to set the printer object properties in the format suggested; oPrinter.Properties_ ("DriverName").Value = strDriver Cheers, MW. From python-url at phaseit.net Wed Jun 22 12:02:48 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 22 Jun 2005 16:02:48 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 22) Message-ID: QOTW: "Python is more concerned with making it easy to write good programs than difficult to write bad ones." - Steve Holden "Scientists build so that they can learn. Programmers and engineers learn so that they can build." - Magnus Lycka "It happens that old Java programmers make one module per class when they start using Python. That's more or less equivalent of never using more than 8.3 characters in filenames in modern operating systems, or to make a detour on your way to work because there used to be a fence blocking the shortest way a long time ago." - Magnus Lycka Python doesn't currently have a case or switch statement. Case blocks are easily simulated with if, elif, and else, but would Python's readability benefit from having it built in?: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/29e45afc78adcd15 A Podcast worth listening to at last. Guido speaks on Python's history and community: http://www.itconversations.com/shows/detail545.html http://www.itconversations.com/shows/detail559.html If your class implements __eq__ but not __ne__, (a = b) does not imply !(a != b). If this something that should be fixed, or just a "gotcha"? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f6e0986b2c0f01c0 John Machin instructively analyzes several of Excel's defects as a data-management vehicle, obliquely highlighting Python's Zen. Tim Roberts follows up with a small but potentially crucial addendum pertinent, among others, to those who deal with USA "zip codes": http://groups-beta.google.com/group/comp.lang.python/index/browse_frm/thread/d14b13c8bc6e8515/ Recent (unreleased) work on distutils allows you to automatically upload packages to PyPI: http://www.amk.ca/diary/archives/003937.html Text files and line endings; Python helps you out on Windows, which can be a little confusing: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2d3f61b949bca0e9 Kalle wants to protect his instance attributes. He's warned off the idea, but at the same time, alex23 demonstrates an interesting way of doing it using properties(): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9f7c29fed95d7586 Creating a Python iterator by wrapping any callable: http://bob.pythonmac.org/archives/2005/06/14/python-iterators-and-sentinel-values/ Richard Lewis wants resumable exceptions. Python doesn't have them, but Peter Hansen shows him how to achieve what he wants, and Willem shows us how resumable exceptions work in Lisp: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e3dafce228dd4258 Jan Danielsson is confused about the difference between __str__ and __repr__, and what they are both for: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b37f1e3fae1154d6 The Kamaelia Framework; communicating with and linking Python generators: http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml Ron Adams proposes an "also" block to be executed if a "for" loop's "else" block isn't, and more controversially, that the "else" block's meaning be switched: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b15de260c5ca02e0 How you convince your marketing drones that switching from Python to Java would be A Bad Thing? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5b6d1ff54640e9b1 Why should an ambitious 14-year-old look at Python? (And why source-code hiding is a waste of time.) http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/107a4da1dd45b915 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From dberlin at gmail.com Thu Jun 30 14:37:18 2005 From: dberlin at gmail.com (dberlin at gmail.com) Date: 30 Jun 2005 11:37:18 -0700 Subject: Generic communications module with a little help from classes... Message-ID: <1120156638.560379.208550@g14g2000cwa.googlegroups.com> Hi, What I want to do is create a module that offers a generic set of functions (send, recieve, etc...) and reffers the request to the correct module (rs-232, tcp/ip, etc..). I want all this to be unseen by the script that calls this module. I want the script to specify the communication type, and then be able to use the functions. In the future, when the whole script will work on a different type of communication all that will be changed is the type of communication property. How do I do this? I thought of a few possibilities: 1. all communication modules will have the same function names and same number of params (problematic), and then it will look like this: class module1: def send(self): # send one way class module2: def send(self): # send the other if X: selected = module1 else: selected = module2 class main(selected): pass m = main() m.send() 2. the other option is creating a "wrapper" class for each module. this class takes the generic params of the function "send" and organizes the params and name so it will be compatible with the comm module: class a: def send(self, what): module1.sendCMD(what) class b: def send(self, what): module2.SEND(what) if X: selected = a else: selected = b class main(selected): pass m = main() m.send() ############# which way is better? any better ideas? thanks. From pdemb at gazeta.pl Sat Jun 4 06:05:31 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sat, 04 Jun 2005 12:05:31 +0200 Subject: idiom for constructor? References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> <87acm6e9ei.fsf@hector.domek> Message-ID: <8764wue8t0.fsf@hector.domek> Peter Dembinski writes: [snap] Eh, sorry, it should look like this: > #v+ > > class A: > def __init__(self, a, b, c, d): > initial = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4} initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d} > > for param in initial.keys(): > exec "self.%s = initial['%s']" % (param, param) > > #v- From mwm at mired.org Sun Jun 5 00:06:21 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 04 Jun 2005 23:06:21 -0500 Subject: any macro-like construct/technique/trick? References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: <86oeala1mq.fsf@guru.mired.org> Andrew Dalke writes: > Mac wrote: >> Is there a way to mimic the behaviour of C/C++'s preprocessor for >> macros? > > There are no standard or commonly accepted ways of doing that. > > You could do as Jordan Rastrick suggested and write your own sort > of preprocessor, or use an existing one. I've never tried it with python, but the C preprocessor is available as 'cpp' on most Unix systesm. Using it on languages other than C has been worthwhile on a few occasions. It would certainly seem to directly meet the OP's needs. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From duikboot at localhost.localdomain Tue Jun 28 03:39:14 2005 From: duikboot at localhost.localdomain (db) Date: Tue, 28 Jun 2005 09:39:14 +0200 Subject: Newbie: Help Figger Out My Problem References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> Message-ID: On Tue, 28 Jun 2005 00:23:30 -0700, ChuckDubya wrote: > ##Coin Flip: randomly flips 100 "coins" and prints results > ##Original draft: june 27, 2005 > ##Chuck > > import random > heads = 0 > tails = 0 > flips = 0 > while flips < 99: > coin = random.randrange(0, 2) > if coin == 0: > heads = heads + 1 > else: > tails = tails + 1 > flips = flips + 1 > if flips >= 99: > print "Heads: " + heads > print "Tails: " + tails > print "Total: " + flips + "flips" > raw_input("Press the enter key to exit.") > > > > When I save and run this "program", I get a DOS window that flashes at > me and disappears. What's wrong with it? Your programm gives an error. You are trying to concatenate strings with integers. http://docs.python.org/lib/typesseq-strings.html import random heads = 0 tails = 0 flips = 0 while flips < 99: coin = random.randrange(0, 2) if coin == 0: heads = heads + 1 else: tails = tails + 1 flips = flips + 1 if flips >= 99: print "Heads: %s" % heads ## string formatting print "Tails: %s" %tails ## string formatting print "Total: %s flips" % flips ## string formatting raw_input("Press the enter key to exit.") hth Arjen From kbk at shore.net Thu Jun 30 00:35:04 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 30 Jun 2005 00:35:04 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200506300435.j5U4Z49Y015752@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 344 open ( +6) / 2875 closed ( +9) / 3219 total (+15) Bugs : 897 open (-17) / 5094 closed (+34) / 5991 total (+17) RFE : 191 open ( +3) / 170 closed ( +0) / 361 total ( +3) New / Reopened Patches ______________________ fileinput openfile patch, bz2fileinput (2005-06-22) http://python.org/sf/1225466 opened by Stephan Boettcher Proposal to implement comment rows in csv module (2005-06-22) http://python.org/sf/1225769 opened by Iain Haslam Patch for (Doc) bug #1217513 (2005-06-25) CLOSED http://python.org/sf/1227442 opened by Peter van Kampen Patch for (Doc) bug #1225705 (2005-06-25) CLOSED http://python.org/sf/1227444 opened by Peter van Kampen Patch for (Doc) bug #1175022 (2005-06-25) CLOSED http://python.org/sf/1227489 opened by Peter van Kampen Patch for (Doc) bug #1186072 (2005-06-25) CLOSED http://python.org/sf/1227495 opened by Peter van Kampen Patch for (Doc) bug #1166582 (2005-06-25) CLOSED http://python.org/sf/1227513 opened by Peter van Kampen Patch for (Doc) bug #1212195 (2005-06-26) http://python.org/sf/1227545 opened by Peter van Kampen Patch for (Doc) bug #1219273 (2005-06-26) http://python.org/sf/1227568 opened by Peter van Kampen Patch for (Doc) bug #1228904 (2005-06-29) http://python.org/sf/1229935 opened by Peter van Kampen solaris 10 should not define _XOPEN_SOURCE_EXTENDED (2005-06-27) http://python.org/sf/1227966 opened by Bill Clarke code.py use sys.excepthook to display exceptions (2005-06-27) http://python.org/sf/1228112 opened by Miki Tebeka optionally allow mutable builtin types (2005-06-28) http://python.org/sf/1229239 opened by Greg Couch optionally allow mutable builtin types (2005-06-28) CLOSED http://python.org/sf/1229280 opened by Greg Couch Zipfile fix create_system information (2005-06-29) http://python.org/sf/1229511 opened by Hendrik Muhs Patches Closed ______________ Building on Mac OS X 10.1 (2004-01-02) http://python.org/sf/869555 closed by mwh httplib mentions getreply instead of getresponse (2005-05-16) http://python.org/sf/1203094 closed by birkenfeld note that os.chown can have -1 as an argument (2005-06-01) http://python.org/sf/1213031 closed by birkenfeld Patch for (Doc) bug #1217513 (2005-06-25) http://python.org/sf/1227442 closed by birkenfeld Patch for (Doc) bug #1225705 (2005-06-25) http://python.org/sf/1227444 closed by birkenfeld Patch for (Doc) bug #1175022 (2005-06-25) http://python.org/sf/1227489 closed by birkenfeld Patch for (Doc) bug #1186072 (2005-06-25) http://python.org/sf/1227495 closed by birkenfeld Patch for (Doc) bug #1166582 (2005-06-25) http://python.org/sf/1227513 closed by birkenfeld cgitb: make more usable for 'binary-only' sw (new patch) (2005-02-19) http://python.org/sf/1144549 closed by birkenfeld optionally allow mutable builtin types (2005-06-28) http://python.org/sf/1229280 closed by gregcouch New / Reopened Bugs ___________________ crash in gcmodule.c on python reinitialization (2005-06-22) http://python.org/sf/1225584 opened by Alexander Miseler os.environ documentation should mention unsetenv (2005-06-22) CLOSED http://python.org/sf/1225705 opened by Brian Wellington SimpleXMLRPCServer example is broken (2004-10-06) http://python.org/sf/1041501 reopened by kjohnson Can't take sequence slice past 32K (2005-06-23) CLOSED http://python.org/sf/1226404 reopened by tim_one Can't take sequence slice past 32K (2005-06-23) CLOSED http://python.org/sf/1226404 opened by Gene Cash cPickle and pickle dump bug (inf float) (2005-06-24) CLOSED http://python.org/sf/1226955 opened by Andrea Bolzonella segfault in os module (2005-06-24) http://python.org/sf/1226969 opened by jacobo_es Queue class does not inherit object (2005-06-24) CLOSED http://python.org/sf/1227166 opened by Vincent C?t?-Roy CGIXMLRPCRequestHandler example uses nonexistant "div()" (2005-06-24) CLOSED http://python.org/sf/1227181 opened by Danny Yoo Two requests to one file are not done in parallel (2005-06-25) http://python.org/sf/1227480 opened by Markus Franz subprocess: inheritance of std descriptors inconsistent (2005-06-26) http://python.org/sf/1227748 opened by Andr? Malo shelve/bsddb crash on db close (2005-06-26) http://python.org/sf/1227955 opened by Scott cPickle and pickle dump bug (inf float) (2005-06-27) CLOSED http://python.org/sf/1228015 opened by Andrea Bolzonella usage of type "char*" instead of "const char*" (2005-06-27) http://python.org/sf/1228053 opened by Mattias Ekholm update to 7.15 zlib & 7.18.1 ZipFile Objects docs (2005-06-28) CLOSED http://python.org/sf/1228830 opened by Brian vdB weakref example broken (2005-06-28) http://python.org/sf/1228904 opened by paolo veronelli error whit dict working whith class (2005-06-28) CLOSED http://python.org/sf/1229264 opened by ST2015 No struct.pack exception for some out of range integers (2005-06-29) http://python.org/sf/1229380 opened by Adal Chiriliuc missing Py_DECREF in PyObject_CallMethod (2005-06-28) http://python.org/sf/1229429 opened by Gary httplib error checking. (2005-06-29) http://python.org/sf/1229646 opened by Chris Johns Tracing C function calls and keyword arguments (2005-06-29) http://python.org/sf/1229680 opened by Frank Cieslok Bus error in extension with gcc 3.3 (2005-06-29) http://python.org/sf/1229788 opened by Gary Robinson Bugs Closed ___________ Line endings problem with Python 2.4.1 cause imports to fail (2005-06-21) http://python.org/sf/1225059 closed by doerwalter os.environ documentation should mention unsetenv (2005-06-22) http://python.org/sf/1225705 closed by birkenfeld int/long unification and hex() (2005-06-20) http://python.org/sf/1224347 closed by rhettinger rsplit introduces spurious CR (2005-06-21) http://python.org/sf/1224672 closed by birkenfeld subprocess.Popen fails with closed stdout (2005-04-10) http://python.org/sf/1180160 closed by astrand Can't take sequence slice past 32K (2005-06-23) http://python.org/sf/1226404 closed by mwh Can't take sequence slice past 32K (2005-06-23) http://python.org/sf/1226404 closed by birkenfeld cPickle and pickle dump bug (inf float) (2005-06-24) http://python.org/sf/1226955 closed by mwh Queue class does not inherit object (2005-06-24) http://python.org/sf/1227166 closed by rhettinger CGIXMLRPCRequestHandler example uses nonexistant "div()" (2005-06-24) http://python.org/sf/1227181 closed by dyoo Info from man python not in docs (2005-06-08) http://python.org/sf/1217152 closed by birkenfeld Omission in docs for smtplib.SMTP.sendmail() (2005-06-09) http://python.org/sf/1217513 closed by birkenfeld httplib docs mentioning HTTPConnection.getreply (2005-05-15) http://python.org/sf/1202475 closed by birkenfeld os.waitpid docs don't specify return value for WNOHANG (2005-04-26) http://python.org/sf/1190563 closed by birkenfeld cgi.CGIHTTPRequestHandler remembers QUERY_STRING (2003-09-07) http://python.org/sf/801992 closed by birkenfeld property example code error (2005-04-01) http://python.org/sf/1175022 closed by birkenfeld tempfile.mktemp() omits pid from name (2003-12-10) http://python.org/sf/857566 closed by birkenfeld tempnam doc doesn't include link to tmpfile (2005-04-19) http://python.org/sf/1186072 closed by birkenfeld IterableUserDict not in docs (2005-03-19) http://python.org/sf/1166582 closed by birkenfeld Python keeps file references after calling close methode (2005-04-10) http://python.org/sf/1180237 closed by birkenfeld thisid not intialized in pindent.py script (2004-11-25) http://python.org/sf/1072853 closed by birkenfeld raw_input() displays wrong unicode prompt (2005-01-10) http://python.org/sf/1099364 closed by birkenfeld Cookie.py produces invalid code (2005-01-25) http://python.org/sf/1108948 closed by birkenfeld Cross-site scripting on BaseHTTPServer (2005-01-11) http://python.org/sf/1100201 closed by birkenfeld urllib2.py assumes 206 is an error (2005-04-07) http://python.org/sf/1178145 closed by birkenfeld poorly named variable in urllib2.py (2005-04-03) http://python.org/sf/1175848 closed by birkenfeld self.length shield exception in httplib (2005-03-03) http://python.org/sf/1155638 closed by birkenfeld BaseCookie does not call value_decode (2005-03-25) http://python.org/sf/1170279 closed by birkenfeld doctest.script_from_examples() result sometimes un-exec-able (2005-03-29) http://python.org/sf/1172785 closed by birkenfeld Can't read some http URLs using neither urllib, nor urllib2 (2004-11-01) http://python.org/sf/1058059 closed by birkenfeld CGIHTTPServer: directories/scripts with spaces in their name (2004-12-19) http://python.org/sf/1088039 closed by birkenfeld CGI QUERY_STRING (2004-05-02) http://python.org/sf/946247 closed by birkenfeld attempt to access sys.argv when it doesn't exist (2003-11-10) http://python.org/sf/839151 closed by birkenfeld cPickle and pickle dump bug (inf float) (2005-06-27) http://python.org/sf/1228015 closed by mwh update to 7.15 zlib & 7.18.1 ZipFile Objects docs (2005-06-28) http://python.org/sf/1228830 closed by rhettinger error whit dict working whith class (2005-06-28) http://python.org/sf/1229264 closed by birkenfeld New / Reopened RFE __________________ Add Jason Orendorff's path module to stdlib (2005-06-23) http://python.org/sf/1226256 opened by Michael Hoffman From jcigar at ben.vub.ac.be Tue Jun 28 10:37:50 2005 From: jcigar at ben.vub.ac.be (Julien Cigar) Date: Tue, 28 Jun 2005 16:37:50 +0200 Subject: mod_python and Internal Server Error ... Message-ID: Hello, I'm using mod_python 3.1.3 with Apache 2.0.54 on a Debian box with the publisher handler and the Clearsilver template engine, and from time to time apache returns an 500 error code (Internal Server Error). Apache errog.log file looks like : [Tue Jun 28 14:42:12 2005] [error] [client 164.x.x.x] PythonHandler mod_python.publisher: Traceback (most recent call last): [Tue Jun 28 14:42:12 2005] [error] [client 164.x.x.x] PythonHandler mod_python.publisher: File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line 299, in HandlerDispatch\n result = object(req) [Tue Jun 28 14:42:12 2005] [error] [client 164.x.x.x] PythonHandler mod_python.publisher: File "/usr/lib/python2.3/site-packages/mod_python/publisher.py", line 98, in handler\n path=[path]) [Tue Jun 28 14:42:12 2005] [error] [client 164.x.x.x] PythonHandler mod_python.publisher: File "/usr/lib/python2.3/site-packages/mod_python/apache.py", line 454, in import_module\n f, p, d = imp.find_module(parts[i], path) [Tue Jun 28 14:42:12 2005] [error] [client 164.x.x.x] PythonHandler mod_python.publisher: ImportError: No module named taxal ... What is strange is that when I reload the page, it's displayed fine, but from time to time I get 500 error code ... which is quite annoying ... As I'm using the publisher handler, my index.py looks like : import sys import os.path import neo_cgi import neo_util import neo_cs from mod_python import util, apache from psycopg import QuotedString config = apache.import_module('config', autoreload = 0, log = 0) utils = apache.import_module('utils', autoreload = 0, log = 0) specimen = apache.import_module('specimen', autoreload = 0, log = 0) taxon = apache.import_module('taxon', autoreload = 0, log = 0) fulltextsearch = apache.import_module('fulltextsearch', autoreload = 0, log = 0) template_directory = config.getTemplateDirectory() template_main = config.getTemplateMain() template_menu = config.getTemplateMenu() def index(req): return home(req) def home(req): return _render(req, 'home') def links(req): return _render(req, 'links') def contact(req): return _render(req, 'contact') def taxal(req): sort = req.form.getfirst('sort') order = req.form.getfirst('order') tl = taxon.taxon() tl.getTaxaList(sort, order) hdf = tl.getHDF() return _render(req, 'taxalist', hdf) (...) So for the above example if I GET http://b.abc.be/birds/taxal it should run the "def taxal(req)" function ... I don't understand why I get a "mod_python.publisher: ImportError: No module named taxal" error message in the apache logfile. We have several virtualhosts : a.abc.be, b.abc.be, c.abc.be, ... (fictive addresses). Our www directory is organized like this : /var/www/vhosts/a.abc.be/ /var/www/vhosts/b.abc.be/ /var/www/vhosts/b.abc.be/enbi/ /var/www/vhosts/b.abc.be/enbi/projects/birds/ /var/www/vhosts/b.abc.be/enbi/projects/butterfly/ /var/www/vhosts/b.abc.be/enbi/projects/rubiaceae/ /var/www/vhosts/c.abc.be/blah/ I've tried with "PythonInterpPerDirectory on" in my .htaccess, but without success ... In advance thanks for your support From ivanlan at pauahtun.org Sun Jun 5 13:27:09 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Sun, 05 Jun 2005 11:27:09 -0600 Subject: maybe a bug in python: NOW Pythonic Gotchas References: Message-ID: <42A335ED.8DC2883B@pauahtun.org> Hi All-- This little gotcha ought to be number one on "The Official List of Pythonic Gotchas," which should be required reading for everyone. What? There isn't one? Why not? Send me your tired, your poor, your huddled gotchas yearning to breathe free. I'll whup 'em into shape and make a doc page. The gods of documentation (as opposed to the gods _in_ documentation) can transfer it to the Official Documentation Homeland, or not, as they see fit. Metta, Ivan Tiago St?rmer Daitx wrote: > > Just as everyone said, use ('a',) instead of ('a'). As Steve said > there are lots of documentation about it. Check the Library Reference > at http://www.python.org/doc/current/lib/typesseq.html#l2h-155 or to > make things more clear you could read the tuples section in the > tutorial at > http://docs.python.org/tut/node7.html#SECTION007300000000000000000 > > my 2 cents > > Regards, > Tiago S Daitx > > On 6/5/05, flyaflya wrote: > > >>> a = {1: ("a")} > >>> a[1] > 'a' > why not ('a')? when > >>> a = {1: ((("a")))} > >>> a[1] > 'a' > the result is 'a' too,not ((("a"))).but when use["a"] or > ("a","b"),the > tuple is longer than 1, it's no problem. > > -- > [http://www.flyaflya.com/] > -- > http://mail.python.org/mailman/listinfo/python-list > > --------------------------------------------------------------- > -- > http://mail.python.org/mailman/listinfo/python-list -- ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From steve at REMOVETHIScyber.com.au Sat Jun 11 20:35:42 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 12 Jun 2005 10:35:42 +1000 Subject: case/switch statement? References: Message-ID: On Sat, 11 Jun 2005 16:15:42 +0000, Joe Stevenson wrote: > Hi all, > > I skimmed through the docs for Python, and I did not find anything like > a case or switch statement. I assume there is one and that I just > missed it. Can someone please point me to the appropriate document, or > post an example? I don't relish the idea especially long if-else > statements. I don't relish the idea of especially long case statements. I've never understood why something like: if x = 5: do_this elif x = 6: do_that else: do_something_else is supposed to be "bad", but case of: x = 5: do_this x = 6: do_that otherwise: do_something_else is supposed to be "good". (Choose whatever syntax you prefer for case statements, the principle remains.) Arguably, a case statement *might* allow the compiler to optimize the code, maybe, sometimes. But in general, no such optimization is possible, so a case statement is merely equivalent to a series of if...elif... statements. There is no case statement in Python. If you don't care about readability, one alternative is to use a dictionary: case = {5: do_this, 6: do_that} case.get(x, do_something_else)() -- Steven. From Xavier.Decoret at imag.fr Wed Jun 8 08:21:54 2005 From: Xavier.Decoret at imag.fr (=?ISO-8859-1?Q?Xavier_D=E9coret?=) Date: Wed, 08 Jun 2005 14:21:54 +0200 Subject: Knowing the signature of a function Message-ID: Hello, I have the following code: def foo(x,y): pass How can I query the function object foo to know the number of parameters it expects. I can find it is a function using callable(f), I can find some information (listed by dir(foo)) such as the name of the function,etc.. but nowhere I can find the number of arguments. I would like to know wether the function expects one or zero arguments. From peter at somewhere.com Tue Jun 21 09:25:46 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 21 Jun 2005 15:25:46 +0200 Subject: A tool for Python - request for some advice In-Reply-To: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> Message-ID: TPJ schrieb: > First I have to admit that my English isn't good enough. I'm still > studying and sometimes I just can't express what I want to express. No excuses, please! Keep in mind that your English is much better than the Polish of most of us. And just in case you were fishing for compliments: Your English IS good enough. ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From chad.hughes at pnl.gov Thu Jun 9 16:59:41 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Thu, 09 Jun 2005 13:59:41 -0700 Subject: smtpd module Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6155@pnlmse27.pnl.gov> Does anyone know of any documentation on how to use the smtpd module, either the SMTPServer or the DebuggingServer? I cannot find any usage cases or examples anywhere. I can find examples of using the smtplib module but not the smtpd module. Thanks, Chad -------------- next part -------------- An HTML attachment was scrubbed... URL: From rkern at ucsd.edu Sat Jun 4 06:19:55 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 04 Jun 2005 03:19:55 -0700 Subject: If - Or statements In-Reply-To: <42A175E0.8040800@mailshack.com> References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> <42A175E0.8040800@mailshack.com> Message-ID: <42A1804B.6090504@ucsd.edu> Ognjen Bezanov wrote: > Robert Kern wrote: > > >>Ognjen Bezanov wrote: >> >> >>>Another newbie-ish question. >>> >>>I want to create an if statement which will check if a particular >>>variable matches one of the statements, and willl execute the statement >>>if the variable matches any of the statements. >>> >>>I have tried the following (the pass is just used for testing) >>> >>> >>>if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] == >>>"aac" or ext[1] != "wma": >>> print "we have a valid extension: " + ext[1] #here would go the >>>code for decoding the above >>> pass >> >> >>It works fine for me. Could you post the smallest complete program >>(one that defines ext) that displays the behavior and its entire output? >> >>As an aside, is 'ext[1] != "wma"' correct or should it be ==? As >>written, you could collapse the whole thing to 'if ext[1] != "wma":' >>but I presume it is a typo. > > filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom > drive > for thefile in filelist[:]: #for each file in the filelist > if thefile.find(".") != -1: #if the file has an extenstion > at all > ext = thefile.split('.') #get the file extension > ext[1] = ext[1].lower() #convert to lowercase > print ext[1] #debugging, to see the variable before > passed to if statement > > if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" > or ext[1] == "aac" or ext[1] == "wma": > print "we have a valid extension: " + ext[1] #here > would go the code for decoding the above > pass It works just fine for me. Note that you could (and probably should) write the if statement as if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'): but I really don't think that's your problem. Could you also post the output, too? In [1]:filelist = os.listdir('./') In [2]:for thefile in filelist: ...: if '.' in thefile: ...: ext = thefile.split('.') ...: ext[1] = ext[1].lower() ...: print ext[1] ...: if (ext[1] == 'mp3' or ext[1] == 'mp4' or ext[1] == 'ogg' or ext[1] == 'aac' or ext[1] == 'wma'): ...: print 'We have a valid extension: %s' % ext[1] ...: ogg We have a valid extension: ogg [etc.] -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mwm at mired.org Thu Jun 23 15:46:07 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 23 Jun 2005 15:46:07 -0400 Subject: suggestions invited References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119545314.216605.305340@z14g2000cwz.googlegroups.com> Message-ID: <86hdfozwjk.fsf@guru.mired.org> gry at ll.mit.edu writes: > Aditi wrote: >> hi all...i m a software engg. student completed my 2nd yr...i have been >> asked to make a project during these summer vacations...and hereby i >> would like to invite some ideas bout the design and implementation of >> an APPLICATION MONITORING SYSTEM....i have to start from scrach so >> please tell me how to go bout it rite from the beggining this is the >> first time i m making a project of this complexity... >> i have to make a system used by the IT department of a company which >> contains 31 applications and their details which are being used in a >> company ...the details are... >> Application sub application catagory platform language version IT >> owner functional owner remarks source code documentation last updated >> dates >> i want to design a system such that it lets the it employee enter the >> name of the application and gives him all the details about it...please >> suggest an appropriate design and the language which you think would be >> best to use...as i have enouf time with me and i can learn a new >> language as well...i currently know c and c++...your advise is welcomed >> Aditi > Then you might look at xml as a means for storing the data. Xml is > structured, readable without special software(very helpful for > debugging), and easy to use for simple data. Try the xml module from > http://pyxml.sourceforge.net/topics/download.html > [look at the demos for simple usage] Don't be intimidated by complex > formal definitions of XML, what you need is not hard to use. I'd humbly disagree with the suggestion of using XML for storage. It has a fairly large overhead, is usually unreadable unless special care is taken when you generate it, and not as easy to use as some of the alternatvives. It definitely has it's place - for instance, if you are interchanging data with other developers who have settled on an XML format for doing so. If you can use a DTD and leverage existing XML tools - editors, validators, etc. - to advantage, then it's a good choice. But for simple data storage, I think it's overkill. Pickle is much easier to use, and you can explore stored data with an interactive Python interpreter. The application as described doesn't really call for an application. You have apparently static descriptions of 31 different applications. What's wrong with 31 XHTML pages (so you get to use XML after all :-) and a front page that lists the applications alphabetically? That also avoids the problem of what you do when the employee misspells the name of the application. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From greg_miller at nexpress.com Mon Jun 27 09:00:13 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 27 Jun 2005 06:00:13 -0700 Subject: COM problem .py versus .exe References: Message-ID: <1119877213.793716.212120@f14g2000cwb.googlegroups.com> Thanks for the tweaked code, it worked on my desktop. The acid test will be when I put it on one of the "virgin" PC's ( no python installed, just running the py2exe executable ) that run the machine. I won't be getting one of those until later in the week, but I'm hoping that since it cleared the problem here, it will also clear the problem on that machine, ( the error message was slightly different ), so once again thanks again. Greg From http Sun Jun 19 02:34:42 2005 From: http (Paul Rubin) Date: 18 Jun 2005 23:34:42 -0700 Subject: pickle alternative References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> <1119161205.327572.136150@g44g2000cwa.googlegroups.com> Message-ID: <7xd5qi3ldp.fsf@ruckus.brouhaha.com> simonwittber at gmail.com writes: > > I think you should implement it as a C extension and/or write a PEP. > > This has been an unfilled need in Python for a while (SF RFE 467384). > > I've submitted a proto PEP to python-dev. It coming up against many of > the same objections to the RFE. See also bug# 471893 where jhylton suggests a PEP. Something really ought to be done about this. From 11949invalid at mynewsgate.net Sat Jun 18 10:41:32 2005 From: 11949invalid at mynewsgate.net (Dariosky) Date: Sat, 18 Jun 2005 14:41:32 GMT Subject: Localization in OSX Message-ID: <2005061814413211949@mynewsgate.net> Hi, I have a problem with L10N of an app, I'm unable to retrieve default language in mac while this works for both Linux and Windows: LOCALE=locale.getdefaultlocale() Where can I find default system settings with mac? -- dariosky http://dariosky.altervista.org/ From fredrik at pythonware.com Mon Jun 20 13:36:23 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Jun 2005 19:36:23 +0200 Subject: utf8 and ftplib References: <1119267462.32655.236736750@webmail.messagingengine.com> <1119275301.13168.236745297@webmail.messagingengine.com> Message-ID: Richard Lewis wrote: > On Mon, 20 Jun 2005 14:27:17 +0200, "Fredrik Lundh" > said: > > > > well, you're messing it up all by yourself. getting rid of all the > > codecs and > > unicode2charrefs nonsense will fix this: > > > Thanks for being so patient and understanding. > > OK, I've taken it all out. The only thinking about encoding I had to do > in the actual code I'm working on was to use: > file.write(document.toxml(encoding="utf-8")) > > instead of just > file.write(document.toxml()) > > because otherwise I got errors on copyright symbol characters. sounds like a bug in minidom... > My code now works without generating any errors but Konqueror's KHTML > and Embedded Advanced Text Viewer and IE5 on the Mac still show > capital-A-with-a-tilde in all the files that have been > generated/altered. Whereas my text editor and Mozilla show them > correctly. > > The "unicode2charrefs() nonsense" was an attempt to make it output with > character references rather than literal characters for all characters > with codes greater than 128. Is there a way of doing this? character references refer to code points in the Unicode code space, so you just convert the bytes you get after converting to UTF-8. however, if you're only using characters from the ISO Latin 1 set (which is a strict subset of Unicode), you could en- code to "iso-8859-1" and run unicode2charrefs on the result. but someone should really fix minidom so it does the right thing. (fwiw, if you use my ElementTree kit, you can simply do tree.write(encoding="us-ascii") and the toolkit will then use charrefs for any character that's not plain ascii. you can get ElementTree from here: http://effbot.org/zone/element-index.htm ) From ramen at lackingtalent.com Tue Jun 28 14:10:36 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 28 Jun 2005 11:10:36 -0700 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> References: <11bs1bc5jotvg9c@news.supernews.com> <42BF6995.1050606@boonthavorn.com> <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> Message-ID: <6rgwe.89652$yV4.72889@okepread03> Stephen Kellett wrote: > In message , Simon > Brunning writes > >> Eclipse's refactorings are a great boon, I find. Refectoring is never >> *fully* automatic, of course, but the ability to, for example, select >> a chunk of code and have it extracted into a separate method with all >> needed arguments and the return value worked out for you is very >> helpful. All you have to do is give the new method a name. And this >> sort of thing can certainly improve readability. > > This is not an attach on you Simon, but if people are relying on that > type of thing for increases in software productivity they are hiring the > wrong people. I think that the right people to hire are the ones that can make the best use of whatever tools are available so they can get their job done well and in a reasonable amount of time. I'm not a big fan of Java programming, but sometimes I have to do it, and when I do, I must say that the refactoring capabilities of IDEs like IntelliJ IDEA are very helpful. Being able to rename classes, variables and functions across multiple files, extract methods with automatic naming and typing of parameters and throws-clauses, and move methods from one class to another makes it so much easier to reorganize and improve large amounts of code. And due to Java's verbosity, there usually is a lot of code to manage even for simple changes. In Python, there's still a need to do these sorts of things. Typically, we use "search and replace" and "cut and paste" instead. You could make a similar statement about those tools - if you rely on "cut and paste" to increase your productivity... gah, it makes me cringe just writing that! Nonetheless, I would hate to program without "cut and paste" as a tool. In any language. The need for automatic refactoring tools in Python is smaller; Python gives you the opportunity to program at a higher level of abstraction, so there is less code to deal with. In addition, since Python doesn't have checked exceptions or require type annotation, design changes tend to "splatter" less across your code base. Still, Python's dynamic nature limits the sort of automatic changes you can make reliably, and we ought to recognize that. By using Python, we are making a tradeoff: in communicating less information, we are forcing IDEs to do more guesswork. Java requires less guesswork for the IDE, but requires significantly more communication on behalf of the programmer. I don't think it's a cut-and-dry win for either language. Dave From gralex1974 at ua.fm Wed Jun 8 11:39:03 2005 From: gralex1974 at ua.fm (gralex) Date: Wed, 8 Jun 2005 18:39:03 +0300 Subject: Popup ListBox in wxPython Message-ID: Hi, all !!! How i can made Popup ListBox ? Example in Demo is not working... Have anybody examples ? From flyaflya at gmail.com Sun Jun 5 12:33:48 2005 From: flyaflya at gmail.com (flyaflya) Date: Mon, 06 Jun 2005 00:33:48 +0800 Subject: maybe a bug in python Message-ID: >>> a = {1: ("a")} >>> a[1] 'a' why not ('a')? when >>> a = {1: ((("a")))} >>> a[1] 'a' the result is 'a' too,not ((("a"))).but when use["a"] or ("a","b"),the tuple is longer than 1, it's no problem. -- [http://www.flyaflya.com/] From chinook.nr at tds.net Wed Jun 29 01:01:18 2005 From: chinook.nr at tds.net (Chinook) Date: Wed, 29 Jun 2005 01:01:18 -0400 Subject: OO refactoring trial ?? References: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> <0001HW.BEE6FEEE000C427BF0407550@news.gmane.org> <1120018704.586468.68720@f14g2000cwb.googlegroups.com> Message-ID: <0001HW.BEE7A35E001C617AF0407550@news.gmane.org> On Wed, 29 Jun 2005 00:18:24 -0400, Paul McGuire wrote (in article <1120018704.586468.68720 at f14g2000cwb.googlegroups.com>): > Lee - > > Bruce Eckel's observation: > > "the above scaffolding of Obstacle, Player and GameElementFactory > (which was translated from the Java version of this example) is > unnecessary - it's only required for languages that have static > type checking. As long as the concrete Python classes follow the form > of the required classes, we don't need any base classes..." > > is consistent with my "duck-typing" comment that all that is needed of > A,B,etc. is that they provide the necessary testit and doit methods in > the proper form. He also goes on to say that, even if the base classes > were empty, they still provide a useful handle for all of the derived > classes, to indicate they are all common subtypes of "Shape" or > whatever. > > I think you were referring to the "Poking Python with a Stick" entry in > the second link. The inheritance of all taunts from Taunt allowed the > author to put some overriding common-to-all-taunts behavior into the > superclass, even if it was just a "sorry, not implemented" exception > into the base Taunt class's tauntTheKnights() method. The idea was to > provide a runtime exception if the needed method had not been > overridden in the subclass. But it also provides a place to put any > other common-to-all-taunts behavior, perhaps a common constructor, or > other common helper methods. I think this is a good use of > inheritance, when the base class actually adds some value to the > architecture, even if it is just Bruce Eckel's empty placeholder base > class. Note also that this author was doing patterns experimentation > in both Python and Java. I envision him writing the factory's > getInstance() method in Java, and having to declare its return value > type. In this case Java really drives you to having all possible > return values derive from a common base class, so that you can define > the method as: > > Taunt getInstance(string tauntTypeTag) { ... > > which is a bit easier to deal with than just declaring that getInstance > returns an object, and then having to cast it - in fact, if there were > no common base type, it would be problematic to know just what to cast > it to. > > But Python does not require this sort of type rigidity. In your code, > the only requirement is that each class A,B,etc. have testit and doit > methods - they have to walk and talk like ducks, they don't need to > *be* ducks. My point in an earlier post was, I think many current > design patterns were born out of the C++ and Java worlds, and may be > overly restrictive for a comparable implementation in Python. > > One step you might take in the MultiEvaluator constructor is to > validate the provided classes on input, so that you don't have to > exhaustively test all A thru Z classes before finding out that you > misspelled Z's doit method as "dooit". This goes one better than the > abstract subclass's "you forgot to override me" method implementation. > > In sum, both of the links you sent used examples that had inheritance > hierarchies where the base class provided some contribution and > commonality among the derived classes. TauntArthur "is-a" Taunt, > TauntGalahad "is-a" Taunt. It really does look like the Factory > pattern should return objects that share a common base class. But in > Python, that common base class can also be just "something that walks > like a duck." > > -- Paul > > Thank you for the clarification Paul. I missed the influence of C++ and Java origins because my past experience was more in the assembler realm with a little C and Pascal, and now I'm trying to get up to speed with Python, ObjC and the OO world. You've helped me look at what I'm reading in a better light. Thanks again, Lee C From hancock at anansispaceworks.com Wed Jun 15 14:30:40 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 15 Jun 2005 13:30:40 -0500 Subject: "also" to balance "else" ? In-Reply-To: References: Message-ID: <200506151330.40236.hancock@anansispaceworks.com> On Wednesday 15 June 2005 03:57 am, Fredrik Lundh wrote: > where your "abnormal behaviour" is, of course, the expected > behaviour. if you insist on looking at things the wrong way, > things will look reversed. Unfortunately, the converse is true, too: no matter how twisted an idea is, you can make it seem logical with the right point of view. ;-) I think the OP is correct in saying that for-else is non-intuitive. Your use case is the only one in which "else" makes sense, IMHO, and that's only because it reflects the overall meaning of the algorithm, not because it actually reflects what's going on in the syntax. If "finally" is wrong (and I see your point there), then maybe "normally" is the right thing to call it? After all, it's the opposite of the "exception" case, which is probably the "normal" case. The fact that, in a search algorithm, the exception case is the normal result, and the syntactically normal case is the exception just confuses the issue. The question is, how difficult is it for the person reading the code to understand what was written? Now of course, a person skilled in language X will understand the syntax even if all the keywords are unintelligible gibberish, and from that PoV, it will surely make sense. But I get the impression that Python is *trying* to use words with the right inuitive meaning in the interest of helping newbies. I *personally* can get my head around "for-else" and use it if I really need it, but I agree that it could be spelled better. OTOH, I see no reason for an opposite construct, since, as you and others have pointed out, that can be handled by the if in the loop or by an exception handler. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From cfbolz at gmx.de Fri Jun 10 05:18:20 2005 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Fri, 10 Jun 2005 11:18:20 +0200 Subject: ANN: Python for Maemo released! In-Reply-To: References: Message-ID: <42A95ADC.6080606@gmx.de> [snip Python port announcement] > No reptiles were harmed in the making of these crafts. +1 QOTW From kay.schluehr at gmx.net Sat Jun 18 03:53:34 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 18 Jun 2005 00:53:34 -0700 Subject: Back to the future - python to C++ advice wanted In-Reply-To: References: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> Message-ID: <1119081214.366589.119720@g43g2000cwa.googlegroups.com> D H wrote: > That's why so many people have switched to Java or C# (or Python and > other langugages of course). You might talk to them about using Python, > since Python and C/C++ fit together very nicely (with tools like BOOST, > SWIG, Pyrex,...). But me personally I like to avoid C++ altogether when > possible, and use Java or C# instead, both of which also can be combined > with python or python-like languages such as jython, groovy, or boo. But accessing Java packages from jython does not reduce effecively the underlying pain. Personally I favour for programming in C++ over Java, because I feel at least the mind of an evil genius ( C++ template programming is Turing complete, operator overloading enables objects having a builtin groove ) where Java is plain mediocrity. In spirit it is a kind of Anti-Python. I recommend studying C++ idioms carefully. http://www1.bell-labs.com/user/cope/Patterns/C++Idioms/EuroPLoP98.html If Georges starts on greenfields he may have a look at Qt and it's object library which is not only concerned with widgets. http://doc.trolltech.com/3.3/ BOOST is more high brow and I guess that it compiles slow because it uses templates extensively. Template metaprogramming as a compile time language was a funny discovery. Here is some prove of it's capabilities: http://osl.iu.edu/~tveldhui/papers/2003/turing.pdf Regards, Kay From phillip.watts at anvilcom.com Mon Jun 20 13:21:28 2005 From: phillip.watts at anvilcom.com (phil) Date: Mon, 20 Jun 2005 12:21:28 -0500 Subject: Embedded Systems Python? References: <11bdnto1au02i63@corp.supernews.com> Message-ID: <42B6FB18.1050304@anvilcom.com> I developed for my former employee a thin client whose primary purpose was AS400 connectivity. This required a fairly complex interactive gui configuration which I wrote in Python. This system could also be configed by a remote manager. Wrote that also in python using UDP sockets. The hardware was 64Mb memory and 64Mb compact flash. OS wa 2.4.20 linux from Debian I did a lot of cleanup removing unneeded modules but other than that, standard Python 2.3.4 worked great. Dennis Clark wrote: > Hi all, > > I've looked through the threads about embedded Python that are a year > and a half old, and I thought that I'd ask this question now to see if > anything has changed. > > Has anyone, or is anyone working with Python in an embedded Linux > environment? Mine is NO where near as constrained as a cell phone since > I've got plenty of memory to work with, I'm just running a Linux 2.4 kernel > on an ARM9 platform. > > Are there success stories for Python on embedded Linux systems today? > The embedded Java JVM's seem to all be propriatary and have quite high > license fees (don't mention Kaffe, it seems pretty fragile to me.) > > I'm a bit of a newb when it comes to Python, is there anyone with experience > compiling it on Linux platforms that can offer me pointers to try this out > myself? > > thanks, > DLC > From greg at cosc.canterbury.ac.nz Wed Jun 8 23:40:55 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 15:40:55 +1200 Subject: Annoying behaviour of the != operator In-Reply-To: <1118256283.485202.19780@o13g2000cwo.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: <3gps2lFdnvh0U1@individual.net> Jordan Rastrick wrote: > Where are the 'number of situations' where __ne__ cannot be derived > from __eq__? Is it just the floating point one? I must admit, I've > missed any others. The floating point one is just an example, it's not meant to be the entire justification. Some others: * Numeric arrays, where comparisons return an array of booleans resulting from applying the comparison to each element. * Computer algebra systems and such like, which return a parse tree as a result of evaluating an expression. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From venkatasubramanian at gmail.com Wed Jun 8 12:47:04 2005 From: venkatasubramanian at gmail.com (venkata subramanian) Date: Wed, 8 Jun 2005 22:17:04 +0530 Subject: Subject: Re: Binary numbers In-Reply-To: References: Message-ID: > Em Quarta 08 Junho 2005 09:38, Guyon Mor?e escreveu: > > Don't know if this is what you mean, but: > > > > Binary to decimal: > > >>> bin_num = '100001011' > > >>> int(bin_num, 2) > > > > 267 > > Dont know this way of using it. Thanks for the teachings :) > > See ya ! >>> def binary(i): ... ls=[] ... while 1: ... ls.append(i&1) ... i>>=1 ... if i==0: ... break ... return "".join(str(x) for x in reversed(ls)) ... >>> binary(20) '10100' From hancock at anansispaceworks.com Wed Jun 22 01:54:50 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 22 Jun 2005 00:54:50 -0500 Subject: references/addrresses in imperative languages In-Reply-To: References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> <1119335440.863575.24360@g14g2000cwa.googlegroups.com> Message-ID: <200506220054.51077.hancock@anansispaceworks.com> On Tuesday 21 June 2005 06:27 pm, Andrea Griffini wrote: > On 20 Jun 2005 23:30:40 -0700, "Xah Lee" wrote: > >Thanks for explaning this tricky underneath stuff. > > Surely this is different from C/C++/Java, but it's > IMO all but tricky or underneath. Made me feel like an idiot, though. ;-) Seriously though, thanks for the correction. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From gsakkis at rutgers.edu Sun Jun 19 13:13:41 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 19 Jun 2005 10:13:41 -0700 Subject: Why is there no instancemethod builtin? References: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> <1119197146.922190.38000@g44g2000cwa.googlegroups.com> Message-ID: <1119201221.143713.8890@z14g2000cwz.googlegroups.com> "Michele Simionato" wrote: > In this case I have used hasattr(obj, "__iter__") instead of > isinstance(obj, list) > (strings are iterable but do not have __iter__ method). I think hasattr > is much better > since it works for tuples and custom iterables too. The fact that strings don't have __iter__ is an implementation detail (I can't think of any reason other than historic and perhaps backwards compatibility for this; iterables should IMHO by definition be exactly the objects with __iter__). Also, what if tuples and any other iterables except for lists are considered atomic ? An implementation of s-expressions would use a single data structure for the nesting (e.g. a builtin list or a custom linked list) and objects of all other types should be considered atoms, even if they happen to be iterable. George From devlai at gmail.com Sat Jun 25 16:15:16 2005 From: devlai at gmail.com (Devan L) Date: 25 Jun 2005 13:15:16 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <1119730516.936848.195640@f14g2000cwb.googlegroups.com> But by using the builtin reduce, you need to specify a function, which probably slows it down more than any speed-up from the loop in C. From guy.lateur at b-b.be Tue Jun 14 06:01:43 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 14 Jun 2005 10:01:43 GMT Subject: Where is Word? References: Message-ID: Unfortunately, I need to open/edit a (temporary) text file with Word, and those are opened by default with UltraEdit (or Notepad or..). Thanks for the tip, though. Anything else? Do I need to read the registry? g While this doesn't answer the question you're asking, I believe it does solve the problem you're facing. Relying on the fact that the Microsoft Office products will have associated themselves as the default (Open) action with files of the appropriate extensions, you can use os.startfile: import os os.startfile ("c:/temp/blah.doc") HTH TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From luismgz at gmail.com Mon Jun 13 08:20:44 2005 From: luismgz at gmail.com (Neuruss) Date: 13 Jun 2005 05:20:44 -0700 Subject: Learning more about "The Python Way" References: <0001HW.BED2700A0044BB0FF0284550@news.gmane.org> Message-ID: > As someone else mentioned, get a copy of the 2nd edition of the Python > Cookbook. It's full of gold. Or you can read the recipes online here: http://aspn.activestate.com/ASPN/Python/Cookbook/ From brian at rkspeed-rugby.dk Thu Jun 30 04:03:36 2005 From: brian at rkspeed-rugby.dk (Brian Elmegaard) Date: 30 Jun 2005 10:03:36 +0200 Subject: Favorite non-python language trick? References: Message-ID: Joseph Garvin writes: > I'm curious -- what is everyone's favorite trick from a non-python > language? Metapost solution of linear equations: x1+9=x2-8=2; > And -- why isn't it in Python? I'd like to know too. -- Brian (remove the sport for mail) http://www.et.web.mek.dtu.dk/Staff/be/be.html From jrastrick at student.usyd.edu.au Fri Jun 17 17:13:42 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 17 Jun 2005 14:13:42 -0700 Subject: Please help me understand this code.... In-Reply-To: <1119035981.924689.139880@f14g2000cwb.googlegroups.com> References: <1119035981.924689.139880@f14g2000cwb.googlegroups.com> Message-ID: <1119042822.700790.22620@g49g2000cwa.googlegroups.com> The : is used in Python for slice notation, which is explained pretty thoroughly in the Python tutorial, specifically at: http://www.python.org/doc/2.4/tut/node5.html From gsakkis at rutgers.edu Sat Jun 25 15:17:20 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Jun 2005 12:17:20 -0700 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: <1119727040.440447.123000@f14g2000cwb.googlegroups.com> "Konstantin Veretennicov" wrote: > On 6/25/05, Steven D'Aprano wrote: > > On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote: > > > > > On 6/25/05, Mandus wrote: > > >> It is really a consensus on this; that > > >> removing map, filter, reduce is a good thing? It will render a whole lot > > >> of my software unusable :( > > > > > > I think you'll be able to use "from __past__ import map, filter, > > > reduce" or something like that :) They don't have to be built-in. > > > > More likely they will be moved to something like itertools than "__past__". > > > > Or just define them yourself: > > > > def map(f, seq): > > return [f(x) for x in seq] > > > > def filter(p, seq): > > return [x for x in seq if p(x)] > > > > def reduce(f, seq, zero): > > r = zero > > for x in seq: r = f(r, x) > > return r > > FWIW, these don't exactly reproduce behaviour of current built-ins. > Filter, for instance, doesn't always return lists and map accepts more > than one seq... Just my $.02. > > - kv If they go to itertools, they can simply be: def map(f, *iterables): return list(imap(f,*iterables)) def filter(f, seq): return list(ifilter(f,seq)) George From jabel at plus.net Tue Jun 28 11:45:09 2005 From: jabel at plus.net (John Abel) Date: Tue, 28 Jun 2005 16:45:09 +0100 Subject: building python 2.4.1 In-Reply-To: References: Message-ID: <42C17085.8020206@plus.net> Andreas Heiss wrote: >John Abel wrote: > > > >>Andreas Heiss wrote: >> >> >> >>>Hi ! >>>I am trying to build python 2.4.1 from source on a Linux system. >>>Everything seems fine, but tkinter seems not to work. >>>The file _tkinter.pyd is missing. >>>How can tell configure to build all necessary components ? >>> >>>Thanks >>>Andreas >>> >>> >>> >>> >>It looks to like Tcl/Tk is not installed on your system. You will need >>to have them installed for Tkinter to build. >> >> > >Actually, tk and tcl 8.4 are installed. >However, there are no tcl.h and tk.h header files. I haven't ssen those >files since Tcl/Tk8.0 > > > > Hmmm, where they a pre/package install? I'm sure I had to build Tcl/Tk from source on my Debian install. J From garabik-news-2005-05 at kassiopeia.juls.savba.sk Thu Jun 9 10:17:46 2005 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Thu, 9 Jun 2005 14:17:46 +0000 (UTC) Subject: tail -f sys.stdin References: Message-ID: Antal Rutz wrote: > Hi! > > Maybe a very newbie question but: > I'd like to write a prog which reads one line at a time on its sys.stdin > and immediately processes it. > If there are'nt any new lines wait (block on input). > what about: for line in sys.stdin: process(line) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From xah at xahlee.org Sat Jun 18 03:49:26 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jun 2005 00:49:26 -0700 Subject: Python documentation problem Message-ID: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Python documentation, http://python.org/doc/2.4.1/lib/typesfunctions.html ----------------- 2.3.10.3 Functions Function objects are created by function definitions. The only operation on a function object is to call it: func(argument-list). There are really two flavors of function objects: built-in functions and user-defined functions. Both support the same operation (to call the function), but the implementation is different, hence the different object types. See the Python Reference Manual for more information. ----------------- Fuck the python doc wasted my time. Fuck python coders. Each time i tried to use python doc and got frustrated because it being grossly incompetent, i'll post a message like this, no more frequent than once a week. This will go on as long the python community does nothing to fix it or that i remain coding in python. For reference, see http://xahlee.org/perl-python/re-write_notes.html Xah xah at xahlee.org ? http://xahlee.org/ From benyang22 at yahoo.com Fri Jun 17 16:40:25 2005 From: benyang22 at yahoo.com (benyang22 at yahoo.com) Date: 17 Jun 2005 13:40:25 -0700 Subject: whos -- a function listing objects References: <1118948272.051392.323240@g14g2000cwa.googlegroups.com> Message-ID: <1119040825.743795.228870@z14g2000cwz.googlegroups.com> That is nice. I didn't know iPython can do whos. Will try it. iPython seems to infinitely configurable. Hope it will not suck too much of my time into it. From tzot at sil-tec.gr Mon Jun 6 09:24:21 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 06 Jun 2005 16:24:21 +0300 Subject: Destructive Windows Script References: <7xd5r0uno2.fsf@ruckus.brouhaha.com> Message-ID: <6jj8a1dujr5fl1ev0beoilnop3imbqeoeu@4ax.com> On 05 Jun 2005 21:14:37 -0700, rumours say that Paul Rubin might have written: >The only way to be 100% sure the data is gone from a drive, is >basically to melt the drive. However, if your data is that sensitive, >you shouldn't ever write it to a hard drive in the clear anyway. A little healthy insanity never hurt anyone in the security field :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From info at dishnews.com Tue Jun 14 20:57:08 2005 From: info at dishnews.com (info at dishnews.com) Date: Tue, 14 Jun 2005 17:57:08 -0700 Subject: Autoroll Fix Members Update Now Message-ID: Attn Satellite tv tester,http://www.nagra2ready.com It is very urgent that you change your keys on your cards and fta units. The current keys are as follows. Dishnetwork Key 1 is active, changed TUE JUNE 14th, 2005 KEY0: 34 12 B8 ED 07 A7 CB C8 KEY1:0C 97 B4 37 5E 3F BE 81 It is also very important to note that if you are using an fta that you flash it with the latest version 4.2 of our nagra2ready bin. We provide support for all brands of fta units. Login now to update your receiver with the ecm-proof bin that we have compiled. http://www.nagra2ready.com If you are using rom cards or other card based fixes, it is important that you are protected from the ecm slated in the stream within the next 24 hours. This rare type of damaging ecm will bypass all current blockers and will cause permanant dammage to your hardware. Update your equipment now, do not wait for the worst to happen. We only have 72 slots open for new members, so if you fail to join in time, we will lock down the members section to new members. We do this to preserve the integrity of our ultra-private scripts and keep the code secure on a limited platform. http://www.nagra2ready.com From hancock at anansispaceworks.com Mon Jun 27 00:22:00 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 26 Jun 2005 23:22:00 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: <200506260559.18488.hancock@anansispaceworks.com> Message-ID: <200506262322.00250.hancock@anansispaceworks.com> On Sunday 26 June 2005 06:11 am, Robert Kern wrote: > Terry Hancock wrote: > > On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote: > >>However, then you must forbid a=b=1 for assigning to two variables > >>at the same time. > > You need to differentiate > a = b = 1 > from > a = b == 1 Okay, I see what you mean. I can't ever recall having needed the second form, though. Of course, you could still do assignment like this: a, b = (1,)*2 But I guess that's not exactly elegant. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From jeffelkins at earthlink.net Sat Jun 4 11:23:47 2005 From: jeffelkins at earthlink.net (Jeff Elkins) Date: Sat, 4 Jun 2005 11:23:47 -0400 Subject: Walking through a mysql db In-Reply-To: <200506040924.25574.jeffelkins@earthlink.net> References: <200506040924.25574.jeffelkins@earthlink.net> Message-ID: <200506041123.48102.jeffelkins@earthlink.net> On Saturday 04 June 2005 09:24 am, Jeff Elkins wrote: > I'm writing a small wxpython app to display and update a dataset. So far, I > get the first record for display: > > try: > cursor = conn.cursor () > cursor.execute ("SELECT * FROM dataset") > item = cursor.fetchone () > > Now, how do I step through the dataset one row at a time? My form has > 'next' and 'back' buttons, and I'd like them to step forward or back, > fetching the appropriate row in the table. I've tried setting > cursor.rownumber by incrementing it prior to the fetchone() w/o effect. Thanks for the responses! The buttons are working now. Within this same app, I've got a search function working, but I need the rownumber when a record is fetched. sql = """select * from address where %s = %%s""" % arg1.lower() cursor.execute(sql, (arg2,)) item = cursor.fetchone () index = cursor.rownumber At this point, the record is on the screen, but cursor.rownumber doesn't reflect the actual rownumber...it always returns 1. How can I obtain the actual row number for the displayed record? Jeff From nephish at xit.net Thu Jun 9 00:37:56 2005 From: nephish at xit.net (nephish at xit.net) Date: 8 Jun 2005 21:37:56 -0700 Subject: need some cgi help please In-Reply-To: <3gpn0vFdp53cU1@individual.net> References: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> <3gpn0vFdp53cU1@individual.net> Message-ID: <1118291876.124306.150170@g43g2000cwa.googlegroups.com> i fixed it. the program was going nuts because there were spaces in the name of the file. go figgure. anyway, i changed the way i format the timestamp that becomes the file name and removed the spaces. working all better now. thanks From rkern at ucsd.edu Wed Jun 8 17:19:18 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 08 Jun 2005 14:19:18 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: <1118264973.349272.173370@z14g2000cwz.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> <1118264973.349272.173370@z14g2000cwz.googlegroups.com> Message-ID: Jordan Rastrick wrote: > Mahesh raised the argument some posts back that Python should not 'just > guess' what you want. But the problem is, it *already does* - it > guesses you want object identity comparison if you haven't written > __ne__. But if __ne__ is not provided, than the negation of > > a==b > > is *surely* a better guess for a != b than the negation of > > a is b The problem arises that, in the presence of rich comparisons, (a == b) is not always a boolean value, while (a is b) is always a boolean value. I *would* prefer that (a != b) raise an error when __ne__ isn't provided, but such is life until 3.0. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dimitri.pater at gmail.com Thu Jun 30 19:48:25 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Fri, 1 Jul 2005 01:48:25 +0200 Subject: I have a question. In-Reply-To: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> References: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Message-ID: Hi, here is an example of using the random function I am working at right now (it randomizes (is that a word?) every word in a list): import string import random from itertools import ifilter, ifilterfalse def reinterpolate(word): #thanks to Raymond Hettinger (taken from the Python list) word = list(word) random.shuffle(word) isvowel = dict.fromkeys('aeiouy').has_key vowels = ifilterfalse(isvowel, word) consonants = ifilter(isvowel, word) result = [] for v, c in map(None, vowels, consonants): if c: result.append(c) if v: result.append(v) # added stuff to keep the dot at the end of every sentence in the list (dp) result = ''.join(result) if result.find('.') != -1: result = result.replace('.', '') + '.' return ''.join(result) else: return ''.join(result) def gib(mystring): print 'This is the original: ', mystring mylist = string.split(mystring) newlist = [] for i in range(len(mylist)): i = reinterpolate(mylist[i]) newlist.append(i) newstring = ' '.join(newlist) cap = ". ".join([s.capitalize() for s in newstring.split(". ")]) print 'This is the scramble: ', cap # example usage if __name__ == "__main__": mystring = "harry is a strange guy. so is his sister, but at least she is not a guy. i am." gib(mystring) Maybe it helps. regards, Dimitri On 6/30/05, Nathan Pinno wrote: > > > > Hi all, > > Does Python have a random function? If so, can you show me an example > using it? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > > > > -- > > > ---------------------------------------------------------------- > Posted via UsenetRevolution.com - > Revolutionary Usenet > ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** > http://www.UsenetRevolution.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From gandalf at geochemsource.com Wed Jun 1 16:11:18 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 01 Jun 2005 22:11:18 +0200 Subject: idiom for constructor? In-Reply-To: References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <429E1666.3010203@geochemsource.com> >You could try: > >class Foo: > def __init__(self,a,b,c,d): > args = locals() > for arg in args.keys(): > if name!='self': > self.__dict__[arg] = args[arg] > > Should be: if arg!='self' Also it is not perfect. For example: class Foo: def __init__(self,a,b,c,d): temp = 12 self.foo2 = temp + 4 args = locals() for arg in args.keys(): if arg!='self': self.__dict__[arg] = args[arg] a = Foo(1,2,3,4) print dir(a) Results in: ['__doc__', '__init__', '__module__', 'a', 'b', 'c', 'd', 'foo2', 'temp'] E.g. not only the parameters but all local variables are used... From fredrik at pythonware.com Mon Jun 13 05:34:01 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Jun 2005 11:34:01 +0200 Subject: re - multiple results References: Message-ID: Pingveno wrote: > I'm working on the Python Challenge (make sure to try it: > http://www.pythonchallenge.com). One of the puzzles requires the use of > regular expressions, but with multiple matches in the text. I tried to > use re.findall(), but I only go one result instead of a list of results. > >>>> print re.findall(r"myexpression",text) > ['AZBaCTR'] > > There should, of course, be several matches. "myexpression" won't return "AZBaCTR" for any kind of input, so I'm not sure what "of course" really refers to... > What function should I use? Or is it not a function issue? my guess is that you're using "*" or "+" in a situation where you don't really need them. cf. >>> re.findall("\w", "abcdef") ['a', 'b', 'c', 'd', 'e', 'f'] >>> re.findall("\w+", "abcdef") ['abcdef'] From d at e.f Fri Jun 17 16:02:58 2005 From: d at e.f (D H) Date: Fri, 17 Jun 2005 15:02:58 -0500 Subject: case/switch statement? In-Reply-To: References: <4oadnU1eGeQx3zPfRVn-uQ@comcast.com> Message-ID: Peter Hansen wrote: > D H wrote: > >> Peter Hansen wrote: >> >>> With a case statement, on the other hand, you *know* that it must be >>> just simple conditionals (a series of x == some_constant tests), so >>> you don't need to look at all the cases, just the one that interests >>> you. >> >> >> Since you and Steve Holden agree that a case statement is useful, why >> don't you propose it for python, or add it to the wiki page for Python >> 3000. > > > Two simple reasons. > > 1. You forgot my previous comment that "in current Python the equivalent > approach is, of course, a dictionary of some kind, though it's arguable > whether this is as clean in many cases as a case statement would be." I didn't forget that. I never read it, and I don't see the relevance to my suggestion. Now that I've read it, I would hardly call using a dictionary as a switch statement, the "equivalent". The fact that people use a dictionary as a conditional is a python wart. > 2. Just because something is "useful" doesn't mean it should be added to > Python. The bar should be set much higher, and should include at least > "and significantly better than any existing alternative way of doing the > same thing." Now go read point 1 again... ;-) Now go read my message again. I made a suggestion to you. I didn't say that a switch statement should be added myself. I would never propose that because the chances of it being added are microscopic. > My point was not to suggest that I want a case statement in Python, nor Neither was the MY point, which you seem to have inferred. > even that a case statement is a good thing to have in a language (though > it might be... it's not my place to say). My point was simply to point > out that performance is not the only reason to use a case statement. I don't think you could have misread my simple suggestion to you any more completely than you did. From richardlewis at fastmail.co.uk Fri Jun 17 05:40:42 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Fri, 17 Jun 2005 10:40:42 +0100 Subject: utf8 and ftplib In-Reply-To: <11b3ftrea0k2e29@news.supernews.com> References: <11b3ftrea0k2e29@news.supernews.com> Message-ID: <1119001242.31248.236579821@webmail.messagingengine.com> On Thu, 16 Jun 2005 12:06:50 -0600, "John Roth" said: > "Richard Lewis" wrote in message > news:mailman.540.1118935910.10512.python-list at python.org... > > Hi there, > > > > I'm having a problem with unicode files and ftplib (using Python 2.3.5). > > > > I've got this code: > > > > xml_source = codecs.open("foo.xml", 'w+b', "utf8") > > #xml_source = file("foo.xml", 'w+b') > > > > ftp.retrbinary("RETR foo.xml", xml_source.write) > > #ftp.retrlines("RETR foo.xml", xml_source.write) > > > > It looks like there are at least two problems here. The major one > is that you seem to have a misconception about utf-8 encoding. > Who doesn't? ;-) > > Whatever program you are using to read it has to then decode > it from utf-8 into unicode. Failure to do this is what is causing > the extra characters on output. > > > Amusingly, this would have worked: > > xml_source = codecs.EncodedFile("foo.xml", "utf-8", "utf-8") > > It is, of course, an expensive way of doing nothing, but > it at least has the virtue of being good documentation. > OK, I've fiddled around a bit more but I still haven't managed to get it to work. I get the fact that its not the FTP operation thats causing the problem so it must be either the xml.minidom.parse() function (and whatever sort of file I give that) or the way that I write my results to output files after I've done my DOM processing. I'll post some more detailed code: def open_file(file_name): ftp = ftplib.FTP(self.host) ftp.login(self.login, self.passwd) content_file = file(file_name, 'w+b') ftp.retrbinary("RETR " + self.path, content_file.write) ftp.quit() content_file.close() ## Case 1: #self.document = parse(file_name) ## Case 2: #self.document = parse(codecs.open(file_name, 'r+b', "utf-8")) # Case 3: content_file = codecs.open(file_name, 'r', "utf-8") self.document = parse(codecs.EncodedFile(content_file, "utf-8", "utf-8")) content_file.close() In Case1 I get the incorrectly encoded characters. In Case 2 I get the exception: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe6' in position 5208: ordinal not in range(128)" when it calls the xml.minidom.parse() function. In Case 3 I get the exception: "UnicodeEncodeError: 'ascii' codec can't encode character u'\xe6' in position 5208: ordinal not in range(128)" when it calls the xml.minidom.parse() function. The character at position 5208 is an 'a' (assuming Emacs' goto-char function has the same idea about file positions as xml.minidom.parse()?). When I first tried these two new cases it came up with an unencodable character at another position. By replacing the large dash at this position with an ordinary minus sign I stopped it from raising the exception at that point in the file. I checked the character xe6 and (assuming I know what I'm doing) its a small ae ligature. Anyway, later on in the program I create a *very* large unicode string after doing some playing with the DOM tree. I then write this to a file using: html_file = codecs.open(file_name, "w+b", "utf8") html_file.write(very_large_unicode_string) The problem could be here? Cheers, Richard From http Sat Jun 18 03:38:43 2005 From: http (Paul Rubin) Date: 18 Jun 2005 00:38:43 -0700 Subject: functions with unlimeted variable arguments... References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> Message-ID: <7xr7f0yv0c.fsf@ruckus.brouhaha.com> "Xah Lee" writes: > but are there other solutions? > > Xah Geez man, haven't you been around long enough to read the manual? def f(*a): return a From eurleif at ecritters.biz Mon Jun 20 07:40:22 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 20 Jun 2005 11:40:22 GMT Subject: subprocess.call(*args **kwargs) on Linux In-Reply-To: <1119265420.031534.29250@g49g2000cwa.googlegroups.com> References: <1119265420.031534.29250@g49g2000cwa.googlegroups.com> Message-ID: McBooCzech wrote: > This is easy. Subprocess function "call" looks: > returncode = subprocess.call(["/root/dex/dex","/dev/ttyS0", > "blabla.txt"]) > and it runs smoothly. > > The problem starts when I am trying to add 1>/dev/null 2>/dev/null > parameters to suppres output sendings. from subprocess import call, STDOUT call(["command", "arg", "arg"], stdout=open("/dev/null", "w"), stderr=STDOUT) From narshe at gmail.com Thu Jun 9 14:26:41 2005 From: narshe at gmail.com (Josh Close) Date: Thu, 9 Jun 2005 13:26:41 -0500 Subject: re behaving strangely Message-ID: <4a0cafe2050609112629a05c98@mail.gmail.com> This is not returning a match re.compile( r'b' ).search( 'back', re.I ) Anyone know why this is? -- -Josh From rkern at ucsd.edu Sun Jun 19 18:25:23 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 19 Jun 2005 15:25:23 -0700 Subject: functions with unlimeted variable arguments... In-Reply-To: <1119218400.989803.230410@g47g2000cwa.googlegroups.com> References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> <7xr7f0yv0c.fsf@ruckus.brouhaha.com> <1119218400.989803.230410@g47g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > oops... it is in the tutorial... sorry. > > though, where would one find it in the python reference? > i.e. the function def with variable/default parameters. > > This is not a rhetorical question, but where would one start to look > for it in the python ref? Oddly enough, http://docs.python.org/ref/function.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kbk at shore.net Thu Jun 9 23:03:56 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 9 Jun 2005 23:03:56 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200506100303.j5A33uIC002882@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 339 open ( -5) / 2857 closed (+12) / 3196 total ( +7) Bugs : 908 open ( -8) / 5036 closed (+22) / 5944 total (+14) RFE : 189 open ( -2) / 168 closed ( +5) / 357 total ( +3) New / Reopened Patches ______________________ Trivial typo in unicodedata._getcode (2005-06-02) http://python.org/sf/1213831 opened by Darek Suchojad Support non-file source/dest in marshal (2005-06-04) http://python.org/sf/1214879 opened by Skip Montanaro file.encoding support for file.write and file.writelines (2005-06-04) http://python.org/sf/1214889 opened by Reinhold Birkenfeld two fileinput enhancements (fileno, openhook) (2005-06-05) http://python.org/sf/1215184 opened by Reinhold Birkenfeld Suggested Additional Material for urllib2 docs (2005-06-08) http://python.org/sf/1216942 opened by Mike Foord proposed patch for tls wrapped ssl support added to smtplib (2005-06-08) http://python.org/sf/1217246 opened by Pete G Patches Closed ______________ [ast] fix for 1183468: return/yield in class (2005-04-16) http://python.org/sf/1184418 closed by nascheme [AST] throw SyntaxError in "from x import y," (2005-05-04) http://python.org/sf/1194895 closed by nascheme fix for trivial flatten bug in astgen (2005-01-04) http://python.org/sf/1095541 closed by nascheme Add st_flags support to (l)stat function (2005-06-01) http://python.org/sf/1212117 closed by perky buffer overflow in _cursesmodule.c (2005-05-11) http://python.org/sf/1200134 closed by akuchling Typo in Curses-Function doc (2005-04-20) http://python.org/sf/1186781 closed by akuchling binary formats for marshalling floats (2005-04-11) http://python.org/sf/1180995 closed by mwh test_locale fix on modern linux (2005-05-07) http://python.org/sf/1197218 closed by anthonybaxter An URL for UnicodeData File Format 3.2 has changed. (2005-05-25) http://python.org/sf/1207985 closed by perky Patch for [ 1170331 ] Error in base64.b32decode (2005-03-27) http://python.org/sf/1171487 closed by akuchling #1074261 gzip dies on gz files with many appended headers (2004-11-27) http://python.org/sf/1074381 closed by akuchling asynchat does not accept 'long' terminator (2004-08-03) http://python.org/sf/1002763 closed by akuchling New / Reopened Bugs ___________________ Queue.qsize() better info about unreliability (2005-06-02) http://python.org/sf/1213475 opened by Nikos Kouremenos os.path.realpath() cannot handle symlinks (2005-06-02) CLOSED http://python.org/sf/1213894 opened by Ilya Sandler test_marshal.py discards marshal.load val (2005-06-04) CLOSED http://python.org/sf/1214662 opened by Skip Montanaro subprocess auto-reaps children (2005-06-04) http://python.org/sf/1214859 opened by Mattias Engdeg?rd bsddb dbobj.DB.associate doesn't accept dbobj.DB param (2005-06-04) http://python.org/sf/1215023 opened by Gregory P. Smith int('x',radix) puzzle (2005-06-05) CLOSED http://python.org/sf/1215146 opened by elgordo String and list methods deeply hidden (2005-06-06) http://python.org/sf/1215887 opened by Reinhold Birkenfeld Large tarfiles cause overflow (2005-06-06) http://python.org/sf/1215928 opened by Tom Emerson Replace MSVC memory allocator with ptmalloc2 (2005-06-07) http://python.org/sf/1216562 opened by Niall Douglas csv module sometimes raises _csv.Error (2005-06-08) CLOSED http://python.org/sf/1216831 opened by Mary Gardiner LINKCC->CXX, -ltermcap->-lncurses (2005-06-08) http://python.org/sf/1216923 opened by Niki W. Waibel Info from man python not in docs (2005-06-08) http://python.org/sf/1217152 opened by Kent Johnson Omission in docs for smtplib.SMTP.sendmail() (2005-06-09) http://python.org/sf/1217513 opened by Kent Johnson make frameworkinstall fails for non-default location (2005-06-09) http://python.org/sf/1217591 opened by Mitch Chapman pydoc includes unnecessary files for a package. (2005-06-09) http://python.org/sf/1217881 opened by Igor Belyi Bugs Closed ___________ check for return/yield outside function is wrong (2005-04-15) http://python.org/sf/1183468 closed by nascheme Incorrect result for regular expression - "|(hello)|(world)" (2005-06-01) http://python.org/sf/1212411 closed by tim_one doc bug in Lock.acquire (2005-05-27) http://python.org/sf/1209880 closed by akuchling (?(id)yes|no) only works when referencing the first group (2005-04-06) http://python.org/sf/1177831 closed by akuchling Notation (2005-04-30) http://python.org/sf/1193001 closed by akuchling os.path.realpath() cannot handle symlinks (2005-06-03) http://python.org/sf/1213894 closed by birkenfeld bz2.BZ2File doesn't handle modes correctly (2005-05-03) http://python.org/sf/1194181 closed by birkenfeld test_marshal.py discards marshal.load val (2005-06-04) http://python.org/sf/1214662 closed by montanaro WeakValueDictionary.__init__ is backwards (2005-05-06) http://python.org/sf/1196315 closed by birkenfeld Typo in "Differences from mimelib" (2005-05-27) http://python.org/sf/1210001 closed by birkenfeld IDLE 1.0.5 (Python 2.3.5) crashes under Windows (2005-05-21) http://python.org/sf/1206232 closed by kbk example broken in section 1.12 of Extending & Embedding (2005-04-16) http://python.org/sf/1184380 closed by birkenfeld try to open /dev/null as directory (2005-04-15) http://python.org/sf/1183585 closed by birkenfeld int('x',radix) puzzle (2005-06-05) http://python.org/sf/1215146 closed by birkenfeld compileall doesn't notice syntax errors (2001-03-30) http://python.org/sf/412436 closed by birkenfeld doc speaks of extensions option while it's *called* ext_modu (2005-03-25) http://python.org/sf/1170422 closed by akuchling dumbdbm hoses index on load failure (2005-03-29) http://python.org/sf/1172763 closed by akuchling csv module sometimes raises _csv.Error (2005-06-07) http://python.org/sf/1216831 closed by montanaro error in documentation for splitting empty string (2005-03-28) http://python.org/sf/1171994 closed by akuchling Error in base64.b32decode (2005-03-24) http://python.org/sf/1170331 closed by akuchling gzip dies on gz files with many appended headers (2004-11-27) http://python.org/sf/1074261 closed by akuchling datetime changes missing from "Porting from 2.3 to 2.4" (2004-12-04) http://python.org/sf/1079134 closed by akuchling New / Reopened RFE __________________ Move test_method_checksum from test_unicodedata. (2005-06-02) CLOSED http://python.org/sf/1213703 opened by Darek Suchojad module warnings lacks a remove filter function (2005-06-04) http://python.org/sf/1214675 opened by Torsten Bronger Add Error Code Dictionary to urllib2 (2005-06-08) http://python.org/sf/1216944 opened by Mike Foord RFE Closed __________ Move test_method_checksum from test_unicodedata. (2005-06-02) http://python.org/sf/1213703 closed by rhettinger Prepending Text (2005-05-31) http://python.org/sf/1212169 closed by rhettinger The array module and the buffer interface (2005-04-26) http://python.org/sf/1190033 closed by rhettinger expm1 and log1p (2005-03-14) http://python.org/sf/1163139 closed by rhettinger Support file path concat with "/" (2002-11-27) http://python.org/sf/644940 closed by birkenfeld From dalke at dalkescientific.com Wed Jun 1 23:03:50 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 02 Jun 2005 03:03:50 GMT Subject: any macro-like construct/technique/trick? References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: Mac wrote: > Is there a way to mimic the behaviour of C/C++'s preprocessor for > macros? There are no standard or commonly accepted ways of doing that. You could do as Jordan Rastrick suggested and write your own sort of preprocessor, or use an existing one. With the new import hooks you can probably make the conversion happen automatically, though I hesitate suggestions that as you might actually do that. It's typically a bad idea because you're in essence creating a new language that is similar to but not Python, making it harder for people to understand what's going on. > The problem: a lot of code like this: > > def foo(): > # .... do some stuff > if debug: > emit_dbg_obj(DbgObjFoo(a,b,c)) ... > * the two-lines of debug conditional tend to really break up the flow > of the surrounding code If flow is your only concern you can have a do-nothing function and at the top have if debug: emit = emit_dbg_obj else: def emit(*args, **kwargs): pass then write all your code as emit(DbgObjFoo(a,b,c)) > * using > def debug_emit(obj): > if debug: > emit_dbg_obj(obj) > is a poor solution, because it *always* instantiates DbgObj*, even when > not needed; I want to avoid such unnecessary waste That would work as well of course. How bad is the waste? Is it really a problem? Is all your code of the form emit(Class(constructor, args)) ? If so, your debug_emit could be made to look like debug_emit(klass, *args, **kwargs): if debug: emit_dbg_obj(klass(*args, **kwargs)) and used debug_emit(DbgObjFoo, a, b, c) debug_emit(DbgObjBar, d, e) though I would use the do-nothing function version I sketched earlier because, *ahem*, it avoids an unnecessary waste of the extra "if debug:" check. :) Andrew dalke at dalkescientific.com From dieter at handshake.de Thu Jun 9 15:08:08 2005 From: dieter at handshake.de (Dieter Maurer) Date: 09 Jun 2005 21:08:08 +0200 Subject: some profiler questions References: <1118201931.104592.50900@z14g2000cwz.googlegroups.com> Message-ID: "Mac" writes on 7 Jun 2005 20:38:51 -0700: > .... > 1) I'd still like to run my whole app (i.e., using main()), but I'd > like to limit the profiling to only the select few subroutines. That > is, say I have a set of such fns in mind, call it "key_fns", and I > would like to only profile # of invocations of these fns from key_fns, > as well as by whom they were called, and how much cumulative time was > spent in them. Is such lower-level control possible? The main reason > I want this is that I do not want to profile most of the low-level > routines, like vector addition, at least not yet... I don't want to > slow down code execution any more than is necessary, as the statistics > gathering should occur during "normal" runs (i.e., during normal > operation). Please read the "How it works section". You find an example how the profiler can be customized in my "ZopeProfiler" product (the "HLProfiler.py"). It makes profiling slower (as it derives high level profiles in addition to the low level ones) but might nevertheless help you as an example. > 2) I've only just discovered that pstats has "print_callers()"! That's > very useful info I wasn't aware was available! What I'm really looking > for now is profiler output in the style generated by "gprof", the GNU > profiler, as I have found that format terribly useful (a section for > each fn, with the fn's callers and callees interwoven in each section). > Does anyone know of a utility which would format the Python profiling > info in that format, or something very similar? I haven't actually > seen any output from print_callers (can't find any samples on Net, and > my app is currently half-busted, mid-refactor), so if that's what it > precisely does, ignore this question. Thus, you look at the internal representation of "pstats" and format it in the way you like... > 3) assuming the above-mentioned fine control of (1) is not yet > possible, I will muddle on with my own "selective" profiling code; the > question I have then is, what is the cleanest way to override a class > instance's method at runtime? class_.f = some_wrapper(class_.f) > What my profiler is doing is overriding > the key fns/methods of an instance with a stat-gatherer-instrumented > version, which ends up calling the original method. I tried reading > profile.py and pstats.py for ideas, but they are a little too > complicated for me, for now; I doubt that's how they do their profiling > anyways. You should read the "How it works section". You will find out that your doubt is justified... Dieter From rkern at ucsd.edu Thu Jun 30 19:45:07 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 16:45:07 -0700 Subject: Using Numeric 24.0b2 with Scientific.IO.NetCDF In-Reply-To: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> References: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> Message-ID: bandw wrote: > I am having a problem using Numeric-24.0b2 in conjunction with > the NetCDF module from ScientificPython (version 2.4.9). > This problem does not surface using Numeric-23.8. The problem > arises in using the "min" function on a NetCDF floating array. > In 23.8, the "min" function returns a floating scalar, while in > 24.0b2 it returns an *array* of length "1". Below I list a > simple NetCDF file and a Python script that illustrate the > problem. When I run the script using 23.8, I get the result: > > 1.0 > > whereas using 24.0b2 I get: > > 1.0 > > This creates a backward incompatibility that breaks several of > my codes. Call float(temp) if you really need a Python float. The change was intentional such that A[i] would always be an array regardless of the shape of A. This greatly simplifies certain types of code although the change does have its transition costs for some specific pieces of older code like yours. BTW, you don't want to use the builtin min(). That iterates over the array as if it were a Python list. Use minimum.reduce(). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ahmedshinwari786 at yahoo.com Mon Jun 13 03:41:15 2005 From: ahmedshinwari786 at yahoo.com (Ahmed Shinwari) Date: Mon, 13 Jun 2005 00:41:15 -0700 (PDT) Subject: NIST Ihead Image format Message-ID: <20050613074115.1161.qmail@web54601.mail.yahoo.com> Hello Charles, I am Ahmed, I read your query regarding image reader for NIST's ihead standard. You mentioned that NIST has a sample database of such images for downloading, could please do me a favour, (i) forward me the link of NIST where sample data of ihead image is stored, I can not find it. (ii) if you have obtained the ihead image reader, please forward it to me, Thanking in advance, Ahmed Ali Shinwari. __________________________________ Discover Yahoo! Stay in touch with email, IM, photo sharing and more. Check it out! http://discover.yahoo.com/stayintouch.html From deets at web.de Thu Jun 23 10:53:32 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 23 Jun 2005 16:53:32 +0200 Subject: newbie - modules for jython (under grinder 3) ? In-Reply-To: <42bac1b8$0$2021$ed2e19e4@ptn-nntp-reader04.plus.net> References: <42bac1b8$0$2021$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <3i00ndFho4uoU1@uni-berlin.de> bugbear wrote: > I'm just trying to use Grinder 3 to beat > up my http-app. > > Grinder 3 comes with its own jython.jar. > > Some of the sample scripts: > http://grinder.sourceforge.net/g3/script-gallery.html > use import statements that don't work for me. > > Reading around, these are reference to modules. > > Do I need a "proper" jython instead of the one > that grinder ships with? I guess so - at least there are jython-modules written as *py-files in my jython installation, including the threading.py module. Now - I don't exactly remember how to specify where to find those, but AFAIK there is a system property that you have to set to that path. So - go, fetch jython from jython.org, install it and try to proceed. Diez From qscomputing at gmail.com Thu Jun 2 15:53:58 2005 From: qscomputing at gmail.com (qscomputing at gmail.com) Date: 2 Jun 2005 12:53:58 -0700 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <1117742038.474266.172450@g43g2000cwa.googlegroups.com> > > 1. What is the easiest way to create a for loop in the style I'm used > > to from Delphi > > Use Delphi. Very literal interpretation of my text: I should have said "in a similar style to". :-) > I can think of a number of reasons why somebody might want to hide their > code. I can't really think of any pressing reasons for wanting to hide code other than a habit developed from coding in Windows where, as I'm sure you'll know, doing otherwise is considered a bit odd. Like all habits, it's a hard one to break. :-( From onurb at xiludom.gro Thu Jun 30 06:43:24 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 30 Jun 2005 12:43:24 +0200 Subject: Store multiple dictionaries in a file In-Reply-To: References: Message-ID: <42c3cccd$0$12707$626a14ce@news.free.fr> Philipp H. Mohr wrote: > Hello, > > I would like to store multiple dictionaries in a file, if possible one per > line. Why "one per line" ? > My code currently produces a new dictionary every iteration and > passes it on to another peace of code. May this code rest in piece > In order to be able to re-run some > experiments at a later date I would like to store every dictionary in the > same file. > I looked at pickel, but that seems to require a whole file for each > dictionary. > > It would be great if some one could tell me how to do that. A pretty simple solution could be to store all the dicts in another container (list or dict, depending on how you need to retrieve'em, but from what you explain I'd say a list) and then pickle this container. My 2 cents... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tdaitx at gmail.com Sat Jun 4 21:10:13 2005 From: tdaitx at gmail.com (=?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=) Date: Sat, 4 Jun 2005 22:10:13 -0300 Subject: executing a command In-Reply-To: References: Message-ID: Hello, When you use one of the os.exec*p fnnctions python looks for the specified file in the directories refered by os.environ['PATH']. If and _only_ if your os.enviroment['PATH'] isn't set then it looks in os.defpath - you can check this at http://www.python.org/doc/current/lib/os-path.html#l2h-1557 So, my advice is that you first try printing your os.environ['PATH'] to check wheter it includes the program that you are calling or not (and then you will have to include it). In the case that it isn't set, then check os.defpath. Also, when you use one of the functions os.exec that requires a path variable to be passed (ie. the ones that doesn't have 'p' in their names) the path can be relative or absolute, but it must include the file name (and not only the dir where the file is). And for each one of these os.exec* functions the first argument will always be used as the program "name" (argv[0]), so unless you a reason to do otherwise, pass the same name as the file that you are calling. Regards, Tiago S Daitx On 6/4/05, andrea valle wrote: > Hi to all, > I need to run a program from inside python (substantially, algorithmic > batch processing). > I'm on mac osx 10.3.8 with python 2.3 framework and macpython. > > Trying to use exec*, I checked references, Brueck & Tanner, and then > grab this code from effbot: > > >>> program = "python" > >>> def run(program, *args): > os.execvp(program, (program,) + args) > print "ok" > > >>> run("python", "/Users/apple/Desktop/prova.py") > > Traceback (most recent call last): > File "", line 1, in -toplevel- > run("python", "/Users/apple/Desktop/prova.py") > File "", line 2, in run > os.execvp(program, (program,) + args) > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/os.py", line 336, in execvp > _execvpe(file, args) > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/os.py", line 374, in _execvpe > func(fullname, *argrest) > OSError: [Errno 45] Operation not supported > > This OSError seems to be consistend with all exec family. What does it > mean and how to use exec? > > I also tried with. os.system. It works if I invoke python, but it fails > (in a way I don't know) when I invoke other programs. > > For example: > command = "python /Users/apple/Desktop/test.py" > >>> os.system(command) > 0 > (test.py write a string in a file. It works) > > But with lilypond or with latex I have no output (and in fact it > doesn't give 0 as result): > > >>> command = "lilypond /Users/apple/Desktop/test.ly" > >>> os.system(command) > 32512 > >>> command = "latex /Users/apple/Desktop/test.tex" > >>> os.system(command) > 32512 > > Any help is much appreciated > > Thanks a lot > > -a- > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From EP at zomething.com Tue Jun 21 03:42:21 2005 From: EP at zomething.com (EP) Date: Mon, 20 Jun 2005 23:42:21 -0800 Subject: Python choice of database In-Reply-To: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: <20050620234221.1251363715.EP@zomething.com> Oren suggested: > How about using the filesystem as a database? For the number of records > you describe it may work surprisingly well. A bonus is that the > database is easy to manage manually. I tried this for one application under the Windows OS and it worked fine... until my records (text - maybe 50KB average) unexpectedly blossomed into the 10,000-1,000,000 ranges. If I or someone else (who innocently doesn't know better) opens up one of the directories with ~150,000 files in it, the machine's personality gets a little ugly (it seems buggy but is just very busy; no crashing). Under 10,000 files per directory seems to work just fine, though. For less expansive (and more structured) data, cPickle is a favorite. From michele.simionato at gmail.com Wed Jun 1 08:30:23 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 Jun 2005 05:30:23 -0700 Subject: Function Serialization In-Reply-To: <1117627366.569543.227090@o13g2000cwo.googlegroups.com> References: <1117627366.569543.227090@o13g2000cwo.googlegroups.com> Message-ID: <1117629023.949739.302650@g14g2000cwa.googlegroups.com> The simple way is to use shelve: $ ipython Python 2.4.1c2 (#2, Mar 19 2005, 01:04:19) Type "copyright", "credits" or "license" for more information. IPython 0.6.5 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: import shelve In [2]: sh=shelve.open("x.shelve") In [3]: def f(): pass ...: In [4]: sh["f"]=f In [5]: sh.close() In [6]: sh=shelve.open("x.shelve") In [7]: sh["f"] Out[7]: You may want to experiment a bit. Michele Simionato From erinhouston at gmail.com Wed Jun 8 16:20:51 2005 From: erinhouston at gmail.com (erinhouston at gmail.com) Date: 8 Jun 2005 13:20:51 -0700 Subject: separate IE instances? References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> <1118165668.863841.291290@z14g2000cwz.googlegroups.com> Message-ID: <1118262051.519340.205600@z14g2000cwz.googlegroups.com> Here is quick and dirty example of what jc talked about. import win32api from win32com.client import Dispatch a = win32api.ShellExecute(0,None,"iexplore.exe",None,None,1) internetExplorerClassIdentity='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}' hwnds = Dispatch(internetExplorerClassIdentity) ieObj = hwnds[1] ieObj.Navigate("http://www.google.com/search?hl=en&lr=&q=python") From peter at engcorp.com Thu Jun 2 09:58:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 09:58:34 -0400 Subject: Two questions In-Reply-To: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: qscomputing at gmail.com wrote: > I've developed in several other languages and have recently found > Python and I'm trying to use it in the shape of the PythonCard > application development tool. > > My two questions: > > 1. What is the easiest way to create a for loop in the style I'm used > to from Delphi ie: > for I:=0 to 2 do begin > //code > end; for i in xrange(0, 3): # code Please read the tutorial. I'm fairly sure this and many more things you'll want to know are covered adequately. > 2. Philospohy(sp?) aside, I could potentially want to create a > binary-only distribution of my finished apps. I noticed the > documentation on .pyc files: how do I create these and, aside from > being basically read-only, are they used just like ordinary .py source > files? And can they be easily reverse-engineered? They are compiled versions of the .py files, so definitely not the same. They are created automatically and transparently when you import .py modules, so normally you don't pay any attention to them. They can easily be reverse-engineered, if by that you mean turned back into source code. See "decompyle" for example. Using the "compileall" module you can manually compile .py to .pyc but, again, that's generally not needed. Use of tools like py2exe is generally advised for packaging and distibution if you don't want to distribute source, though few of the existing tools do much more than package up .pyc files inside archives, bundle the runtime library, and add wrapper code to make the execution transparent. Philosophy not entirely aside, you should note that object code in any language can "easily" be reverse-engineered in the same way, with the only difference being the degree of ease involved. If the code is worth enough to someone that they are willing to risk violating your license terms, they *will* be able to recover enough source code (whether it was Python, C, or assembly) to do what they need. The only certain protection is to keep the valuable code on a server and use some kind of web service (or whatever) to control access to its execution. (There have been *many* past discussions of all this in the forum -- it's a very tired topic by now -- so please feel free to peruse the archives via Google Groups before asking lots of the same questions over again. You'll be doing yourself a favour.) -Peter From curi at curi.us Wed Jun 1 13:08:14 2005 From: curi at curi.us (Elliot Temple) Date: Wed, 1 Jun 2005 10:08:14 -0700 Subject: Pressing A Webpage Button Message-ID: How do I make Python press a button on a webpage? I looked at urllib, but I only see how to open a URL with that. I searched google but no luck. For example, google has a button how would i make a script to press that button? Just for fun, is there any way to do the equivalent of typing into a text field like the google search field before hitting the button? (I don't actually need to do this.) If someone could point me in the right direction it'd be appreciated. -- Elliot Temple http://www.curi.us/ --- [This E-mail scanned for viruses by Declude Virus] From austin at maxtronic.com.tw Fri Jun 24 09:16:29 2005 From: austin at maxtronic.com.tw (Austin) Date: Fri, 24 Jun 2005 21:16:29 +0800 Subject: windows service problem Message-ID: class HelloService(win32serviceutil.ServiceFramework): _svc_name_ = "HelloService" _svc_display_name_ = "Hello Service" def __init__(self,args): win32serviceutil.ServiceFramework.__init__(self,args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) self.check = 1 def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) self.check = 0 def SvcDoRun(self): win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) while True: CheckPoint('SvcDoRun') if self.check == 0: break if __name__ == '__main__': win32serviceutil.HandleCommandLine(HelloService) ----------------------------------------------------------------------- I modified the demo code from Python Programming on Win32. CheckPoint is a class to open a file and write some words. But the problem is that no matter how I re-start the service and the CheckPoint() doesn't work. Anything wrong? From rakesh.thakrar at microcom.ltd.uk Thu Jun 9 06:52:30 2005 From: rakesh.thakrar at microcom.ltd.uk (Rakesh Thakrar) Date: Thu, 9 Jun 2005 11:52:30 +0100 Subject: Graduate / Junior Open Source Developer (Python) required Message-ID: <3945FCE4ADA5554081F9AD5469652901016183F2@server-01.wwrg.wwrg.co.uk> Hi, I am looking for a Graduate / Junior Open Source Developer to work as a python developer for one of my clients, please have a look at the job spec below. Please do not hesitate to call me if you are interested. I also have a Junior Tester role, mid level and team leader/manager roles available working in a Python and Agile environment for the same location please email or call me on 01727 752000 for further information. > South East - Sussex > Graduate/Junior Python / Open Source Developer Our client is a cutting edge software development company that has applied novel technological approaches to produce an excitingly different data management system. Due to expansion of the development team our client is currently seeking a Graduate/Junior Python / Open Source Developer that would like to work as Python Software Engineer. Ideally you will be degree qualified or equivalent and show interest with Open Source Technologies as well as having personal or commercial experience with Linux. Salary c?20-30K. Please do not hesitate to call me for further information on 01727 752000 or email me at rakesh.thakrar at microcom.ltd.uk. > Regards > Rakesh > > ___________________________ > Rakesh Thakrar > Senior Consultant > Microcom Limited > Recruitment Division > 2 Adelaide Street > St. Albans > Herts, AL3 5BH > Tel: 01727 752 000 > Mob: 079 7094 3227 > Fax: 01727 752 018 > www.microcom.ltd.uk > ____________________________________ > > > ************************************************************************** > *********************** > The views expressed in this e-mail are not necessarily the views of > Worldwide Recruitment Holdings Ltd, its directors, officers or employees > make no representation or accept any liability for its accuracy or > completeness unless expressly stated to the contrary. > This e-mail, and any attachments are strictly confidential and > intended for the addressee(s) only. > The content may also contain legal, professional or other privileged > information. Unless expressly stated to the contrary, no contracts may be > concluded on behalf of Worldwide Recruitment Holdings Ltd by means of > e-mail communication. You may report the matter by calling us on +44 (0) > 1727 752000. > Please ensure you have adequate virus protection before you open or > detach any documents from this transmission. Worldwide Recruitment > Holdings Ltd does not accept any liability for viruses. > > Worldwide Recruitment Holdings Ltd is registered in England: Company > number: 0391174. > Registered Office: Faulkner House, Victoria Street, St Albans, > Herts, AL1 3SE. > > > ************************************************************************** > *********************** > From gregpinero at gmail.com Thu Jun 23 00:02:55 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 23 Jun 2005 00:02:55 -0400 Subject: os.system(cmd) isn't working Message-ID: <312cfe2b050622210266e3713c@mail.gmail.com> Hi guys, I'm trying to run this statement: os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' "www.blendedtechnologies.com"') The goal is to have firefox open to that website. When I type r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' "www.blendedtechnologies.com"' in the python interpreter I get: '"C:\\Program Files\\Mozilla Firefox\\firefox.exe" "www.blendedtechnologies.com"' And when I copy this into my command prompt (less outermost ' ) firefox opens up to that page like I would expect. However in python nothing happens and I get exit status 1. I'm using Python 2.3 on Windows XP pro service pack 2. I'd greatly appriciate any help. Thanks, Greg From nospam at nospam.nospam Sun Jun 12 06:15:27 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Sun, 12 Jun 2005 03:15:27 -0700 Subject: How to get/set class attributes in Python References: Message-ID: On Sun, 12 Jun 2005 11:54:52 +0200, Kalle Anke wrote: >I'm coming to Python from other programming languages. I like to >hide all attributes of a class and to only provide access to them >via methods. Some of these languages allows me to write something >similar to this > >int age( ) >{ > return theAge >} > >void age( x : int ) >{ > theAge = x >} > >(I usually do more than this in the methods). I would like to do >something similar in Python, and I've come up with two ways to do >it: The first one uses the ability to use a variable number of >arguments ... not very nice. The other is better and uses >__setattr__ and __getattr__ in this way: > >class SuperClass: > def __setattr__( self, attrname, value ): > if attrname == 'somevalue': > self.__dict__['something'] = value > else: > raise AttributeError, attrname > > def __str__( self ): > return str(self.something) > >class Child( SuperClass ): > def __setattr__( self, attrname, value ): > if attrname == 'funky': > self.__dict__['fun'] = value > else: > SuperClass.__setattr__( self, attrname, value ) > > def __str__( self ): > return SuperClass.__str__( self ) + ', ' + str(self.fun) > >Is this the "Pythonic" way of doing it or should I do it in a different >way or do I have to use setX/getX (shudder) I'm totally new to Python myself, but my understanding is that From roccomoretti at hotpop.com Mon Jun 13 13:54:54 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 13 Jun 2005 12:54:54 -0500 Subject: Annoying behaviour of the != operator In-Reply-To: References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: Before I answer, let me clarify my position. I am NOT advocating any change for the 2.x series. I'm not even forwarding any particular proposal for 3.0/3000. My key (and close to sole) point is that behavior of > & < is conceptually distinct from ordering in a sorted list, even though the behaviors coincide for the most common case of numbers. >>One way to handle that is to refuse to sort anything that doesn't have >>a "natural" order. But as I understand it, Guido decided that being >>able to sort arbitrary lists is a feature, not a bug. But you can't >>sort ones with complex numbers in them, because you also want >>'1+3j<3+1j' to raise an error. > > > As George Sakkis noted, Guido has since recanted. Unfortunately, in > this case, the time machine would have broken too much existing code. As I mentioned in response, the referenced email only mentions the ability to use < & > in comparing arbitrary objects. My key point is that this is conceptually different than disallowing sorting on heterogeneous list. There are ways to disallow one, while still allowing the other. > "Doesn't" and "can't" (call me pessimistic) comes from all the issues > and disagreements we're having in this thread, and "shouldn't" comes > from the Zen: > > Explicit is better than implicit. > In the face of ambiguity, refuse the temptation to guess. Well, Python already "guesses implicitly", everytime you do a "1 + 2.0" or a "a + b", where 'a' doesn't define '__add__' and 'b' defines '__radd__' - The trick is to be clear and explicit (in the documetation) everytine you are implicit (in the running program). It's not guessing - it's a precisely defined part of the language. >>>AIUI, __cmp__ exists for backwards compatibility, and __eq__ and friends >>>are flexible enough to cover any possible comparison scheme. > > >>Except if you want the situation where "[1+2j, 3+4j].sort()" works, and >>'1+3j < 3+1j' fails. > > > I'm sticking with my position that both should fail, unless you > *explicity* tell sort what to do (since for now, we all seem to agree > that the other one should fail). If I have an application that thinks > it has to sort a list of arbitrary objects, then I have to be clever > enough to help. Even if you decide to disallow sorting heterogenous lists, you still have the problem of what to do a user defined homogeneous list where __lt__ doesn't return a boolean. Moreso: >>Except if you want the situation where "[a, b].sort()" works, and >>'a < b' fails. If you combine list sorting and >/< together, there is no way someone who wants >/< on a specific class to return a non-boolean value to have a homogeneous list of those objects sort the way they want them too. If, on the other hand, you split the two and provide a sensible and explicitly defined fall-back order, then someone who doesn't care about the distinction can carry on as if they were combined. In addition, those people who want to sort lists of objects which return non-booleans for >/< can do that too. BTW, the optional parameter for the sort function is not a suitable alternative. The main problem with it is where the sort order is encoded. The extra parameter in the sort has to be provided *every place* where sort is called, instead of a single place in the definition of the object. And you can't subclass the sort function in your user defined fuction, because sort is an operation on the list, not the objects in it. And please don't say that always explicitly specifying the sort order is a good thing, unless you want the sort order to *always* be specified, even with builtins. (Sorting numbers? Ascending/Descending/Magnitude? - Strings? ASCII/EBDIC/Alphabetical/Case Insensitive/Accents at the end or interspersed? -- Okay, a little petulant, but the real issue is lists/tuples/dicts. Why isn't the sort order on those explicit?) All that said, I'm not Guido, and in his wisdom he may decide that having a sort order different from that given by >/< is an attractive nuisance, even with user defined objects. He may then deside to disallow it like he disallows goto's and free-form indentation. From jabel at plus.net Mon Jun 20 11:22:07 2005 From: jabel at plus.net (John Abel) Date: Mon, 20 Jun 2005 16:22:07 +0100 Subject: Python choice of database In-Reply-To: References: Message-ID: <42B6DF1F.2060304@plus.net> Gadfly PySQLite ( requires SQLite library ) J Philippe C. Martin wrote: >Hi, > >I am looking for a stand-alone (not client/server) database solution for >Python. > >1) speed is not an issue >2) I wish to store less than 5000 records >3) each record should not be larger than 16K > > >As I start with Python objects, I thought of using shelve, but looking at >the restrictions (record size + potential collisions) I feel I should study >my options a bit further before I get started. > > >Regards, > >Philippe > > > From hancock at anansispaceworks.com Mon Jun 13 19:20:14 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 18:20:14 -0500 Subject: Request for help on naming conventions In-Reply-To: References: Message-ID: <200506131820.14882.hancock@anansispaceworks.com> On Monday 13 June 2005 03:59 am, Steven D'Aprano wrote: > Are there any useful naming conventions for modules, classes and functions? > > For instance, should I name functions as verbs and classes as nouns? Hmm. Okay, here's a few I use: Classes are generally: Capitalized or CapWords and I use nouns. Unless it's a "mix-in" in which case, I use adjectives. This mirrors usage in the Zope sources, BTW. Method names are either: funkyCaps (Zope uses this) or lower_case_with_underscores. I use verb names for methods and functions with very few exceptions. I use nouns or occasionally adjectives for attributes. Constants or enumeration values are ALLCAPS or ALL_CAPS, and usually I define them within a namespace with a descriptive, all lower case name (a trivial class). The enumeration is usually abbreviated, but would be an adjective, e.g.: color.RED I use *plural* names for lists and tuples, but singular names for mappings. This is so that I can use the singular in the loop: for book in books: pass But I use single character variables in list comprehensions (and generators, except I haven't used them yet): late_books = [b for b in books if b.duedate < datetime.now()] I also use single-character names in highly mathematical code: def dot_product(a,b): return a.x*b.x + a.y*b.y + a.z*b.z But if a variable is going to be used more than about 20 lines away from where it is defined, I use a descriptive word instead. I like to use Capital or CapWords for modules, too, although I'm beginning to wonder about that practice. I really hate redundancy like this: Topic.create_topic() and usually prefer: Topic.create() which of course means, I have to qualify things a lot in my code. This has never been an issue, but if it did, I would just introduce an intermediary like this ("_" for "."): Topic_create = Topic.create After that, it's kind of case-by-case. Do read PEP 8, too, of course. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From rkern at ucsd.edu Mon Jun 6 09:34:32 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 06 Jun 2005 06:34:32 -0700 Subject: Destructive Windows Script In-Reply-To: <1118063741.854716.183560@g14g2000cwa.googlegroups.com> References: <1118063741.854716.183560@g14g2000cwa.googlegroups.com> Message-ID: Michele Simionato wrote: > BTW, since this is a bit off-topic anyway, how do I recover > files accidentally removed? Is there a free tool that works > on FAT/NTFS and ext2/ext3? On all of those filesystems at the same time? Probably not. But there are tools for each. Google, and ye shall find. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steven.bethard at gmail.com Mon Jun 20 11:57:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Jun 2005 09:57:35 -0600 Subject: import via pathname In-Reply-To: <1119281457.058120.69070@g49g2000cwa.googlegroups.com> References: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> <1119281457.058120.69070@g49g2000cwa.googlegroups.com> Message-ID: <3YWdnehqSfzyeivfRVn-vQ@comcast.com> passion_to_be_free at hotmail.com wrote: > Ahh....I see. I played around with the sys.path function...and it > looks like python automatically looks in the same directory as my > script first. Then is searches to all the other pre-defined paths. So > it works for me to just keep my main script in the same directory as > the two modules I'm using. Yup, as long as you're not worried about having too many modules around, that should work fine. =) STeVe From gregpinero at gmail.com Thu Jun 9 21:55:29 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 9 Jun 2005 21:55:29 -0400 Subject: MySQLDBAPI In-Reply-To: <2tqln2-6c3.ln1@news.interplanet.it> References: <2tqln2-6c3.ln1@news.interplanet.it> Message-ID: <312cfe2b0506091855206c7e77@mail.gmail.com> I didn't see anything about mysql-devel package in the release notes. Is that something I can install all to my home directory? On 6/9/05, deelan wrote: > Gregory Pi?ero wrote: > > Hey guys, > (...) > > > > My first question is if there is anything built into python as far as > > a Database API that will work with MySQL. It seems like there should > > be because Python without it is kinda useless for web development. If > > there is then I'd probably prefer to use that instead. > > there is not. mysqldb module is the answer. > > (...) > >>>cd MySQL-python-1.2.0 > >>>python2.4 setup.py install --home=~ > > > > running install > > running build > > running build_py > > running build_ext > > building '_mysql' extension > > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall > > -Wstrict-prototypes -fPIC -I/usr/local/include/python2.4 -c _mysql.c > > -o build/temp.linux-i686-2.4/_mysql.o > > -I'/usr/local/mysql/include/mysql' > > _mysql.c:41:19: mysql.h: No such file or directory > > _mysql.c:42:26: mysqld_error.h: No such file or directory > > _mysql.c:43:20: errmsg.h: No such file or directory > > error: command 'gcc' failed with exit status 1 > > you need mysql-devel package installed to compile the "_mysql" extension. > > just look a the release notes: > > > HTH. > > -- > deelan, #1 fan of adriana lima! > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From kent37 at tds.net Thu Jun 9 13:28:23 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Jun 2005 13:28:23 -0400 Subject: splitting strings with python In-Reply-To: <1118308380.823382.146430@g47g2000cwa.googlegroups.com> References: <1118308380.823382.146430@g47g2000cwa.googlegroups.com> Message-ID: <42a87be0$1_3@newspeer2.tds.net> sbucking at gmail.com wrote: > im trying to split a string with this form (the string is from a > japanese dictionary file with mulitple definitions in english for each > japanese word) > > > str1 [str2] / (def1, ...) (1) def2 / def3 / .... (2) def4/ def5 ... / > > > the varibles i need are str*, def*. Could you post a few examples of real data and what you want to extract from it? The above raises a few questions: - are str* and def* single words or can they include whitespace, comma, slash, paren... - not clear what replaces the ... (or if they are literal) This might be a good job for PyParsing. Kent > > sometimes the (1) and (2) are not included - they are included only if > the word has two different meanings > > > "..." means that there are sometimes more then two definitions per > meaning. > > > im trying to use the re.split() function but with no luck. > > Is this possible with python, or am i dreamin!? > > All the best, > > . > From zanesdad at bellsouth.net Tue Jun 14 12:15:57 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 14 Jun 2005 12:15:57 -0400 Subject: collect data using threads In-Reply-To: <42aeeef3$1_1@newspeer2.tds.net> References: <42aeeef3$1_1@newspeer2.tds.net> Message-ID: <42AF02BD.9080809@bellsouth.net> Kent Johnson wrote: >Peter Hansen wrote: > > >>Qiangning Hong wrote: >> >> >> >>>A class Collector, it spawns several threads to read from serial port. >>>Collector.get_data() will get all the data they have read since last >>>call. Who can tell me whether my implementation correct? >>> >>> >>[snip sample with a list] >> >> >> >>>I am not very sure about the get_data() method. Will it cause data lose >>>if there is a thread is appending data to self.data at the same time? >>> >>> >>That will not work, and you will get data loss, as Jeremy points out. >> >>Normally Python lists are safe, but your key problem (in this code) is >>that you are rebinding self.data to a new list! If another thread calls >>on_received() just after the line "x = self.data" executes, then the new >>data will never be seen. >> >> > >Can you explain why not? self.data is still bound to the same list as x. At least if the execution sequence is >x = self.data > self.data.append(a_piece_of_data) >self.data = [] > >ISTM it should work. > >I'm not arguing in favor of the original code, I'm just trying to understand your specific failure mode. > >Thanks, >Kent > > Here's the original code: class Collector(object): def __init__(self): self.data = [] spawn_work_bees(callback=self.on_received) def on_received(self, a_piece_of_data): """This callback is executed in work bee threads!""" self.data.append(a_piece_of_data) def get_data(self): x = self.data self.data = [] return x The more I look at this, the more I'm not sure whether data loss will occur. For me, that's good enough reason to rewrite this code. I'd rather be clear and certain than clever anyday. So, let's say you a thread T1 which starts in ``get_data()`` and makes it as far as ``x = self.data``. Then another thread T2 comes along in ``on_received()`` and gets as far as ``self.data.append(a_piece_of_data)``. ``x`` in T1's get_data()`` (as you pointed out) is still pointing to the list that T2 just appended to and T1 will return that list. But what happens if you get multiple guys in ``get_data()`` and multiple guys in ``on_received()``? I can't prove it, but it seems like you're going to have an uncertain outcome. If you're just dealing with 2 threads, I can't see how that would be unsafe. Maybe someone could come up with a use case that would disprove that. But if you've got, say, 4 threads, 2 in each method....that's gonna get messy. And, honestly, I'm trying *really* hard to come up with a scenario that would lose data and I can't. Maybe someone like Peter or Aahz or some little 13 year old in Topeka who's smarter than me can come up with something. But I do know this - the more I think about this as to whether this is unsafe or not is making my head hurt. If you have a piece of code that you have to spend that much time on trying to figure out if it is threadsafe or not, why would you leave it as is? Maybe the rest of you are more confident in your thinking and programming skills than I am, but I would quickly slap a Queue in there. If for nothing else than to rest from simulating in my head 1, 2, 3, 5, 10 threads in the ``get_data()`` method while various threads are in the ``on_received()`` method. Aaaagghhh.....need....motrin...... Jeremy Jones -------------- next part -------------- An HTML attachment was scrubbed... URL: From rex.eastbourne at gmail.com Fri Jun 24 16:42:19 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 24 Jun 2005 13:42:19 -0700 Subject: Running Python interpreter in Emacs In-Reply-To: References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> Message-ID: <1119645739.213660.103840@o13g2000cwo.googlegroups.com> I have the following in my .emacs: (add-to-list 'load-path "C:\Program Files\Python24") Is that enough? I didn't see anything similar to that in your .emacs file, so I'm wondering if I'm supposed to add the path to my PATH elsewhere. Thanks, Rex From powderkeg at snow.email.ne.jp Fri Jun 3 02:17:39 2005 From: powderkeg at snow.email.ne.jp (Mark Sargent) Date: Fri, 03 Jun 2005 15:17:39 +0900 Subject: Moving Places, Subtracting from slices/lists In-Reply-To: References: <429EACCE.8050101@snow.email.ne.jp><429EB16C.1090509@snow.email.ne.jp> Message-ID: <429FF603.80207@snow.email.ne.jp> Fredrik Lundh wrote: >Elliot Temple wrote: > > > >>btw hotcat[:] is a *copy* of hotcat, so just leave out "[:]" >> >> > >when you want to modify the thing you're looping over, you need >to be careful. looping over a copy is often a good idea (see the >Python tutorial and the FAQ for more on this). > > > Yes, I saw that, and that's why I was using the copy form in the loop...thanx for verifying this. >>enumerate is a function that adds indexes to a list. observe: >> >> > > > >>>>hotcat = ['roof', 'roof', 'roof'] >>>>for index, word in enumerate(hotcat): >>>> if word == 'roof': del hotcat[index] >>>>print hotcat >>>> >>>> >['roof'] > >if I understand the OP correctly, he wants to *move* the "roof" to the >end of the string. > > correct... > try: > hotcat.remove("root") > hotcat.append("root") > except ValueError: > pass > >is most likely the fastest way to do that. > > > > > will give it a blast...thanx > > > Cheers. Mark Sargent. From phillip.watts at anvilcom.com Wed Jun 29 08:11:43 2005 From: phillip.watts at anvilcom.com (phil) Date: Wed, 29 Jun 2005 07:11:43 -0500 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119956464.362328.290370@o13g2000cwo.googlegroups.com> <87ekala2xf.fsf@titan.staselog.com> Message-ID: <42C28FFF.7010303@anvilcom.com> > I don't want to start a flamewar here - > No heat, no flames. Everyone's cool > Let me emphasize a little more. Even though Python itself is great, I think we > don't have quite yet tools that offer > Ya know, I just don't know enough about javaworld. The language I do not like. I wonder what percentage of the tools you refer to are Eclipse and not Java per se. ?? I don't know. The really big bucks of IBM sent Eclipse through the roof. Python reminds me more of Linux. Incredible no of packages, kinda disjointed, docs pretty bad, not integrated. But amazing stuff if you have the stomach for it. (seen pygame?) Maybe Python will get a daddy someday. Comes down to preference. Isn't it absolutely amazing how many choices we have. Remember the 70's - Cobol, ASM, C, Basic.CICS(shudder) I am pleased that folks on a Python list feel free to praise other technologies. That's neat. From bokr at oz.net Sun Jun 26 14:57:59 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 18:57:59 GMT Subject: Interpreter-like help in cmd.Cmd References: <2MCdnf5cFKCCLjXfRVn-pw@powergate.ca> Message-ID: <42bef47a.269535721@news.oz.net> On Thu, 09 Jun 2005 16:53:17 -0700, Sarir Khamsi wrote: >Peter Hansen writes: > >> class _Helper(object): >> """Define the built-in 'help'. >> This is a wrapper around pydoc.help (with a twist). >> >> """ >> >> def __repr__(self): >> return "Type help() for interactive help, " \ >> "or help(object) for help about object." >> def __call__(self, *args, **kwds): >> import pydoc >> return pydoc.help(*args, **kwds) > >Thanks, but how do I integrate this with cmd.Cmd? Have you read the docs for the cmd module? E.g., http://www.python.org/doc/current/lib/Cmd-objects.html """ All subclasses of Cmd inherit a predefined do_help(). This method, called with an argument 'bar', invokes the corresponding method help_bar(). With no argument, do_help() lists all available help topics (that is, all commands with corresponding help_*() methods), and also lists any undocumented commands. """ This suggests that typing "help xxx" might call do_help('xxx') and that will call help_xxx if it exists. So if you want help on a non-cmd.Cmd command, you might want to modify do_help to call pydoc as above instead of generating its default have-no-help repsonse, whatever that is. Just guessing, but that should get you closer. You can look at the source in python\Lib\cmd.py E.g., D:\Python23\Lib\cmd.py or D:\Python-2.4b1\Lib\cmd.py for me. Look in cmd.py at class Cmd method do_help: def do_help(self, arg): if arg: # XXX check arg syntax try: func = getattr(self, 'help_' + arg) except AttributeError: try: doc=getattr(self, 'do_' + arg).__doc__ if doc: self.stdout.write("%s\n"%str(doc)) return except AttributeError: pass [1] --> self.stdout.write("%s\n"%str(self.nohelp % (arg,))) return func() else: # ... generates topic listing Probably you can write your own Cmd subclass and override do_help and modify at [1] to do the pydoc call as in Peter's snippet. Hopefully no weird interactions, but it should be easy to try ;-) HTH Regards, Bengt Richter From newsgroups at jhrothjr.com Mon Jun 27 20:24:54 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 27 Jun 2005 18:24:54 -0600 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Message-ID: <11c166s2sh66b93@news.supernews.com> "Inkiniteo" wrote in message news:1119911939.179743.98220 at z14g2000cwz.googlegroups.com... > Hi guys. I have a script that sends the info by email, but i'd like to > avoid the convertion to HTML by the email client or Gmail, because it > ruins all the formatting i did (with tabs, mostly). Briefing, i wanna > be able to send SMTP mail and the receiver only get it in plain text. As long as your mimetype is text/plain you should have minimal trouble. There's no way you can control what the recipient's mail client does, however. In particular, there are a lot of mail clients out there that handle tabs poorly. Outlook Express is the poster child for this: it ignores tabs completely, however it is by no means the only culprit. It's simply the most widespread one. In other words, use strings of spaces rather than tabs, and you'll probably find your messages coming out looking better. John Roth > From bronger at physik.rwth-aachen.de Sun Jun 5 12:45:39 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Sun, 05 Jun 2005 18:45:39 +0200 Subject: maybe a bug in python References: Message-ID: <87mzq4lpl8.fsf@wilson.rwth-aachen.de> Hall?chen! flyaflya writes: >>>> a = {1: ("a")} >>>> a[1] > 'a' > why not ('a')? ("a") is not a tuple, but ("a",) is. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From timh at zute.net Fri Jun 10 22:41:42 2005 From: timh at zute.net (Tim Hoffman) Date: Sat, 11 Jun 2005 10:41:42 +0800 Subject: How to use axdebug Message-ID: <42aa4f67$1@news.highway1.com.au> Hi I am trying to work how how to use axdebug, and for the life of me can't work it out. I have tried google ;-) and looked for docs, and now am working through the code. I have a Delphi/C++ app that has a Delphi Scripting component that uses windows underlying Scripting Host, and am successfully running Python (via COM (registered through axscript) in this environment and passing objects from the delphi env to the python code, calling ,methods etc.... My reading of the code of axdebug, suggests that the windows script debugger should be startable/invokable in some way and via axdebug supposedly able to debug a python script. However I can't for the life of me work out how this might happen. Has anyone got any clues, hints, rtfm's they can suggest. I have been able to get remote debugging via Boaconstructor working, but wanted to see if I could get there via the Windows Script Debugger. Rgds Tim From nospam at here.com Tue Jun 14 10:06:31 2005 From: nospam at here.com (Matt Feinstein) Date: Tue, 14 Jun 2005 10:06:31 -0400 Subject: Problem with 'struct' module Message-ID: Using the 'struct' module (Win32, python version 2.4.1)-- The library documentation says that 'no alignment is required for any type'. However, struct.calcsize('fd') gives 16 while struct.calcsize('df') gives 12, implying that double precision data has to start on a double-word boundary. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From aahz at pythoncraft.com Sat Jun 11 19:03:03 2005 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2005 16:03:03 -0700 Subject: How many threads are too many? References: Message-ID: In article , rbt wrote: > >When designing a threaded application, is there a pratical limit on the >number of threads that one should use or is there a way to set it up so >that the OS handles the number of threads automatically? I am developing >on 32-bit x86 Intel systems with python 2.4.1. The OS will be Linux and >Windows. The practical limit is somewhere between five and a hundred threads, depending on what you're doing. The more I/O you're doing, the more greater numbers of threads will benefit you. >I have an older app that used to work fine (254 threads) on early 2.3 >Pythons, but now, I get this error with 2.4.1 and 2.3.5: > >Traceback (most recent call last): > File "net_queue_and_threads.py", line 124, in ? > thread.start() > File "/usr/lib/python2.3/threading.py", line 416, in start > _start_new_thread(self.__bootstrap, ()) >thread.error: can't start new thread That's rather odd. Which OS is this? Did you build Python yourself or did you download it? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From steven.bethard at gmail.com Thu Jun 30 00:02:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Jun 2005 22:02:22 -0600 Subject: aligning text with space-normalized text In-Reply-To: <42C35438.2010207@lexicon.net> References: <42C35438.2010207@lexicon.net> Message-ID: John Machin wrote: > If "work" is meant to detect *all* possibilities of 'chunks' not having > been derived from 'text' in the described manner, then it doesn't work > -- all information about the positions of the whitespace is thrown away > by your code. > > For example, text = 'foo bar', chunks = ['foobar'] This doesn't match the (admittedly vague) spec which said that chunks are created "as if by ' '.join(chunk.split())". For the text: 'foo bar' the possible chunk lists should be something like: ['foo bar'] ['foo', 'bar'] If it helps, you can think of chunks as lists of words, where the words have been ' '.join()ed. STeVe From antonxx at gmx.de Thu Jun 2 03:00:26 2005 From: antonxx at gmx.de (anton) Date: 2 Jun 2005 00:00:26 -0700 Subject: BCB5 & Py_InitModule in python 2.3.5 crashes sometimes Message-ID: <1117695626.702827.217420@g47g2000cwa.googlegroups.com> Hi, I embedded the python 2.3.5 interpreter in my Borland C++ Builder 5 application on WinXP pro Sp2 and all runs fine. (I translated the python23.lib with coff2omf) But from time to time when I call Py_InitModule I get a dialog: Title: Microsoft Visual C++ Runtime Library Text: Program: bla\bla\myapp.exe This application has requested the Runtime to terminate in an unusual way, please contact the applicatio'n team for more information. (This problem appears sometime somewhere else too, but I was not able to localize it) My question is: - has somebody experienced something similar with BCB5? (so I know if its perhaps a bug in bcb only) - or is it a bug in python 2.3.5 - has the python interpreter some threads which are perhaps not completely initialized?? - would python 2.4.1 help (since its linked with VS 2003??) When I go through my code step by step in the bcb debugger all runs fine, only if i "run" over the critical part I get the problem. (thats the reason its so hard to localize) The python interpreter is initialized when I click on a button in my app (not in the startapp of the app) The funny thing: I crash 3 times my app, and when I try it the 4'th time it works. I would be very glad for even a small hint, since actually I have no more ideas :-( Thanks From peter at engcorp.com Wed Jun 8 10:15:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Jun 2005 10:15:13 -0400 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: <1118238280.678863.211490@g44g2000cwa.googlegroups.com> References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Message-ID: <7r-dnd4Q5rThYDvfRVn-pA@powergate.ca> ajikoe at gmail.com wrote: > It means in windows we should use 'wb' to write and 'rb' to read ? > Am I right? There is a conceptual difference between "text" files and other files (which are lumped under the label "binary"). Binary files have any kind of data in them (bytes from 0 to 255) and no inherent concept of "lines", and thus no line ending sequences. Text files generally have no control characters except those used to terminate the lines (lines are by definition sequences of bytes followed by the line ending sequence). The line ending sequence is platform-dependent: Linux and most other things use just \n (LineFeed), while Windows/DOS uses \r\n (CarriageReturn + LineFeed) and the old MacOS used just \r (CarriageReturn). Since the specific line ending used on your platform is rarely important to you, so long as you are compatible with other applications that use "text" files (such as Notepad), you should use just "r" and "w" to read and write files that you consider "text" (and note: it's just a convention, in your mind... and at some times a given file might be treated the other way, quite legitimately). Python (actually the underlying libraries, I believe) will convert the platform-specific line endings to \n when reading text files, and will convert \n to the proper line ending sequence for your platform when writing. If you don't want this conversion, which is unlikely if this is really just a text file, then and only then do you want to use "rb" and "wb". So the answer to the question "What should I be using?" depends entirely on you: if you were interested in seeing the raw bytes that Notepad wrote, then use "rb". If you want to work with that file as a *text* file, then use just "r". Note also the existence of the "U" modifier. Opening a file with "rU" will read any of the aforementioned line-ending sequences and convert them to just \n, allowing you to work with text files created on other platforms. (I don't believe there's a "wU" and conceptually it's sort of meaningless anyway, so you would just use "w" to write the file out again.) -Peter From peter at somewhere.com Wed Jun 15 03:43:06 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 15 Jun 2005 09:43:06 +0200 Subject: What is different with Python ? In-Reply-To: <42AF24CC.2040507@carmen.se> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <42AF24CC.2040507@carmen.se> Message-ID: Magnus Lycka schrieb: > Peter Maas wrote: > >> Learning is investigating. By top-down I mean high level (cat, >> dog, table sun, sky) to low level (molecules, atoms, fields ...). > > > Aha. So you must learn cosmology first then. I don't think so. ;) I wasn't talking about size but about sensual accessibility. And I'm going to withdraw from this discussion. My English is not good enough for this kind of stuff. And ... it's off topic! ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From hammer at maxwell.com Fri Jun 17 11:01:54 2005 From: hammer at maxwell.com (Maxwell Hammer) Date: Fri, 17 Jun 2005 11:01:54 -0400 Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') References: Message-ID: Thanks Brian & Martin for the links. I actually found another good one: http://linuxgazette.net/107/pai.html Cheers. From kraus at hagen-partner.de Thu Jun 2 03:10:41 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 02 Jun 2005 09:10:41 +0200 Subject: What's wrong with Zope 3 ? In-Reply-To: <1117646659.949604.308920@z14g2000cwz.googlegroups.com> References: <1117581035.584193.310060@g47g2000cwa.googlegroups.com> <1117646659.949604.308920@z14g2000cwz.googlegroups.com> Message-ID: Kay Schluehr wrote: > > Wolfram Kraus wrote: > >> Kay Schluehr wrote: >> >>> The last downloadable release is from november 2004. The Windows >>> installer is configured for Python 2.3(!). The Zope.org main page >>> announces Zope 2.8 beta 2. Is it stillborn? >>> >>> Kay >>> >> >> What you see is not Zope 3, it is Zope X 3. To quote from the X3 >> information page: "Zope X3 3.0 is for developers. If you are >> expecting an end-user application, this is not for you." > > > Yes I noticed this almost 8 months ago, read a bit of the > documentation and articles published that time, regarded it as > interesting and considered it for future development. But since then > absolutely nothing happened. No project plan, no time-schedule, no > subsequent releases. You can always scan the zope3-mailinglist at zope.org (or via news.gmane.org) to see whats happening. Migth be a better place for questions, too. >> The current stable brance is Zope2.X If you want to incorporate >> some functionalty from X3 in Zope 2.X, do a search for "Five" > > > No, I do not want to migrate components from a new major release > backwards, as well as I do not want to migrate applications from > WinXP to Win98. This seems to be the wrong development process > direction. Well, the problem is that it is not a "new major release" but a "new mayor experimental release". And X3 is not backward compatible, so a lot of Z2 products, e.g. Plone, don't work with X3. > Regards, Kay > HTH, Wolfram (still using Z2 ;-)) From peter at engcorp.com Sat Jun 18 12:56:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:56:32 -0400 Subject: extreme newbie In-Reply-To: <1119111817.610572.73580@g14g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> <1119111817.610572.73580@g14g2000cwa.googlegroups.com> Message-ID: cpunerd4 wrote: > I see your point, although I don't think there is much a 14 year old > can do to sue someone. . . I'm sure my code won't be that valuable > untill I'm older though. Thanks You're probably wrong on the first count, and whether you're wrong on the second is entirely up to you. ;-) (I recall hearing of at least one programmer who made his first million around the age of 14 after having written some brilliant game back in the days of Apple IIs and C-64s. These days I'd be surprised if 14 was still the lower limit for millionaire status amongst young programmers.) -Peter From bogus@does.not.exist.com Wed Jun 29 16:10:01 2005 From: bogus@does.not.exist.com () Date: Wed, 29 Jun 2005 20:10:01 -0000 Subject: No subject Message-ID: #! rnews 1192 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!tiscali!transit0.news.tiscali.nl!tudelft.nl!txtfeed1.tudelft.nl!feeder2.cambrium.nl!feed.tweaknews.nl!feeder.enertel.nl!nntpfeed-01.ops.asmr-01.energis-idc.net!in.100proofnews.com!in.100proofnews.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 18 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Wed, 29 Jun 2005 19:43:22 GMT Xref: news.xs4all.nl comp.lang.python:384026 "Adriaan Renting" writes: [snip] > This doesn't mean I would recommend VB for everything. For large > projects C++ or java can both be far superior, depending on needs and > available tools and libraries. I realy like Python for small projects on > Linux. Both VB and Python are easier to learn as the more powerful > languages, the price is that they lack features that make it easier to > manage large and complex projects. > [snip] What is a large project, and what is Python missing that C++ and Java have for such tasks? -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From irmen.NOSPAM at xs4all.nl Fri Jun 3 14:56:50 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 03 Jun 2005 20:56:50 +0200 Subject: [ANN] Snakelets 1.41 and Frog 1.6 Message-ID: <42a0a7f4$0$29628$e4fe514c@news.xs4all.nl> I'm happy to announce the release of Snakelets 1.41 and at the same time Frog 1.6. Snakelets is a Python web application server. This project provides a threaded web server, Ypages (HTML+Python language, similar to Java's JSPs) and Snakelets: code-centric page request handlers (similar to Java's Servlets). Frog is a Blog server application written for Snakelets. It is small but has many features, such as BBcode markup, XHTML+CSS page output, multiple users, no database required, anti-spam measures, email notification, Smileys, RSS feeds, and more. Please find more info on both projects here: http://snakelets.sourceforge.net/ Download: http://sourceforge.net/project/showfiles.php?group_id=41175 The detailed release notes have been added to the version section. Have fun! --Irmen de Jong From xah at xahlee.org Sat Jun 18 04:11:51 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jun 2005 01:11:51 -0700 Subject: Python documentation problem In-Reply-To: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Message-ID: <1119082311.658973.169610@o13g2000cwo.googlegroups.com> i wanted to find out if Python supports eval. e.g. somecode='3+4' print eval(somecode) # prints 7 in the 14 hundred pages of python doc, where am i supposed to find this info? Xah xah at xahlee.org ? http://xahlee.org/ From gabor at nekomancer.net Tue Jun 14 06:44:50 2005 From: gabor at nekomancer.net (gabor) Date: Tue, 14 Jun 2005 12:44:50 +0200 Subject: multi-CPU, GIL, threading on linux Message-ID: <9f1d7$42aeb56d$3eb01f24$9062@news.flashnewsgroups.com> hi, as i understand, on linux, python uses the operating systems threads (so python is not simulating threads by himself). that means that on a multi-CPU computer, the different threads may get executed on different CPUs. i am working with zope, and i was referenced to this page: http://www.zope.org/Members/glpb/solaris/report_ps it's rather old (2002), but it claims the following: > I do *not* recommend running Zope on multiprocessor machines without an > ability to restrict Zope to execution on a single CPU. > > The reason for this is that the Python Global Interpreter Lock is shared > inside a Zope process. However, threads in Python are backed by > underlying OS threads. Thus, Zope will create multiple threads, and > each thread is likely to be assigned to a different CPU by the OS > scheduler. However, all CPUs but one which are dispatching any given > Zope process will have to then wait and attempt to acquire the GIL; this > process introduces significant latency into Python and thus into Zope. now, i know about tools that allow me to bind a python process to a specific cpu, but i wonder.. is the performance soo bad when i am running a python process, and the threads are running on different cpus? i understand that because of the GIL i cannot make my application faster. but slower? thanks, gabor From cam.ac.uk at mh391.invalid Thu Jun 2 21:39:21 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 03 Jun 2005 02:39:21 +0100 Subject: optparse.py: FutureWarning error In-Reply-To: References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > c) Check to see if Python has a startup option for suppressing warnings > > As to c) python -h gives a list indicating what I thought, that -W controls > warnings, but gives insufficient info for me to use it, and I didn't find > any more in the docs. I hope someone else chimes in. man python. Search for -W. -- Michael Hoffman From sjmachin at lexicon.net Tue Jun 7 18:25:28 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 08 Jun 2005 08:25:28 +1000 Subject: time consuming loops over lists In-Reply-To: References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> Message-ID: <42A61ED8.5030701@lexicon.net> Diez B. Roggisch wrote: > querypk at gmail.com wrote: > >> X-No-Archive: yes >> Can some one help me improve this block of code...this jus converts the >> list of data into tokens based on the range it falls into...but it >> takes a long time.Can someone tell me what can i change to improve >> it... >> > > >> if data[i] in xrange(rngs[j],rngs[j+1]): >> > > That's a bummer: You create a list and then search linearily in in - > where all you want to know is > > if rngs[j] <= data[i] < rngs[j+1] > > Attached is a script that does contain your old and my enhanced version > - and shows that the results are equal. Running only your version takes > ~35s, where mine uses ~1s!!! > > Another optimization im too lazy now would be to do sort of a "tree > search" of data[i] in rngs - as the ranges are ordered, you could find > the proper one in log_2(len(rngs)) instead of len(rngs)/2. > > Additional improvements can be achieved when data is sorted - but that > depends on your application and actually sizes of data. > > Diez > [snip] Make these changes/additions: ================================================= # from Numeric import * # +1 for Overkill-of-the-Year def zeros(n): return n * [0.0] def Tkz3(tk, data, no_of_bins): # indent 5 ??????? # change other funcs to have no_of_bins as an arg tkns = [] dmax = max(data)+1 dmin = min(data) rng = int(ceil(abs((dmax - dmin)/(no_of_bins*1.0)))) for datum in data: j = (datum - dmin) // rng tkns.append( str(tk)+str(j) ) return tkns for func in (Tkz, Tkz2, Tkz3): t0 = time.time() result = func('A', data, nbins) t1 = time.time() results.append(result) print "function %s took %.2f seconds to produce %d tokens" % (func.__name__, t1 - t0, len(result)) allsame = results [0] == results[1] == results[2] print "\nIdentical results:", allsame ======================================================= and get this: C:\junk>ranges.py C:\junk\ranges.py:46: DeprecationWarning: integer argument expected, got float if data[i] in xrange(rngs[j], rngs[j+1]): function Tkz took 12.13 seconds to produce 12292 tokens function Tkz2 took 0.08 seconds to produce 12292 tokens function Tkz3 took 0.02 seconds to produce 12292 tokens Identical results: True ================================================== using Python 2.4.1 (win32) on a 3.2Ghz Intel P4 ================================================== Notes: (1) The OP's code as well as being deliciously O(N**2) depends on the data beint *integers* -- otherwise it goes rapidly pear-shaped; see the deprecation warning above, and try running it with data = [0.00001* x for x in range(20, 12312)]. Consequently the use of math.* is a /mild/ overkill. (2) The OP's code produces bins of equal nominal width but depending in the range, the population of the last bin may be much less than the population of the other bins. Another way of doing it would be to produce bin widths so that the populations were more evenly spread. In any case determining the appropriate bin could still be done by formula rather than by searching. Cheers, John From aahz at pythoncraft.com Sat Jun 11 10:24:14 2005 From: aahz at pythoncraft.com (Aahz) Date: 11 Jun 2005 07:24:14 -0700 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118390462.698504.43650@z14g2000cwz.googlegroups.com> <1118401494.385789.289320@g49g2000cwa.googlegroups.com> Message-ID: In article <1118401494.385789.289320 at g49g2000cwa.googlegroups.com>, wooks wrote: > >Thank you for the long lecture on netiquette which I didn't really >need. You obviously do need it given your improper quoting and attributions. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From grig.gheorghiu at gmail.com Fri Jun 3 16:55:48 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 3 Jun 2005 13:55:48 -0700 Subject: Python interest group software References: Message-ID: <1117832148.591030.206870@g49g2000cwa.googlegroups.com> Try upcoming.org. In addition to the Web interface, they also offer a REST-ful API that you can use from your own app. Grig From rrr at ronadam.com Sat Jun 4 12:56:01 2005 From: rrr at ronadam.com (Ron Adam) Date: Sat, 04 Jun 2005 16:56:01 GMT Subject: Scope In-Reply-To: References: Message-ID: Elliot Temple wrote: > I want to write a function, foo, so the following works: > > def main(): > n = 4 > foo(n) > print n > > #it prints 7 > > if foo needs to take different arguments, that'd be alright. > > Is this possible? It is possible if you pass mutable objects to foo such as lists or dictionaries. Is this what you are looking for? def main(): d = [3,] foo(d) print d[0] def foo(var): var[0] = 7 main() Cheers, _Ron From thomasbartkus at comcast.net Sat Jun 11 12:51:02 2005 From: thomasbartkus at comcast.net (tom) Date: Sat, 11 Jun 2005 11:51:02 -0500 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118429907.140244.298390@g43g2000cwa.googlegroups.com> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 10 Jun 2005 21:57:40 -0700, fuzzylollipop wrote: > I was completely serious, he is _NOT_ going to win this one. He has > already lost. I have been on both sides of this scenario, the "new guys" > were brought in and will win since they are the new "experts from out of > town". Not only do I take you seriously - I agree! I also have been on both sides of this scenario although my take on it is slightly different. It's not so much the "experts from out of town" as it is the tendency to dump the guy(s) that brought them to the party. The sequence goes like this: 1) When there is little or no money to be made, you start out with an implied status as a partner. This means you work long + extra hours for little pay on the promise that you will be rewarded when/if success comes. 2) Then the product gets out the door and it's more long hours with little pay. Much massaging and tweaking and still little money incoming. 3) Success & money start to roll in. Now your status drops from partner to hired hand. An overpaid hired hand at that. Now that the heavy lifting is done, managment is wondering whether they need to actually reward the guy(s) who brought them to the party. The rational parts of their brains shut down while every fiber of their larcenous beings wants them to believe they can now dispense with the high priced talent (you!) for some low bucks commodity labor. There scads of outsourcing firms tripping over one another to sell them the latter. > There may be some other _VALID_ business reason that management has > already made up their mind to hire these Java people. Probably because > they want to sell the company or merge with someone or something and > having a Java product would make them more attractive. Yes, there is a possible _VALID_ reason. That would be the perception, probably accurate, that a technology like Java will shelter them from total dependency on some individual developer (you!). In other words, there is a greater likelihood that they can find replacement talent should they need it. Thats the optimistic view. More often it sinks to the sleazy when they decide to stiff the original guys who did all the extra work up front. If they can replace them, there will be no need to "pay off" on the extra work they did up front. I have had this happen to me as an employee. Later, as an outside consultant, I was frequently disgusted to realize how many manager/owners were merely seeking to avoid the payoff for the guys who went the extra mile to give them a profitable product. Tis business in the USA, sad to say. > There are 2 things he can do. > > 1. Get your resume ready and approach the CEO or whomever and say. Why > is this happening? Since I can guarantee you they have already decided > to port this app to Java. Resume ready is certainly wise and I concur with your gaurantee. > 2. Be quiet, keep his head down, learn Java fasssstt, start agreeing > with the new party line and get on the bandwagon if he really wants to > stay at this company ( I wouldn't ) I disgree here. The party line is nothing but a cover. The goal is to break the dependency on the guru(s) who did the developement or worse, outright replacement. The likelihood of staying on is slim and will become increasingly unpleasant unless the employer is so lacking in concience as to fire him outright. Let me add an Item #3 - If you have some entrepeneurial savvy and can keep your emotions out of it tou can simply tell them you have decided strike out on your own and tell them that you will be available. They will be happy to hear you are leaving and happier still to hear you can be available for backup. Their goals and fears are addressed at the same time. AND there is a very high possibility that they will *need* you at a later date for which you can charge them dearly. That last item #3 has actually worked for me with (2) prior employers. I did have to eat my indignation and keep it friendly but it did pay off in the end. Thomas Bartkus From max at alcyone.com Thu Jun 9 00:43:04 2005 From: max at alcyone.com (Erik Max Francis) Date: Wed, 08 Jun 2005 21:43:04 -0700 Subject: poker card game revisited (code included) In-Reply-To: References: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> Message-ID: John Hazen wrote: > Interesting. I've been thinking about playing with this stuff too, but > hadn't considered masks. So each card has a representation: > > n bits for rank, then m bits for suit. > > 00000000000010 0001 = 2 clubs > 01000000000000 1000 = K spades > ... You can also deal with them as a mask of card indexes. So the deuce of clubs is bit 0, the three of clubs is bit 1, all the way up to the ace of spades, which is bit 51. (That obviously won't fit in an int; you'll need a long.) -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis You are the lovers rock / The rock that I cling to -- Sade From rrocky at bigfoot.com Wed Jun 29 23:44:21 2005 From: rrocky at bigfoot.com (Gafoor) Date: Thu, 30 Jun 2005 09:14:21 +0530 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <3ih84nFlkegqU1@individual.net> Steven D'Aprano wrote: > But don't worry, there is one thing we all agree on throughout the > English-speaking world: you Americans don't speak English. > > There are a few things that you can do to help: > > Herb starts with H, not E. It isn't "ouse" or "ospital" or "istory". > It isn't "erb" either. You just sound like tossers when you try to > pronounce herb in the original French. And the same with homage. > > Taking of herbs, there is no BAY in basil. And oregano sounds like Ray > Romano, not oh-reg-ano. > > And please, fillet of fish only has a silent T if you are speaking > French. 'T' is always silent in the USA. - Innernet - Twenny > Aluminium is al-u-min-ium, not alum-i-num. > > Scientists work in a la-bor-atory, not a lab-rat-ory, even if they > have lab rats in the laboratory. > > Fans of the X-Men movies and comics will remember Professor Charles > Xavier. Unless you are Spanish (Kh-avier), the X sounds like a Z: > Zaviour. But never never never Xecks-Aviour or Eggs-Savior. > > Nuclear. Say no more. From benji at benjiyork.com Thu Jun 30 11:48:12 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 30 Jun 2005 11:48:12 -0400 Subject: I have a question. In-Reply-To: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> References: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Message-ID: <42C4143C.600@benjiyork.com> Nathan Pinno wrote: > Does Python have a random function? If so, can you show me an example > using it? http://docs.python.org/lib/module-random.html -- Benji York From lycka at carmen.se Wed Jun 8 05:07:47 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 08 Jun 2005 11:07:47 +0200 Subject: calling ksh script from python In-Reply-To: <1117788937.207065.18670@z14g2000cwz.googlegroups.com> References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> <1117788937.207065.18670@z14g2000cwz.googlegroups.com> Message-ID: ronan_boisard at yahoo.com wrote: > thanks for your input... > well I just find out that modifying environment through ksh call is not > possible (can't get the new evironment back to python). I thought about this a few days ago. Can't you copy it like this: import os env_rows = os.popen('. some.script > /dev/null; env).readlines() for row in env_rows: var, val = row.split('=',1) os.environ[var]=val From nevillednz.python at 3ttechnology.com Sun Jun 12 14:22:12 2005 From: nevillednz.python at 3ttechnology.com (Neville C. Dempsey) Date: Mon, 13 Jun 2005 02:22:12 +0800 Subject: slicing a bsddb table, eg. for rec in bsddb["AArdvark":"zebra"]: print rec Message-ID: <1118600533.4398.21.camel@localhost> #!/bin/env python import bsddb test=bsddb.btopen("test.tbl") for m in "JFMATQPHSOND": test[m]="Profit for month "+m+" $1B" def subyear_report(record_selection): for data in record_selection.iteritems(): print data # I was expecting a slice of an index file to yield a # generator so not all the records need to be read from disk.... subyear_report(test["Apr":"Sep"]) """ I have tried a few ideas.... but is there a simple way to convert this ["Apr":"Sep"] slice of a file into a generator of the requested records? (I tried UserDict and got a bit further...) Any hints? ThanX NevilleDNZ """ From pdemb at gazeta.pl Sun Jun 12 15:09:56 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 12 Jun 2005 21:09:56 +0200 Subject: How to get/set class attributes in Python References: <42ac6b5b$0$27173$626a14ce@news.free.fr> Message-ID: <87k6kzgznf.fsf@hector.domek> Bruno Desthuilliers writes: [snap] >> Being an untyped language, Python does not require you to enforce >> types. > > Nope. Python *is* typed. But it doesnt confuse implementation > with semantic. Python is typed. And its type system may look strange for anyone who did only Java or C++ programming before :> From danb_83 at yahoo.com Wed Jun 8 18:26:39 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 8 Jun 2005 15:26:39 -0700 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> <1118264973.349272.173370@z14g2000cwz.googlegroups.com> <1118266071.818457.177120@g47g2000cwa.googlegroups.com> Message-ID: <1118269599.446998.96420@g44g2000cwa.googlegroups.com> Mahesh wrote: > I understand that what makes perfect sense to me might not make perfect > sense to you but it seems a sane default. When you compare two objects, > what is that comparision based on? In the explicit is better than > implicit world, Python can only assume that you *really* do want to > compare objects unless you tell it otherwise. The only way it knows how > to compare two objects is to compare object identities. This isn't the issue here. I agree that object identity comparison is a good default equality test. The issue is whether this default should be thought of as # your approach (and the current implementation) def __eq__(self, other): return self is other def __ne__(self, other): return self is not other or # my approach def __eq__(self, other): return self is other def __ne__(self, other): return not (self == other) My approach simplifies the implementation (i.e., requires one fewer method to be overridden) of classes for which (x != y) == not (x == y). This is a very common case. Your approach simplifies the implementation of classes for which equality tests are based on data but inequality tests are based on identity (or vice-versa). I can't think of a single situation in which this is useful. From msoulier at digitaltorque.ca Tue Jun 21 22:25:35 2005 From: msoulier at digitaltorque.ca (Michael P. Soulier) Date: Tue, 21 Jun 2005 22:25:35 -0400 Subject: oddness in shelve module Message-ID: <20050622022535.GU18460@rabbit.digitaltorque.ca> I'm trying to add objects to a shelve db object via hash assignment, but I'm getting an odd exception. Traceback (most recent call last): File "RemGui.py", line 117, in onMonitorButton self.startMonitoring() File "RemGui.py", line 163, in startMonitoring self.monitor() File "RemGui.py", line 181, in monitor self.db.store_sample(dbentry) File "C:\Documents and Settings\Michael Soulier\My Documents\projects\rem\pysr c\RemDBShelve.py", line 38, in store_sample self.db[sample.timestamp] = sample TypeError: object does not support item assignment The object itself is quite simple. I provide it below. If anyone can shed light on this, I'd appreciate it. Thanks, Mike class RemDBEntry(object): """This class represents one entry in the database. It stores a merging of all of the document types supplied by the server.""" def __init__(self, timestamp): self.timestamp = timestamp self.procs = [] self.partitions = [] self.free = None self.uptime = None def merge(self, doc): """This method takes a RemDoc object and merges it with the current object.""" if doc.type == 'uptime': self.uptime = doc.scalar elif doc.type == 'ps': self.procs = doc.children elif doc.type == 'siloShow': self.partitions = doc.children elif doc.type == 'siloShowMaxFree': self.free = doc.scalar else: raise AssertionError, "Unknown document type: %s" % doc.type -- Michael P. Soulier http://www.digitaltorque.ca http://opag.ca python -c 'import this' Jabber: msoulier at digitaltorque.ca -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tim.leslie at gmail.com Mon Jun 13 05:54:47 2005 From: tim.leslie at gmail.com (Tim Leslie) Date: Mon, 13 Jun 2005 19:54:47 +1000 Subject: why python on debian without the module profile? In-Reply-To: <42ad4f7f.654d1ce2.0691.ffffe36b@mx.gmail.com> References: <42ad4f7f.654d1ce2.0691.ffffe36b@mx.gmail.com> Message-ID: My understanding is that there are licence issues (someone please correct me if I'm wrong). The moral of the story is that there's a seperate (non-free) package for the profiler: http://packages.debian.org/testing/python/python2.4-profiler HTH Tim On 6/13/05, kyo guan wrote: > Hi All: > > Python 2.4.1 (#2, May 5 2005, 11:32:06) > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import hotshot,hotshot.stats > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/hotshot/stats.py", line 3, in ? > import profile > ImportError: No module named profile > >>> > > > > Python 2.3.5 (#2, May 4 2005, 08:51:39) > [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import hotshot,hotshot.stats > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/hotshot/stats.py", line 3, in ? > import profile > ImportError: No module named profile > >>> > > -- > http://mail.python.org/mailman/listinfo/python-list > From flupke at nonexistingdomain.com Thu Jun 2 18:33:57 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 02 Jun 2005 22:33:57 GMT Subject: (OT) lincense protection generator In-Reply-To: References: Message-ID: Jarek Zgoda wrote: > flupke napisa?(a): > >> I'm thinking of a function that will generate such a code and put it >> in a file. Then when the program starts it checks this file and checks >> the code in there with a code that it generates at that time again >> based for instance on the current directory and other components >> unique to that computer. It could be a long string (but what info?) >> and then take a hash from it and store the hash value. > > > Better, generate sha1 sum of general machine configuration (i.e. what > "set" command returns) and store it on random internet node. You can be > sure nobody would get it. > > Anyway, it's bad idea. Restrict program usage in license) or any other > contract), but don't do such a mess to people who pay your bills. > Well as i said it's more to see when they tampered with the config or the program. It's not a commercial application but it's for inhouse use in the hospital where i work. These people are, to put it mildly, not the most computer savant people around. It could be handy to avoid me searching for a solution to a problem that arises because of messing with the setup rather than a bug in the code. Thanks, Benedict From peter at engcorp.com Sat Jun 11 09:22:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Jun 2005 09:22:13 -0400 Subject: Is pyton for me? In-Reply-To: <87is0lpl5h.fsf@debian.kirkjobsluder.is-a-geek.net> References: <867jh16d3s.fsf@guru.mired.org> <87is0lpl5h.fsf@debian.kirkjobsluder.is-a-geek.net> Message-ID: <3aidnaJMIv08ezffRVn-iA@powergate.ca> Kirk Job Sluder wrote: > I agree with this approach. For me, there has to be a certain level of > complexity before I reach for python as a tool. For me as well. In my case, the key question is "is this bash script going to be longer than two lines?". If it would be, the Python approach will be done faster and will be more maintainable, since I often don't look at those scripts again for months and would tend to forget any bash syntax that I've learned in the meantime. :-) -Peter From rphillips at engineer.co.summit.oh.us Fri Jun 24 08:49:07 2005 From: rphillips at engineer.co.summit.oh.us (paron) Date: 24 Jun 2005 05:49:07 -0700 Subject: Looking For Geodetic Python Software References: <447po2-iqt.ln1@eskimo.tundraware.com> Message-ID: <1119617347.660102.242140@g14g2000cwa.googlegroups.com> Howard Butler http://hobu.biz/ has some nice Python wrappers for gdal and Frank Warmerdam's other tools. I have to say, though, that geodesy is inherently complicated. Python makes it easy to program, but not easy to understand. http://maps.hobu.net:7080/RPC2 is an XMLRPC service that he exposes that will transform various coordinate systems: take a look at http://hobu.biz/index_html/projection_service/blogentry_view to see what I mean. Ron Phillips Tim Daneliuk wrote: > Is anyone aware of freely available Python modules that can do any of > the following tasks: > > 1) Given the latitude/longitude of two locations, compute the distance > between them. "Distance" in this case would be either the straight-line > flying distance, or the actual over-ground distance that accounts for > the earth's curvature. > > 2) Given n latitude/longitude coordinates, compute the > "geocenter". That is, return the lat/long of the location that > is most "central" to all n initial coordinates. > > 3) Given n lat/long coordinates, compute a Kruskal-type spanning > tree. > > 4) Given n lat/long coordinates, compute an optimal (shortest or longest) > visitation path that reaches each node exactly once. Better still would > be something that had "pluggable" heuristic engines so we could try > different approaches like greedy, shortest-path, hill climbing, and > so forth. It would be even nicer if one could also simulate different > routing schemes (Monte Carlo?). > > In effect, I'm looking for something that mates traditional graph traversal > heuristics with operations research tools working on a geodetic > coordinate system. This is *waaaaay* outside my field of expertise so > I'm hoping someone has taken the pain of it for dummies like me ;) > > TIA, > -- > ---------------------------------------------------------------------------- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ From lkirsh at cs.ubc.ca Fri Jun 24 07:18:12 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Fri, 24 Jun 2005 04:18:12 -0700 Subject: printing indented html code In-Reply-To: <4660fe30050624041674da1b7b@mail.gmail.com> References: <4660fe30050624041674da1b7b@mail.gmail.com> Message-ID: <42BBEBF4.30406@cs.ubc.ca> Looks good. I'll give it a try. Konstantin Veretennicov wrote: > On 6/24/05, Lowell Kirsh wrote: > >>Is there a module or library anyone knows of that will print html code >>indented? > > > Depends on whether you have to deal with xhtml, valid html or just > any, possibly invalid, "pseudo-html" that abounds on the net. > > Here's an example of (too) simple html processing using standard > HTMLParser module: > > from HTMLParser import HTMLParser > > class Indenter(HTMLParser): > > def __init__(self, out): > HTMLParser.__init__(self) > self.out = out > self.indent_level = 0 > > def write_line(self, text): > print >> self.out, '\t' * self.indent_level + text > > def handle_starttag(self, tag, attrs): > self.write_line( > '<%s %s>' % (tag, ' '.join('%s=%s' % (k, v) for k, v in attrs)) > ) > self.indent_level += 1 > > def handle_endtag(self, tag): > self.indent_level -= 1 > self.write_line('' % tag) > > handle_data = write_line > > # handle everything else... > # http://docs.python.org/lib/module-HTMLParser.html > > if __name__ == '__main__': > import sys > i = Indenter(sys.stdout) > i.feed('foobarbody') > i.close() > > - kv From gh at ghaering.de Sat Jun 18 09:58:27 2005 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 18 Jun 2005 15:58:27 +0200 Subject: pysqlite - Checking the existance of a table In-Reply-To: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> References: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> Message-ID: <42B42883.5000807@ghaering.de> rh0dium wrote: > Hi all, > > I am starting to play with pysqlite, and would like to know if there is > a function to determine if a table exists or not. You can try to access the table in a try-catch block, something like: cur.execute("select * from tablename where 1=2") and check if it fails. Or you can query the sqlite_master table (don't know any specification off-hand, but it contains the schema information). Instead of doing a select on sqlite_master, you can use "pragma table_info", which returns information for each column in the table, and, apparently, an empty list if the table does not exist: >>> cur.execute("pragma table_info(foo)") >>> print cur.fetchall() [(0, u'bar', u'integer', 0, None, 0)] >>> cur.execute("pragma table_info(foo_does_not_exist)") >>> print cur.fetchall() [] HTH, -- Gerhard From grante at visi.com Thu Jun 9 17:13:51 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 09 Jun 2005 21:13:51 -0000 Subject: A question about time References: <42a8ac25@griseus.its.uu.se> Message-ID: <11ahc8fntjhiad5@corp.supernews.com> On 2005-06-09, Jan Danielsson wrote: > In C, I would do this: > > server.invalidUntil = time(NULL) + 5*60; // five minute delay In Python, I would do this: server.invalidUntil = time.time() + 5*60 # five minute delay > ..and the check: > > if(time(NULL) > server.invalidUtil) > { > // use server > } if time() > server.invalidUntil: # user server > So the whole thing very simple... Yup. -- Grant Edwards grante Yow! Look!! Karl Malden! at visi.com From peter at engcorp.com Thu Jun 30 23:56:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 30 Jun 2005 23:56:04 -0400 Subject: OOP help needed incorporating existing modules in class In-Reply-To: <300620051907570695%user@unknown.invalid> References: <300620051907570695%user@unknown.invalid> Message-ID: <1s2dncYL-fpuI1nfRVn-2w@powergate.ca> Koncept wrote: > I want to incorporate the datetime and other modules into my class. I > am new to Python and would really appreciate some help doing this. > > class FooBar: > def getDate(self): > return > > ^^^ how do I do something like this? Um.... have you read the tutorial yet? It sounds like you might not even be aware of the purpose of the "import" statement. Either that or I'm misunderstanding the question, because the above code works fine in principal if you've imported the datetime module first. (The above code is probably incorrect in the specifics of the call to ctime(), but reading the documentation for "datetime" after you've learnt the basics of Python should solve that.) -Peter From saint.infidel at gmail.com Fri Jun 24 10:51:52 2005 From: saint.infidel at gmail.com (infidel) Date: 24 Jun 2005 07:51:52 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <1119618780.475725.22580@o13g2000cwo.googlegroups.com> Message-ID: <1119624712.444787.310300@o13g2000cwo.googlegroups.com> > def class Colour: > def __init__(self, blue=0, green=0, red=0): > # pseudo-Python code borrowing concept "with" from Pascal > with self: > blue = blue > green = green > red = red > > And now you can see why Python doesn't support this idiom. Maybe it would make more sense if it was done a la Visual Basic with self: .blue = blue .green = green .red = red requiring a dot to be typed removes the ambiguity and gives the IDEs a chance to Intellisense-ify your coding. From agriff at tin.it Mon Jun 13 01:55:24 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 13 Jun 2005 05:55:24 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> On Sun, 12 Jun 2005 20:22:28 -0400, Roy Smith wrote: >How far down do you have to go? What makes bytes of memory, data busses, >and CPUs the right level of abstraction? They're things that can be IMO genuinely accept as "obvious". Even "counting" is not the lowest level in mathematic... there is the mathematic philosohy direction. From "counting" you can go "up" in the construction direction (rationals, reals, functions, continuity and the whole analysis area) building on the counting concept or you can go "down" asking yourself what it does really mean counting, what do you mean with a "proof", what really is a "set". However the "counting" is naturally considered obvious for our minds and you can build the whole life without the need to look at lower levels and without getting bitten too badly for that simplification. Also lower than memory and data bus there is of course more stuff (in our universe looks like there is *always* more stuff no mattere where you look :-) ), but I would say it's more about electronic than computer science. >Why shouldn't first-year CS students study "how a computer works" at the >level of individual logic gates? After all, if you don't know how gates >work, things like address bus decoders, ALUs, register files, and the like >are all just magic (which you claim there is no room for). It's magic if I'm curious but you can't answer my questions. It's magic if I've to memorize because I'm not *allowed* to understand. It's not magic if I can (and naturally do) just ignore it because I can accept it. It's not magic if I don't have questions because it's for me "obvious" enough. >> Also concrete->abstract shows a clear path; starting >> in the middle and looking both up (to higher >> abstractions) and down (to the implementation >> details) is IMO much more confusing. > >At some point, you need to draw a line in the sand (so to speak) and say, >"I understand everything down to *here* and can do cool stuff with that >knowledge. Below that, I'm willing to take on faith". I suspect you would >agree that's true, even if we don't agree just where the line should be >drawn. You seem to feel that the level of abstraction exposed by a >language like C is the right level. I'm not convinced you need to go that >far down. I'm certainly not convinced you need to start there. I think that if you don't understand memory, addresses and allocation and deallocation, or (roughly) how an hard disk works and what's the difference between hard disks and RAM then you're going to be a horrible programmer. There's no way you will remember what is O(n), what O(1) and what is O(log(n)) among containers unless you roughly understand how it works. If those are magic formulas you'll just forget them and you'll end up writing code that is thousands times slower than necessary. If you don't understand *why* "C" needs malloc then you'll forget about allocating objects. Andrea From irmen.NOSPAM at xs4all.nl Sat Jun 4 14:03:36 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 04 Jun 2005 20:03:36 +0200 Subject: [ANN] Snakelets 1.41 and Frog 1.6 In-Reply-To: <5a446e4e.0506040034.60fa5950@posting.google.com> References: <42a0a7f4$0$29628$e4fe514c@news.xs4all.nl> <5a446e4e.0506040034.60fa5950@posting.google.com> Message-ID: <42a1ecfb$0$29627$e4fe514c@news.xs4all.nl> thinfrog wrote: > It's very interesting, i'm glad to try. > > And it can access data by MYSQL/SQL or other database software? "it" meaning Snakelets, I assume. (because Frog, the blog server, doesn't use any database for storage) Snakelets does not contain ANY database connector. You can therefore use any database you like, but you have to write your own database access connector. Which can be a bit troublesome because you have to make it work in a multi-user multi-thread environment. I plan to add a few examples to Snakelets that show how a database connection could be made (for mysql and/or sqlite perhaps, to name a few) but for now, no example code is available, sorry. --Irmen From newsgroups at jhrothjr.com Tue Jun 7 17:32:58 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 7 Jun 2005 15:32:58 -0600 Subject: Trouble Encoding References: <1118135690.961381.207490@o13g2000cwo.googlegroups.com> Message-ID: <11ac4kiih8srf4c@news.supernews.com> wrote in message news:1118135690.961381.207490 at o13g2000cwo.googlegroups.com... > I'm using feedparser to parse the following: > >
Adv: Termite Inspections! Jenny Moyer welcomes > you to her HomeFinderResource.com TM A "MUST See &hellip;
> > I'm receiveing the following error when i try to print the feedparser > parsing of the above text: > > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in > position 86: ordinal not in range(256) > > Why is this happening and where does the problem lie? Several different things are going on here. First, when you try to print a unicode string using str() or a similar function, Python is going to use the default encoding to render it. The default encoding is usually ASCII-7. Why it's trying to use Latin-1 in this case is somewhat of a mystery. The quote in front of the word MUST is a "smart quote", that is a curly quote, and it is not a valid character in either ASCII or Latin-1. Use Windows-1252 explicitly, and it should render properly. Alternatively use UTF-8, as one of the other posters suggested. Then it's up to whatever software you use to actually put the ink on the paper to render it properly, but that's a different issue. John Roth > > thanks > From donn at drizzle.com Tue Jun 14 02:37:13 2005 From: donn at drizzle.com (Donn Cave) Date: Tue, 14 Jun 2005 06:37:13 -0000 Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: <1118731031.410376@yasure> Quoth Ron Adam : | ... The current for-else | is IMHO is reversed to how the else is used in an if statement. Is that all? As a matter of opinion, this one is fairly simply an arbitrary choice to assign a positive sense to completion of the loop predicate. For search loops, for example, it's clearly a failure - the loop predicate is there to put a bound on the search, and to reach that bound is to fail. Whatever, I don't care if you find this compelling. My point is that rather than a case of intuition driven by subconscious forces beyond our control, the choice between two ways to take the boolean sense of a loop control is really based on some logical premises, which we can reconsider if it's productive to do so. I prefer this to fantasies about changing the language, your mileage may vary. Donn Cave, donn at drizzle.com From dirgesh at gmail.com Sun Jun 5 02:13:50 2005 From: dirgesh at gmail.com (GujuBoy) Date: 4 Jun 2005 23:13:50 -0700 Subject: error in usin list with boost Message-ID: <1117952030.199906.326130@g47g2000cwa.googlegroups.com> i have created a "cpp" file which has the followin code and when i try to compile it..it does not know what "list" is..it says its undefined..i also tried using #include but no differe...can someone please help. thanks static list retrieval_as_list(SplitText &self, int position, int retrieveLength) { list result; int *characters = new int[retrieveLength]; int lenRet = self.RetrieveUTF32(position, characters, retrieveLength); for (int i=0;i References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: Gregory Pi?ero wrote: > I always figured a problem with using MySQL was distribution. Would > you have to tell your users to install MySQL and then to leave the > service running? I've never found an easy way to embed MySQL into a > python app, and even if you could, would you then have to pay for it? There are more reasons than that not to use MySQL... See e.g. http://sql-info.de/mysql/gotchas.html It seems a lot of the most badly missed features are appearing in MySQL 5.0, but as features are added, I suppose the claimed advantages in performance and simplicity withers away, and these features can hardly be considered very mature yet. (One should also note that MySQL manuals have often claimed that features it lacked were useless, or even dangerous, until MySQL AB decided to implement them themselves... :) Also, the GPL/Commercial licence is not a good thing for commercial apps, particularly since this licence applies even to client libs. Recent PostgreSQL versions are stable, fast, and have native Windows versions. From tom at dtsam.com Mon Jun 6 17:04:47 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Mon, 6 Jun 2005 16:04:47 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: "James Tanis" wrote in message news:mailman.43.1118073133.10512.python-list at python.org... > Previously, on Jun 6, Thomas Bartkus said: > > # "bruno modulix" wrote in message > # news:42a3fc70$0$30762$626a14ce at news.free.fr... > # > You mean the "wimp gui builder + db -> ui pipeline" model ? If yes, C > # > doesn't have it, C++ doesn't have it (in fact most languages doesn't > # > have it) - and .... > # > # > .... the fact is that C and C++ are usually considered as much > # > more "serious and professionnal" than VB and the likes. > # > # Yes but there is another fact that must be considered. > # Systems like VB (and the likes) are much more *productive* . > # > # The secret of that particular success has nothing to do with the language > # and everything to do with the integrated GUI / IDE available to that > # particular (VB) language. > > That's pretty arguable. C/C++ has no shortage of integrated GUI/IDE > available especially if your willing to fork out the same kind of books > that you would need to for VB. > > # > # Anything that reduces the overhead involved in producing a > # consistent/attractive/idiot proof user interface makes a far more > # productive environment. > # > # Thomas Bartkus > > My 2 cents, I'm much more productive with Python and QT Builder as I > am with VB and those aren't nearly as intergrated as VB's GUI/IDE. A > language's productivity, I believe, rests on how high or low-level the > language and its libraries are. Not just that though, productivity is > also very much affected by the breadth of the libraries available. When scripting, Windows or Linux, I also am much more productive with Python. When automating a process for another human being, I am much more productive with a RAD tool like VB. The effort involved in creating the user front end simply overwhelms all the considerable efficiencies of Python. When I code wxPython, I find I want to use VB to create/model my user interface. Once I prototype my Windows (Frames!) using VB, I can then xlate this to wxPython code. What I couldn't do without the VB IDE was visualize and experiment with the impact of various layouts *before* I lay down code. It is simply too onerous to experiment by code manipulation and too easy to swish around visually with a mouse. When I use a GUI designer like wxGlade, I still find it awkward enough to merit prototyping with the VB IDE and then mimic the windows I create with wxGlade. > Sure, GUI RAD solutions increase development in a very real way, but you > can find an offering for just about every language out there these days. Yes. But the tools available for Python are still primitive compared to RAD tools like Delphi/Visual Studio. I still don't know enough wxPython to understand what the barriers are to creating a RAD visual design and construction tool similar to the Visual Studio environment. My ravings here are simply the result of a suspicion - - The suspicion is that the only barrier is the Python (and Linux!) communities grossly underestimating the value of such an undertaking. Thomas Bartkus From usenet.20.evilspam at spamgourmet.com Sun Jun 12 19:19:18 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 23:19:18 GMT Subject: How to get/set class attributes in Python In-Reply-To: <87is0jfe60.fsf@hector.domek> References: <42ac6b5b$0$27173$626a14ce@news.free.fr> <87k6kzgznf.fsf@hector.domek> <87is0jfe60.fsf@hector.domek> Message-ID: Peter Dembinski wrote: > Chris Spencer writes: > > >>Peter Dembinski wrote: >> >>Of course, in that Python is dynamically typed as opposed to the >>static typing of Java or C++. Please excuse my previous mis-wording :) > > > Mis-wording? I previously said Python was "untyped", when it's more accurate to say "dynamically typed". From steve at REMOVETHIScyber.com.au Mon Jun 13 04:25:31 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 18:25:31 +1000 Subject: new string function suggestion References: <7fare.27429$J12.6708@newssvr14.news.prodigy.com> Message-ID: On Mon, 13 Jun 2005 07:05:39 +0000, Andy wrote: > What do people think of this? > > 'prefixed string'.lchop('prefix') == 'ed string' > 'string with suffix'.rchop('suffix') == 'string with ' > 'prefix and suffix.chop('prefix', 'suffix') == ' and ' > > The names are analogous to strip, rstrip, and lstrip. If chop is analogous to strip, then they shouldn't raise exceptions if the strings do not start with the prefix or suffix. > I get tired of writing stuff like: > > if path.startswith('html/'): > path = path[len('html/'):] > elif s.startswith('text/'): > path = path[len('text/'):] > > It just gets tedious, and there is duplication. Instead I could just write: Any time you are writing the same piece of code over and over again, you should refactor it out as a function in your module, or even in a special "utility functions" module: def lchop(s, prefix): if s.startswith(prefix): return s[len(prefix):] raise ValueError("Substring doesn't begin with prefix.") # or just return s if you prefer and then call them whenever you need them. -- Steven. From austin at maxtronic.com.tw Mon Jun 13 00:17:53 2005 From: austin at maxtronic.com.tw (Austin) Date: Mon, 13 Jun 2005 12:17:53 +0800 Subject: os.system References: Message-ID: >> My code is " os.system("NET SEND computer hihi") " >> i use this funtion on Windows server 2003. >> it's ok. >> >> But the same code running on Windows XP SP2, it shows the command window >> twice. >> How do i remove the command window? > > Hi, > > You can remove the command window which comes > from python if you use ".pyw" as extension. > This is not an answer why the system method > opens a second window, but maybe it helps, too. > > Thomas > Hi, but my program is complied from py2exe. All extension is 'pyd'. Hm... is there any way to do? From bogus@does.not.exist.com Wed Jun 29 16:10:01 2005 From: bogus@does.not.exist.com () Date: Wed, 29 Jun 2005 20:10:01 -0000 Subject: No subject Message-ID: #! rnews 1192 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!195.241.76.212.MISMATCH!transit1.news.tiscali.nl!tiscali!transit0.news.tiscali.nl!tudelft.nl!txtfeed1.tudelft.nl!feeder2.cambrium.nl!feed.tweaknews.nl!feeder.enertel.nl!nntpfeed-01.ops.asmr-01.energis-idc.net!in.100proofnews.com!in.100proofnews.com!newsread.com!news-xfer.newsread.com!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 18 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Wed, 29 Jun 2005 19:43:22 GMT Xref: news.xs4all.nl comp.lang.python:384026 "Adriaan Renting" writes: [snip] > This doesn't mean I would recommend VB for everything. For large > projects C++ or java can both be far superior, depending on needs and > available tools and libraries. I realy like Python for small projects on > Linux. Both VB and Python are easier to learn as the more powerful > languages, the price is that they lack features that make it easier to > manage large and complex projects. > [snip] What is a large project, and what is Python missing that C++ and Java have for such tasks? -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From tim.golden at viacom-outdoor.co.uk Tue Jun 14 06:30:56 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Jun 2005 11:30:56 +0100 Subject: Where is Word? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8CF@vogbs009.gb.vo.local> [Guy Lateur] | Sent: 14 June 2005 11:02 | To: python-list at python.org | Subject: Re: Where is Word? | | | Unfortunately, I need to open/edit a (temporary) text file | with Word, and | those are opened by default with UltraEdit (or Notepad or..). | Thanks for the | tip, though. | | Anything else? Do I need to read the registry? | | g OK, a slightly more intelligent idea in place of my previous one. You can use win32api.ShellExecute (from the pywin32 extensions) which is like a beefed-up os.startfile. In particular, it allows you to pass parameters to the command. So... import win32api win32api.ShellExecute ( 0, # hwnd "open", # action; could be "print" etc. "winword.exe", # application "c:/temp/temp.txt", #params ".", # working directory 1 # show/don't show ) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From roy at panix.com Sat Jun 18 21:26:48 2005 From: roy at panix.com (Roy Smith) Date: Sat, 18 Jun 2005 21:26:48 -0400 Subject: Is there something similar to ?: operator (C/C++) in Python? References: Message-ID: Bo Peng wrote: > I need to pass a bunch of parameters conditionally. In C/C++, I can do > > func(cond1?a:b,cond2?c:d,.....) Python does not have a ternary operator analogous to C's :?. There are some ugly hacks you can play with the logical operators to emulate :?, but in my opinion, the cure is worse than the disease. > In Python, I am using temporary variables like > > if cond1: > para1 = a > else: > para1 = b > > # .... > # a bunch of such if/else > > func(para1, para2,...) Yeah, that's how I would do it. How many of these things do you have? From thomas.weholt at gmail.com Wed Jun 1 09:17:13 2005 From: thomas.weholt at gmail.com (Thomas W) Date: 1 Jun 2005 06:17:13 -0700 Subject: Monitoring a USB-drive / Card-reader using python? Message-ID: <1117631833.428067.305950@o13g2000cwo.googlegroups.com> I want to monitor a given USB-device, like a Memory Card-reader, and when a memory card is inserted I want to move the data on the card to a different location on the filesystem ( or do something else with the files). Does anybody know how to do this ( on Linux and/or windows ) or if it's even do-able ? Thomas From jefflpolo at gmail.com Thu Jun 2 15:33:19 2005 From: jefflpolo at gmail.com (JPolo) Date: 2 Jun 2005 12:33:19 -0700 Subject: JOB: Google.com Engineering Message-ID: <1117740799.312719.246130@g14g2000cwa.googlegroups.com> Senior Software Engineer/Unix System & Network Administrator, Google.com (SRE) Positions available in: Mt.View, CA; Kirkland, WA; New York, NY; Zurich, Switzerland; and Dublin, Ireland We're looking for top-notch thrill seeking, python gurus to join the Google.com team. Google.com engineers are in the thick of everything involved with keeping Google running, from code-level troubleshooting of traffic anomalies to maintenance of our most cutting edge services; from monitoring and alerts to building new automation infrastructure. We are aggressively building this elite team of high level engineers in this mission critical environment. All team members must have strong analytical and troubleshooting skills, fluency in coding, good communication skills, and most of all enthusiasm for tackling the complex problems of scale which are uniquely Google. Google.com engineers tackle challenging, novel situations every day, and work with just about every other engineering and operations team in the process. Candidates should have: ? Strong programming/scripting skills in any of the following: Python, C, C++, Java, Perl. ? Senior Level experience with Unix system administration. ? Strong understanding of networking For immediate consideration, please send a text (ASCII) or HTML version of your resume to: jpolo at google.com. Important: The subject field of your email must include Senior Software Engineer/Unix System & Network Administrator, Google.com (SRE) From skromta at gmail.com Sat Jun 18 06:02:07 2005 From: skromta at gmail.com (Kalle Anke) Date: Sat, 18 Jun 2005 12:02:07 +0200 Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> <1119088178.088667.227150@g44g2000cwa.googlegroups.com> Message-ID: <0001HW.BED9BDBF0048D1A8F0488550@news.individual.de> On Sat, 18 Jun 2005 11:49:38 +0200, Xah Lee wrote (in article <1119088178.088667.227150 at g44g2000cwa.googlegroups.com>): > the problem is that the page essentially says nothing. Nothing that is > relevant to programing, and such nothingness occupies a significant > portion of the python doc. (at least a quarter) It is like reading a > manual to operate a machinery, and in every other paragraph it offers > the (technically-fantastically-correct) explanations of what bolt or > material were used where. I'm new to Python and the information that's in the docs (at least that example) was what I was looking for. I read this as the referece manual, not a cookbook or a tutorial which clearly requires another style of documentation. From oliver.andrich at gmail.com Mon Jun 20 16:33:32 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Mon, 20 Jun 2005 22:33:32 +0200 Subject: Python and encodings drives me crazy Message-ID: <6f7b52d050620133348c12dd6@mail.gmail.com> Hi everybody, I have to write a little skript, that reads some nasty xml formated files. "Nasty xml formated" means, we have a xml like syntax, no dtd, use html entities without declaration and so on. A task as I like it. My task looks like that... 1. read the data from the file. 2. get rid of the html entities 3. parse the stuff to extract the content of two tags. 4. create a new string from the extracted content 5. write it to a cp850 or even better macroman encoded file Well, step 1 is easy and obvious. Step is solved for me by ===== code ===== from htmlentitydefs import entitydefs html2text = [] for k,v in entitydefs.items(): if v[0] != "&": html2text.append(["&"+k+";" , v]) else: html2text.append(["&"+k+";", ""]) def remove_html_entities(data): for html, char in html2text: data = apply(string.replace, [data, html, char]) return data ===== code ===== Step 3 + 4 also work fine so far. But step 5 drives me completely crazy, cause I get a lot of nice exception from the codecs module. Hopefully someone can help me with that. If my code for processing the file looks like that: def process_file(file_name): data = codecs.open(file_name, "r", "latin1").read() data = remove_html_entities(data) dom = parseString(data) print data I get Traceback (most recent call last): File "ag2blvd.py", line 46, in ? process_file(file_name) File "ag2blvd.py", line 33, in process_file data = remove_html_entities(data) File "ag2blvd.py", line 39, in remove_html_entities data = apply(string.replace, [data, html, char]) File "/usr/lib/python2.4/string.py", line 519, in replace return s.replace(old, new, maxsplit) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position 0: ordinal not in range(128) I am pretty sure that I have iso-latin-1 files, but after running through my code everything looks pretty broken. If I remove the call to remove_html_entities I get Traceback (most recent call last): File "ag2blvd.py", line 46, in ? process_file(file_name) File "ag2blvd.py", line 35, in process_file print data UnicodeEncodeError: 'ascii' codec can't encode character u'\x96' in position 2482: ordinal not in range(128) And this continues, when I try to write to a file in macroman encoding. As I am pretty sure, that I am doing something completely wrong and I also haven't found a trace in the fantastic cookbook, I like to ask for help here. :) I am also pretty sure, that I do something wrong as writing a unicode string with german umlauts to a macroman file opened via the codecs module works fine. Hopefully someone can help me. :) Best regards, Oliver -- Oliver Andrich --- http://fitheach.de/ From sjmachin at lexicon.net Wed Jun 29 22:08:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 30 Jun 2005 12:08:56 +1000 Subject: aligning text with space-normalized text In-Reply-To: References: Message-ID: <42C35438.2010207@lexicon.net> Steven Bethard wrote: [snip] > And it appears to work: [snip] > But it seems somewhat inelegant. Can anyone see an easier/cleaner/more > Pythonic way[1] of writing this code? > > Thanks in advance, > > STeVe > > [1] Yes, I'm aware that these are subjective terms. I'm looking for > subjectively "better" solutions. ;) Perhaps you should define "work" before you worry about """subjectively "better" solutions""". If "work" is meant to detect *all* possibilities of 'chunks' not having been derived from 'text' in the described manner, then it doesn't work -- all information about the positions of the whitespace is thrown away by your code. For example, text = 'foo bar', chunks = ['foobar'] From simonwittber at gmail.com Thu Jun 9 03:49:44 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 9 Jun 2005 00:49:44 -0700 Subject: my golf game needs gui In-Reply-To: References: Message-ID: <1118303384.434950.160870@g44g2000cwa.googlegroups.com> For simple 2D graphics, your best option is pygame. http://pygame.org/ If you need assistance, join the pygame mailing list, where you should find someone to help you out. From thomas at thomas-lotze.de Sat Jun 11 19:48:42 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sun, 12 Jun 2005 01:48:42 +0200 Subject: Controlling a generator the pythonic way References: Message-ID: Peter Hansen wrote: > Fair enough, but who cares what the generator code thinks? It's what the > programmer has to deal with that matters, and an object is going to have a > cleaner interface than a generator-plus-mutable-object. That's right, and among the choices discussed, the object is the one I do prefer. I just don't feel really satisfied... >> It does, however, require a lot of attribute access, which does cost >> some cycles. > > Hmm... "premature optimization" is all I have to say about that. But when is the right time to optimize? There's a point when the thing runs, does the right thing and - by the token of "make it run, make it right, make it fast" - might get optimized. And if there are places in a PDF library that might justly be optimized, the tokenizer is certainly one of them as it gets called really often. Still, I'm going to focus on cleaner code and, first and foremost, a clean API if it comes to a decision between these goals and optimization - at least as long as I'm talking about pure Python code. -- Thomas From jjinux at gmail.com Sat Jun 4 16:54:27 2005 From: jjinux at gmail.com (Shannon -jj Behrens) Date: Sat, 4 Jun 2005 13:54:27 -0700 Subject: [Baypiggies] potluck for google meeting? In-Reply-To: <42728.10.5.1.104.1117911783.squirrel@mail.csquaredtech.com> References: <20050604183452.GA29448@panix.com> <42728.10.5.1.104.1117911783.squirrel@mail.csquaredtech.com> Message-ID: I'm a huge fan of potlucks, but I'm not entirely sure I'd trust the cooking of a bunch of engineers ;) -jj On 6/4/05, donna at csquaredtech.com wrote: > I know that typically you all meet somewhere for dinner beforehand.. or > afterhand.. but I'd like to propose we try a potluck at the meeting.. if > google will allow it. > > I'm volunteering to coordinate the potluck for the july google meeting.. > we can just see how it goes.. From darkpaladin79 at hotmail.com Mon Jun 6 20:01:23 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 20:01:23 -0400 Subject: help with sending mail in Program In-Reply-To: Message-ID: Could someone send me a good tutorial for sending mail then? The one I found is not what I'm looking for. Also please dont send me the stmp definition cause i've looked at that enough. thanks, -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From kosh at aesaeion.com Sat Jun 25 03:00:50 2005 From: kosh at aesaeion.com (William Heymann) Date: Sat, 25 Jun 2005 01:00:50 -0600 Subject: Favorite non-python language trick? In-Reply-To: <8-2dnaaqFsZ07yHfRVn-iA@comcast.com> References: <8-2dnaaqFsZ07yHfRVn-iA@comcast.com> Message-ID: <200506250100.50823.kosh@aesaeion.com> On Friday 24 June 2005 02:53 pm, D H wrote: > Again, you are splitting hairs. His point still stands that it is not > possible to do method overloading in python (unless you use decorator > hacks). It may be possible to add this feature when type declarations > and type checking are added to a future version of python. Decorators are actually a syntax hack remember. Everything you can do in a decorator you could do with python before since they work via nested scopes. It is easy to write wrapper methods and I use them for many purposes but not for type checking. Wrapper methods are very useful to take out common checking code. The checking of conditions does not really belong in the caller (the caller could forget), it does not really belong in the called function since that is not that functions purpose but putting it in a wrapper and having it wrap the called function sure gives a nice seperation and makes life simpler. From pinard at iro.umontreal.ca Fri Jun 3 10:13:56 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Fri, 3 Jun 2005 10:13:56 -0400 Subject: compile python in release... In-Reply-To: <42A05F87.4050302@laposte.net> References: <42A05F87.4050302@laposte.net> Message-ID: <20050603141356.GA11548@phenix.progiciels-bpi.ca> [mg] > My problem is here : all the source files are compiled with the -g > flag which might be the debug flag. (On the other hand, the option > -DNDEBUG is defined : it's normal !) Then my question is : Is exist > a flag/option to run the shell script named 'configure' allowing to > remove the '-g' flag located in the generated makefile ? There is no relation between `-g' and `-DNDEBUG', they control different things. What people usually do is leaving `-g' for compilation and linking, but stripping the resulting binary or library at installation time. See the documentation of `strip' and the `-s' option of `install'. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From irmen.NOSPAM at xs4all.nl Wed Jun 22 03:12:47 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 22 Jun 2005 09:12:47 +0200 Subject: getting an object name In-Reply-To: References: Message-ID: <42b90f6f$0$32363$e4fe514c@news.xs4all.nl> David Bear wrote: > Let's say I have a list called, alist. If I pass alist to a function, > how can I get the name of it? > > alist = range(10) > > def afunction(list): > listName = list.__name__ (fails for a list object) > You don't, see the other reply. You didn't say why you think you need this for, but I suspect that you can solve your case by using a dict in one way or another: { "somename": [1,2,3,4,5] } --Irmen From user at unknown.invalid Fri Jun 3 01:15:00 2005 From: user at unknown.invalid (Koncept) Date: Fri, 03 Jun 2005 01:15:00 -0400 Subject: REQ: Small Perl to Python conversion needed References: <020620052018031433%user@unknown.invalid> <0KSdnUXWwbOxOALfRVn-og@comcast.com> Message-ID: <030620050115000538%user@unknown.invalid> In article <0KSdnUXWwbOxOALfRVn-og at comcast.com>, Steven Bethard wrote: > I don't speak Perl, but based on your output, I'd probably do something > like: > > py> lines = ["1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5"] > py> counts = {} > py> for items in lines: > ... for item in items.split(','): > ... counts[item] = counts.get(item, 0) + 1 > ... > py> for key in sorted(counts, key=counts.__getitem__, reverse=True): > ... print 'Key: %s Frequency: %s' % (key, '*'*counts[key]) > ... > Key: 5 Frequency: ***** > Key: 4 Frequency: **** > Key: 3 Frequency: *** > Key: 2 Frequency: ** > Key: 1 Frequency: * > > I'm probably missing a few subtleties, but hopefully this will get you > started. > > STeVe Thanks Steven. This helped a lot. Exactly what I was looking for -- Koncept << "The snake that cannot shed its skin perishes. So do the spirits who are prevented from changing their opinions; they cease to be a spirit." -Nietzsche From uche.ogbuji at gmail.com Fri Jun 10 13:50:43 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 10 Jun 2005 10:50:43 -0700 Subject: Getting a DOM element's children by type (STUPID) In-Reply-To: References: Message-ID: <1118425843.519222.306330@f14g2000cwb.googlegroups.com> """ If i get myself a DOM tree using xml.dom.minidom (or full-fat xml.dom, i don't mind) """ Don't do that. Stick to minidom. The "full" xml.dom from PyXML is ancient and slow. Of course, there are other, better libraries available now, too. """ is there an easy way to ask a element for its child elements of a particular type? By 'type' i mean 'having a certain tag'. """ You can use list comprehensions[1]. You could use XPath, if you're willing to use a library that supports XPath. In Amara[2], this task is trivial. To get all the images in an XHTML div, you'd simply do: for img in div.img: process_img(img) You access names directly as objects according to their element type name. [1] see, e.g., http://www.xml.com/pub/a/2003/01/08/py-xml.html [2] see http://www.xml.com/pub/a/2005/01/19/amara.html -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Use CSS to display XML, part 2 - http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html XML Output with 4Suite & Amara - http://www.xml.com/pub/a/2005/04/20/py-xml.htmlUse XSLT to prepare XML for import into OpenOffice Calc - http://www.ibm.com/developerworks/xml/library/x-oocalc/ Schema standardization for top-down semantic transparency - http://www-128.ibm.com/developerworks/xml/library/x-think31.html From tjreedy at udel.edu Thu Jun 9 12:21:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Jun 2005 12:21:08 -0400 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> Message-ID: "wooks" wrote in message news:1118318436.192627.320820 at g49g2000cwa.googlegroups.com... > http://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem&item=5206943952 Are you the seller flogging his item? We really don't need every auction listing for Python books copied to this forum. Please don't repeat. TJR From martin.witte at gmail.com Wed Jun 22 08:59:19 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 22 Jun 2005 05:59:19 -0700 Subject: Reading registry export files In-Reply-To: <42b92291$0$1334$5fc3050@dreader2.news.tiscali.nl> References: <42b92291$0$1334$5fc3050@dreader2.news.tiscali.nl> Message-ID: <1119445159.379493.279470@f14g2000cwb.googlegroups.com> It works fine for me on NT. I think it has nothing to do with Python but with the way the file is created - what windows version are you on? Also note the possibility the '/' - I prefer a noatation like below to avoid ambiguity. Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> f = open(r"d:\test.reg") py> r = f.read() py> print r REGEDIT4 I would do it like this however, then join all lists from various .reg files: py> f = open(r'd:\test.reg') py> r = f.readlines() py> print r ['REGEDIT4\n', '\n', '[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Ole]\n', '"Enabl eDCOM"="Y"\n', '"DefaultLaunchPermission"=hex:01,00,04,80,64,00,00,00,80,00,00,0 0,00,00,00,00,\\\n', ' 14,00,00,00,02,00,50,00,03,00,00,00,00,00,18,00,01,00,00 ,00,01,01,00,00,00,\\\n', ' 00,00,05,12,00,00,00,00,00,00,00,00,00,18,00,01,00, 00,00,01,01,00,00,00,00,\\\n', ' 00,05,04,00,00,00,00,00,00,00,00,00,18,00,01,0 0,00,00,01,02,00,00,00,00,00,\\\n', ' 05,20,00,00,00,20,02,00,00,01,05,00,00,00 ,00,00,05,15,00,00,00,a0,5f,84,1f,\\\n', ' 5e,2e,6b,49,ce,12,03,03,f4,01,00,00, 01,05,00,00,00,00,00,05,15,00,00,00,a0,\\\n', ' 5f,84,1f,5e,2e,6b,49,ce,12,03,0 3,f4,01,00,00\n', '\n'] >>> [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Ole] "EnableDCOM"="Y" "DefaultLaunchPermission"=hex:01,00,04,80,64,00,00,00,80,00,00,00,00,00,00,00, 14,00,00,00,02,00,50,00,03,00,00,00,00,00,18,00,01,00,00,00,01,01,00,00,00,\ 00,00,05,12,00,00,00,00,00,00,00,00,00,18,00,01,00,00,00,01,01,00,00,00,00,\ 00,05,04,00,00,00,00,00,00,00,00,00,18,00,01,00,00,00,01,02,00,00,00,00,00,\ 05,20,00,00,00,20,02,00,00,01,05,00,00,00,00,00,05,15,00,00,00,a0,5f,84,1f,\ 5e,2e,6b,49,ce,12,03,03,f4,01,00,00,01,05,00,00,00,00,00,05,15,00,00,00,a0,\ 5f,84,1f,5e,2e,6b,49,ce,12,03,03,f4,01,00,00 From hesterumpe at tiscali.dk Tue Jun 21 09:15:08 2005 From: hesterumpe at tiscali.dk (Bue Krogh Vedel-Larsen) Date: Tue, 21 Jun 2005 13:15:08 GMT Subject: Embedding Python - Deleting a class instance References: Message-ID: Jeff Epler wrote in news:mailman.698.1119357219.10512.python-list at python.org: > > Unless there's a cycle and GC gets involved, all there is to deleting > *anything* in Python is correctly managing the refcount. On the other > hand, you can never free an object while it is still reachable. Some > local name "x" may never spontaneously lose the thing it refers to. Thanks for the replies. I've solved it, it was a kind of cycle: When creating the instance it registered itself with my code, and was supposed to unregister itself when deleted, but since I kept a copy of the object in the program it never got unregistered, and thus never deleted... From sjmaster at gmail.com Fri Jun 17 14:12:05 2005 From: sjmaster at gmail.com (Steve M) Date: 17 Jun 2005 11:12:05 -0700 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? In-Reply-To: References: Message-ID: <1119031925.025149.81510@g14g2000cwa.googlegroups.com> This link seems to be about Closures in Python, but I am not feeling sharp enough at the moment to evaluate the correctness of the discussion. http://en.wikipedia.org/wiki/Python_programming_language#Closures As others have said, you might get more useful responses if you can elaborate upon what exactly you worry are shortcomings of Python compared to Perl. From sjmachin at lexicon.net Wed Jun 29 19:00:50 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 30 Jun 2005 09:00:50 +1000 Subject: Boss wants me to program In-Reply-To: References: Message-ID: <42c32823@news.eftel.com> Thomas Bartkus wrote: > "phil" wrote in message > news:mailman.1070.1120060456.10512.python-list at python.org... > >>>About teaching in the exact sciences: I think we need a more hands-on >>>applied approach, to some extent this holds for the entire school >>>system. >> >>YES! As a geometry(& trig) teacher, I am going to have them build a >>shed, a kite, a sundial. I would love some doable ideas for hands >>on which would teach more principles without being major >>construction projects. >> > > Wow! How about a sextant? > Simple device really. And a great practical demonstration of trigonometry. > > It would be helpful of if your class was near the seashore. You would want a > clear shot at the horizon. > Thomas Bartkus > > 1. Even simpler device: an alidade is not a major construction project -- 2 nails and a piece of planed pine timber will do the job. If you want to venture into eat-your-heart-out territory, check out http://www.geometricum.com/Pic_of_Month_022004.htm Meanwhile, back in the real world, armed with an alidade and a home-made plane table, the kids can get some fresh air and make a map of the school grounds or a local park. And, as a different part of their education, you could suggest they research where English got all those interesting al- words from. 2. Lengths of twine with knots at strategic intervals e.g. (3,4,5), (5, 12, 13) will do for laying out rectangular fields (+ practical lesson -- which of these is less susceptible to error?); add a plumb-bob and you're building houses. 3. Another exercise involving fresh air, theory, and an understanding of the effect of errors of measurement: surveyor's traverse of the boundaries of the school grounds or the park, using a prismatic compass for the angles and their own paces [don't forget to ask them to research "mille passum"] or a pace-stick or a rod or a chain for the distance. Obligatory reference to newsgroup-related topic: possibly a Python script to do all those boring delta_x = paces * cos(delta_theta) etc calcs -- *after* they've done it manually of course. If they get a sign wrong and produce an endpoint that's in the next suburb, they might learn something and not go on to write aviation software that makes the aircraft flip upside down when it crosses the equator. Cheers, John From kent37 at tds.net Sat Jun 18 21:36:47 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Jun 2005 21:36:47 -0400 Subject: extreme newbie In-Reply-To: <1119068711.730364.215290@g47g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> Message-ID: <42b4cba7$1_1@newspeer2.tds.net> Harlin Seritt wrote: > Am I the only one who wonders this: If Python at runtime runs > very much like Java and has generally about the same speed (or faster), > then why in the world isn't Java becoming more archaic and being > steadily replaced by Python? I ask this not as a rhetorical question, > but --really-- how come developers are still stuck on Java when Python > seems to be a far better language? In context, Python is not a low > level compiled language like C/C++ is but an interpreted one just like > Java. Sigh. You're not the only one who wonders this. I have been trying to get my co-workers (in a mostly Java shop) interested in Python & Jython for 2-3 years with no success. What I see is that - most of them have little or no time to learn anything new that is not directly required to get their job done. - most of them have zero interest in evaluating new tools and trying to pick the best; they just use what is popular. "I don't have time to sharpen my saw, I'm too busy cutting down this tree!" Sigh. Kent From dstanek at dstanek.com Fri Jun 3 16:43:14 2005 From: dstanek at dstanek.com (David Stanek) Date: Fri, 3 Jun 2005 16:43:14 -0400 Subject: mod_python config problem In-Reply-To: <42A0AC81.2030901@galileo.edu> References: <42A0AC81.2030901@galileo.edu> Message-ID: <20050603204314.GF8003@goliath.ag.com> On Fri, Jun 03, 2005 at 01:16:17PM -0600, Manuel Pellecer wrote: > i want to use mod_python with Apache2 and i made a .htaccess in the > subdirectory where i have all my scripts: > > The .htacces goes like this: > > AddHandler mod_python .py > PythonHandler mptest > PythonDebug On Try adding the following line to your .htaccess file: PythonPath "sys.path + ['/your/path']" Where '/your/path' is the path in which mptest.py resides. -- David Stanek www.roninds.net GPG keyID #6272EDAF on http://pgp.mit.edu Key fingerprint = 8BAA 7E11 8856 E148 6833 655A 92E2 3E00 6272 EDAF -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From http Wed Jun 22 20:50:49 2005 From: http (Paul Rubin) Date: 22 Jun 2005 17:50:49 -0700 Subject: Avoiding deadlocks in concurrent programming References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: <7xslz93nh2.fsf@ruckus.brouhaha.com> "Eloff" writes: > >If the 100 threads are blocked waiting for the lock, they shouldn't > >get awakened until the lock is released. So this approach is > >reasonable if you can minimize the lock time for each transaction. > > Now that is interesting, because if 100 clients have to go through the > system in a second, the server clearly is capable of sending 100 > clients through in a second, and it doesn't matter if they all go > through "at once" or one at a time so long as nobody gets stuck waiting > for much longer than a few seconds. It would be very simple and > painless for me to send them all through one at a time. It is also > possible that certain objects are never accessed in the same action, > and those could have seperate locks as an optimization (this would > require carefull analysis of the different actions.) If you can design the transactions to not need anything like I/O waiting while a lock is being held, you may as well just use a single lock. Even more Pythonically, have a single thread "own" the structure and let other threads send requests through a Queue object and get replies through another Queue. Even on a multiprocessor system, CPython (because of the GIL) doesn't allow true parallel threads, so it's ok to serialize access to the structure that way. If you need/want real parallelism on a multiprocessor, see http://poshmodule.sf.net but then you start needing fancier synchronization. From peter at engcorp.com Wed Jun 15 11:39:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Jun 2005 11:39:11 -0400 Subject: FAQ: __str__ vs __repr__ In-Reply-To: <42b021ba$1@griseus.its.uu.se> References: <42b021ba$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Sorry, but I Just Don't Get It. I did search the 'net, I did read the > FAQ, but I'm too dumb to understand. > > As far as I can gather, __str__ is just a representation of the > object. [snip] > However, I don't understand what __repr__ should be. __repr__ shouldn't be anything, if you don't have an actual need for it. Neither should __str__. But if you have a need for something, and you're not sure which to use, think of it this way. If you are trying to output a representation of the object for use in debugging, such as in a debug log file, then use __repr__ and make it look like whatever you want, but preferably following the like all the builtin stuff. If you have a need for some representation of the data to use in your application for non-debugging purposes, such as perhaps to display data to a user, or to write data to an output file, then __str__ is a good candidate, and you can make it look like whatever you need. Just don't waste your time defining either a __repr__ or a __str__ just because those methods exist. That won't do anyone any good. -Peter From peter at engcorp.com Mon Jun 27 18:43:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Jun 2005 18:43:45 -0400 Subject: Non-blocking raw_input In-Reply-To: References: Message-ID: Jorge Louis de Castro wrote: > Could anyone tell me whether I can find a non blocking alternative to > raw_input that works on windows? Is there not a python way of achieving > this? Can I find it somewhere in the documentation? > Any help will be highly appreciated Depending on what your requirements are (since you don't really say), the functionality in the standard msvcrt module might help. From gsakkis at rutgers.edu Mon Jun 27 15:43:52 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 27 Jun 2005 12:43:52 -0700 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> Message-ID: <1119901432.218536.289030@g47g2000cwa.googlegroups.com> I'd love to see IPython replace the standard interpreter. Pychecker seems to be a strong candidate too. George From km at mrna.tn.nic.in Thu Jun 2 03:21:24 2005 From: km at mrna.tn.nic.in (km) Date: Thu, 2 Jun 2005 12:51:24 +0530 Subject: decimal numarray Message-ID: <20050602072124.GA28107@mrna.tn.nic.in> Hi all, is there any support for decimal type in numarray module ? regards, KM From http Mon Jun 6 15:14:09 2005 From: http (Paul Rubin) Date: 06 Jun 2005 12:14:09 -0700 Subject: random module question References: <1118079065.795771.248640@g49g2000cwa.googlegroups.com> Message-ID: <7x1x7f70xq.fsf@ruckus.brouhaha.com> "Raymond Hettinger" writes: > >> Can I rely on the random.py module to produce the same series of > >> numbers for future/past versions of Python, given the same seed? > > The answer is a qualified Yes. While the core generator (currently the > Mersenne Twister algorithm) is subject to change across versions, > whenever we've updated the generator, a backward compatable version is > offered (random.WichmannHill for example). Is Mersenne Twister currently available at all in Jython, for example? From Scott.Daniels at Acm.Org Thu Jun 23 20:51:54 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 23 Jun 2005 17:51:54 -0700 Subject: key - key pairs In-Reply-To: References: <200506231612.42324.hancock@anansispaceworks.com> Message-ID: <42bb51ba$1@nntp0.pdx.net> Ivan Van Laningham wrote: > Well, Florian said, "using two different keys, both unique"; if that is > true, then a single key maps to a single value & vice versa. Of course you are right. I got caught up in the problem I imagined (the pair being unique). > ... subclass dict and provide get/set that always insert the value > as a key. So dict["string"]=time also means dict[time]="string". > Or am I missing something? Yup, getting to min and max. I presume that will be key-dependent. --Scott David Daniels Scott.Daniels at Acm.Org From wookiz at hotmail.com Sun Jun 12 14:54:55 2005 From: wookiz at hotmail.com (wooks) Date: 12 Jun 2005 11:54:55 -0700 Subject: Python Developers Handbook - Mistake done and corrected. In-Reply-To: <83toa1p7t4tjq1cnq2g8370a3ul1s000gc@4ax.com> References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <1118399995.306455.161220@o13g2000cwo.googlegroups.com> <1118404332.349662.82650@g44g2000cwa.googlegroups.com> <1118565321.469787.81700@f14g2000cwb.googlegroups.com> <83toa1p7t4tjq1cnq2g8370a3ul1s000gc@4ax.com> Message-ID: <1118602495.576381.177470@g14g2000cwa.googlegroups.com> Arsenal v Spurs.... in baseball that translates to Red Sox v Yankees. From richardlewis at fastmail.co.uk Mon Jun 13 11:45:11 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Mon, 13 Jun 2005 16:45:11 +0100 Subject: Tkinter app structure Message-ID: <1118677511.26222.236253411@webmail.messagingengine.com> Hi there, I've just started my first project with Tkinter. I've already coded all the data handling classes and have a nice interface to work with (it happens to be a wrapper around the DOM of a large(ish) XML document but thats probably not important ;-) I'm new to Tkinter so I've started in a fairly random place: the main menu. I noticed that the event mechanism was based on callbacks so, in a flash of inspiration, I decided to create a new module called 'commands.py' which would contain all my callback methods (meaning I could use them for a toolbar as well, if I ever add one) and which acts as an intermediary between the Tkinter classes and my data hanlding classes. I've also created a 'main.py' module which holds the Tk object (called 'root'), the top level data object (called 'data') and the main UI object (called 'mwnd', an instance of a class inherited from Frame called 'MainWindow'). * The main.py module imports: from dataclasses import * from mainwindow import * from Tkinter import * * The mainwindow.py module imports: from Tkinter import * from commands import * * The commands.py modules imports: import main import tkMessageBox * And the dataclasses.py module imports only unrelated modules This set up should allow me to be able to access main.data and main.root from the commands.py module and the command callback functions (defined in commands.py) from mainwindow.py. main.py looks like this: ==================================== 1: from dataclasses import * 2: from mainwindow import * 3: from Tkinter import * 4: 5: data = Database() 6: 7: root = Tk() 8: mwnd = MainWindow(root) 9: root.mainloop() ==================================== However, when I execute it I get the following error: Traceback (most recent call last): File "./main.py", line 2, in ? from mainwindow import * File "mainwindow.py", line 2, in ? from commands import * File "commands.py", line 4, in ? import main File "main.py", line 8, in ? mwnd = MainWindow(root) NameError: name 'MainWindow' is not defined (where 'mainwindow.py' line 2 is "from commands import *", commands.py line 4 is "import main" and the name "MainWindow" is the name of the class defined in the mainwindow.py module) Whats going wrong? Is it a 'circular import'? Is there a better way that I could organise these modules? Cheers, Richard From erinhouston at gmail.com Thu Jun 23 11:52:54 2005 From: erinhouston at gmail.com (erinhouston at gmail.com) Date: 23 Jun 2005 08:52:54 -0700 Subject: User interfaces in console (dialog like) In-Reply-To: <2fdabf19.0506230445.249d063f@posting.google.com> References: <2fdabf19.0506230445.249d063f@posting.google.com> Message-ID: <1119541974.375570.318560@o13g2000cwo.googlegroups.com> Do you only need to work on windows? if so you could use http://newcenturycomputers.net/projects/wconio.html to build your own gui. We used this for our inhouse ldap admin script. From bkhl at stp.ling.uu.se Mon Jun 27 15:42:03 2005 From: bkhl at stp.ling.uu.se (=?utf-8?q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Mon, 27 Jun 2005 21:42:03 +0200 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: <87ekanpoxg.fsf@lucien.dreaming> Apple Grew writes: > I think since speed is not such an issue (I heard that python can make > faster GUI programs) you should use Visual Basic. It is very well > suited for Windows programming. There is the good thing that you can > visually create the GUI hence it is easier to create the GUI. Of course, you can do that with Python, too, with Glade (http://www.jamesh.id.au/software/libglade/) or Boa Constructor (http://boa-constructor.sourceforge.net/). (There might be more of them.) -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From gsakkis at rutgers.edu Mon Jun 13 06:48:39 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 13 Jun 2005 03:48:39 -0700 Subject: Java to Python - how to?? References: Message-ID: <1118659719.746482.55930@g43g2000cwa.googlegroups.com> ka_czor at poczta.onet.pl wrote: > Hello > > I just start programing in Python. > I've got a qestion, how translate the example code writen in Java to > Python?? > > > public class ConnectionManager { > > public ConnectionManager() { > super(); > } > public void sendAgent(Agent anAgent, WorkplaceAddress anAddress) { > > } > } > > bye class ConnectionManager(object): def __init__(self): super(ConnectionManager,self).__init__() def sendAgent(self, anAgent, anAddress): pass George From skip at pobox.com Wed Jun 1 23:19:09 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Jun 2005 22:19:09 -0500 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> Message-ID: <17054.31405.959697.452020@montanaro.dyndns.org> >> Apparently, most Python people feel productive enough without such a >> tool. Thomas> As did many with Fortran. Or Cobol. Are we now so productive Thomas> that there is no longer an unmet need for new/better software? Thomas> Do we stop here? Is Python a comfortable place for the Luddites Thomas> hang out. There's a difference. When I began programming, the only tools I had were the IBM card punch machine (basically a typewriter to enter my program) and the printout I got from the operator via my drop box (to show me compilation or run-time errors or my program's output on those rare instances when the PL/1 compiler didn't barf on my deck). In that situation, switching to a better set of tools (an ed(1)-like editor displayed on a CRT hooked up to our school's CDC timesharing system) was a no-brainer. It wasn't all that big a jump to switch to PR1ME computer's full-screen editor (probably something like vi, though it's been so long I can't remember anymore). After leaving school and moving on to VAX/VMS I looked around for another full-screen editor, farted around with EDT for a bit, but eventually stumbled upon Gosling's Emacs (on a DECUS tape I think), then GNU Emacs awhile later, then in the past three or four years settled on XEmacs. (I no longer remember how I edited BASIC code on the IMSAI 8080.) About 25 years have elapsed since my first exposure to Gosmacs. As you might imagine, I now have a fair amount of cortical area devoted to Emacs-fu. Based on my inability to help my son with his geometry homework this year I suspect most of the neurons that had previously been devoted to Euclidean geometry have been taken over by Emacs. Here's a quick summary of (some of) the functionality available to me from within Emacs that relates more-or-less directly to programming Python: * I do all my basic text editing and software development in Emacs, both local and remote files, but I also read mail there, including this mailing list. If I had more of a Usenet mindset I could read it in Emacs as well. * Python mode (thanks Tim & Barry) gives me access to inline help for attributes of many builtin objects, it does a good job of colorizing my code, supporting block moves and block comments and alerts me to runaway strings. * With pycomplete hooked up to Pymacs, it can do a pretty decent job completing partial expressions. * Using Emacs' builtin compilation facility I run pychecker over my code and step through the messages it emits. (I suppose with a little thought I could modify the compilation facility to define pychecker suppressions on-the-fly as I pick through pychecker's output.) * Emacs' tags facility lets me effortlessly jump to class and function definitions in my code. * I can get Python tracebacks when sitting at a gdb prompt using a little snippet of gdb's command language. If I wanted to I could use pdb to set breakpoints and execute my code under control of the pdb debugger but I generally just insert print statements. * I've also messed around a little with Bicycle Repair Man, a refactoring editor written in Python that integrates into Emacs via Pymacs. * I can also edit C and C++ code in the same editing/compilation/debugging environment when the need arises. * I can transparently use CVS or SCCS (and I suspect Clearcase and Subversion) from within Emacs, without being aware of the different packages' syntaxes. * If I need to work from home I can ssh into my desktop computer at work and using gnuclient, connect up to a running Emacs session that's got all the state I built up while at work. The learning curve for me to switch to something other than Emacs for software development at this point just isn't worth it. I'm sure the same would be true of long-term vi users or people accustomed to other full-featured editors. (Both Emacs and vi have the advantage that they are available on all major computing platforms.) Maybe I'm arguing for a tight integration between an IDE and an external editor and just don't realize it. I suppose it can be done, but I suspect it would be a major challenge. If not, it would have been done well already by other tools. Instead, my limited experience in this area suggests that most development environments just punt and use whatever feeble editing widget is available in the author's chosen widget set. They all seem feeble and slow to me, mostly because they aren't optimized for editing fixed width text. OTOH, maybe I'm arguing for a better integration of other tools/packages with Emacs and more complete documentation of what's already available. Should anyone be interested in helping out, a good place to tackle that would be in the python-mode project on SF . I do know from past experience with other tools that "providing basic Emacs keybindings" just doesn't cut it. Where are the rectangle and register commands? What about macros? (How would I live without macros?) At this point it's not just basic typing skills I would have to transfer to another tool to be able to switch and be as productive as I am with Emacs today. Sure, you can laugh at the kitchen sink that Emacs has become over the years, but it supports a lot of functionality. Think of it as an IDE framework & tool chest if you like. I'm sure I've only scratched the surface. In short, just because I still program in Emacs, don't assume I write my code on stone with hammer and chisel. Skip From fabioz at esss.com.br Wed Jun 8 12:45:49 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Wed, 08 Jun 2005 13:45:49 -0300 Subject: ANN: PyDev 0.9.4 released Message-ID: <42A720BD.5050701@esss.com.br> Hi All, PyDev - Python IDE (Python Development Enviroment for Eclipse) version 0.9.4 has just been released. Check the homepage (http://pydev.sourceforge.net/) for more details. Release Highlights: - New PYTHONPATH configuration (for the whole ambient), used for running your files, PyLint, code completion... - Integrated Scott Schleiser patches for the debugger (you won't see any 'implement me' anymore!). - Integrated Heikki Toivonen patch for PyLint using the project pythonpath. - Integrated Heikki Toivonen patch for indentation after '(', '[' and '{' (if the line ends with a comma). - Some StackOverflow errors were removed from code completion. - Keybindings added for Refactoring (powered by bycicle repair man) - check the FAQ. - Some bug-fixes as usual... Regards, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br PyDev - Python Development Enviroment for Eclipse pydev.sf.net pydev.blogspot.com From renato.ramonda at gmail.com Wed Jun 8 17:17:04 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Wed, 08 Jun 2005 23:17:04 +0200 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: Thomas Bartkus ha scritto: > The attractiveness of wxPython here is that it extends the platform > neutrality of Python to GUI interfaces. On a Windows platform, the work > looks like any other Windows program. On Gnome/Linux, the identical code > fits right into the Gnome desktop scheme. *Big* plus. Maybe I'm just nitpicking, but please! wxWidgets apps look ALMOST native on windows (combobox and similar widgets are emulated, and look really bad), and they sure _don't_ look like gnome apps on linux (gtk maybe, except for those custom widgets, but surely not gnome). Besides, wx generally catches the look, but almost never the 'feel'. wx is what you use if you really have no other choice, from my point of view... I'd honestly prefer to code a _good_ gui with gtk+glade and then bundle all the package together with py2exe and InnoSetup on windows. It will not look _native_, but it will look _GOOD_. Last time I looked wx did not have spacers (vbox, hbox and the like)... this leads to ugly non resizable vb-style guis, in my experience (just look at aMule... plain ugly). And that's not even starting to consider the version mess: try to install xCHM, Boa Constructor, aMule, VLC and some other app together... instant madness. > Yes. And I'm sorry to sound like I was complaining (but I was :-) > I'm here because MS is well along it's declining years and I've jumped off > the .NET bandwagon. New/wonderful things are no longer forthcoming from Then download gtk2.6 and glade for windows and then install pygtk and code away to your satisfaction! :-D -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From breamoreboy at aol.com Thu Jun 30 14:16:01 2005 From: breamoreboy at aol.com (Mark Lawrence) Date: 30 Jun 2005 11:16:01 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <1120155361.585377.48980@g43g2000cwa.googlegroups.com> muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. Many companies hire salespersons from Britain to > represent their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? > > Be blunt. We Americans need to know. Should we try to change the way we > speak? Are there certain words that sound particularly goofy? Please > help us with your advice on this awkward matter. I believe that all Americans should learn at least one British accent, so start with one in Welsh or Gaelic, once they've mastered this then try English. Kindest Regards. Mark Lawrence. p.s. this is why I love c.l.py. From pkarjala at paju.oulu.fi Wed Jun 8 05:25:10 2005 From: pkarjala at paju.oulu.fi (Pekka Karjalainen) Date: Wed, 8 Jun 2005 09:25:10 +0000 (UTC) Subject: Wxpython demo crashes References: Message-ID: In article , Greg Krohn wrote: > Do you have the unicode version of wxPython? > > http://prdownloads.sourceforge.net/wxpython/wxPython2.6-win32-unicode-2.6.1.0-py24.exe I think I do, because it shows the Unicode demo correctly, and I recall that I specifically chose that from the download section. I'm not at the right computer ATM, however, so I will have to check this later to be sure. -- Pekka Henrik Karjalainen -+- Oulu, Finland From steve at REMOVETHIScyber.com.au Mon Jun 13 19:17:43 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 14 Jun 2005 09:17:43 +1000 Subject: implicit variable declaration and access References: Message-ID: On Mon, 13 Jun 2005 12:18:31 -0400, Ali Razavi wrote: > Is there any reflective facility in python > that I can use to define a variable with a > name stored in another variable ? > like I have : > x = "myVarName" > > what can I do to declare a new variable with the name of the string > stored in x. And how can I access that implicitly later ? Any time you find yourself wanting to indirectly define variables like this, the chances are you would get better results (faster, less security risks, easier to maintain, easier to re-factor and optimise, more readable) if you change the algorithm. Instead of: x = "myVarName" create_real_variable(x, some_value) print myVarName why not do something like this: data = {"myVarName": some_value} print data["myVarName"] It is fast, clean, easy to read, easy to maintain, no security risks from using exec, and other Python programmers won't laugh at you behind your back -- Steven From spam.csubich+block at block.subich.spam.com Wed Jun 8 14:15:35 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 14:15:35 -0400 Subject: Fast text display? Message-ID: As a hobby project, I'm writing a MUD client -- this scratches an itch, and is also a good excuse to become familiar with the Python language. I have a conceptual handle on most of the implementation, but the biggest unknown for me is the seemingly trivial matter of text display. My first requirement is raw speed; none of what I'm doing is processing-intensive, so Python itself shouldn't be a problem here. But still, it's highly desirable to have very fast text updates (text inserted only at the end)-- any slower than 20ms/line stretches usability for fast-scrolling. EVERY other action on the text display, though, like scrolling backwards or text selection, can be orders of magnitude slower. The second requirement is that it support text coloration. The exact markup method isn't important, just so long as individual characters can be independently colored. The third requirement is cross-platform-osity; if you won't hold it against me I'll tell you that I'm developing under Cygwin in Win2k, but I'd really like it if the app could run under 'nix and mac-osx also. I'm pretty open to any graphical toolkit -- I have experience with none of them, so I have little in the way of prejudice. I'm not even sure where to start looking to see if a widget that does this has been premade -- the text widgets that I've seen so far have all had documentation geared more towards text editing than pure display. My closest look has been at PyGTK -- the GTK text widget is certainly complex enough to handle the markup, but it also seems a little bit feature-rich for my needs so I'm concerned about the overhead. In a worst-case scenario, I could try writing a widget-lite with SDL or possibly an OpenGL texture, but if a widget somewhere will already do this then it'd be needless work. To boot, I have no idea how to handle selection on such a homebrew-display if I'm using a proportional font, but that's a minor matter. So, the one-line summation of the novel above, does any one know of a gui toolkit/widget that will do (preferably extremely) fast text display in a cross-platform manner? PS: I couldn't get a prototype curses display working either, the scroll() function didn't work -- interactive log below: >>> import curses >>> x = curses.initscr() >>> print curses.has_il() True >>> x.idlok(1) >>> x.scroll(1) Traceback (most recent call last): File "", line 1, in ? _curses.error: scroll() returned ERR From gideondominick at gmail.com Sun Jun 12 04:52:31 2005 From: gideondominick at gmail.com (gideondominick at gmail.com) Date: 12 Jun 2005 01:52:31 -0700 Subject: Streaming Data Error in .read() (HTTP/ICY) Possible Bug? In-Reply-To: <1118563336.633159.38290@z14g2000cwz.googlegroups.com> References: <1118563336.633159.38290@z14g2000cwz.googlegroups.com> Message-ID: <1118566351.548279.11550@z14g2000cwz.googlegroups.com> I should purhaps mention that i am basically trying to translate this. nc ~= telnet #!/bin/sh nc sc1.liquidviewer.com 9012 < References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: <3gprogFbroi9U1@individual.net> Jordan Rastrick wrote: > But I explicitly provided a method to test equality. Actually, no, you didn't. You provided a method to define the meaning of the operator spelled '==' when applied to your object. That's the level of abstraction at which Python's __xxx__ methods work. They don't make any semantic assumptions. It's arguable that there should perhaps be some default assumptions made, but the Python developers seem to have done the Simplest Thing That Could Possibly Work, which isn't entirely unreasonable. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From bvande at po-box.mcgill.ca Tue Jun 28 01:53:55 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 28 Jun 2005 01:53:55 -0400 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <42C0E5F3.1080806@po-box.mcgill.ca> BORT said unto the world upon 27/06/2005 23:16: > Please forgive me if this is TOO newbie-ish. > > I am toying with the idea of teaching my ten year old a little about > programming. I started my search with something like "best FREE > programming language for kids." After MUCH clicking and high-level > scanning, I am looking at Python and Forth. Both have advocates that > say each is a great approach to learning computers. > [NOTE: This is not a troll. I'm geting ready to bark up a tree and I > prefer to avoid the wrong one. I am cross-posting.] > > Thanks Hi, I don't know a thing about Forth. I'm a hobbyist programmer with enough Python , and a "tourist's" level of a few other languages. So, no pro here :-) Qualifying done: A great thing about Python is the community. Roy Smith's stats comparing mailing list activity is useful data. I would also add that with the leading and closing bits of your post, it seems like perhaps you've seen an ugly flame or two in the past, no? Well, this is a very friendly place by 'net standards. One can get flamed in comp.lang.python, but you have to work at it. Hard. Another good community resource would be the Tutor mailing list -- there are a core group of posters who are very good at explaining things in a patient and novice-friendly way (and a number of intermediate folks like myself who sometimes ask, sometimes answer): . A useful (and free) book aimed at high school students is How to Think Like a Computer Scientist: Learning with Python . Though an adult when I came to Python, I found it useful while first starting and a bit intimidated by the prospect. It quickly got me to a place where reading "grown up" books like Learning Python was easy enough. Best, Brian vdB From steve at REMOVETHIScyber.com.au Mon Jun 13 10:44:11 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 14 Jun 2005 00:44:11 +1000 Subject: Controlling assignation References: Message-ID: On Mon, 13 Jun 2005 15:52:14 +0200, Xavier D?coret wrote: > I would like to know if there is for python's classes an equivalent of > the operator= that can be overidden. > > Let's say I have > >>> a=A() > and I want to write > >>> a=5 > and I want this to change some internal value of a instead of making a > point to a new object (an int 5) > > In other word, I would like to be able to use a=5 instead of a.set(5) > > Is that possible? I don't know, because I don't understand what you mean. What is A()? A class or a function? What is a.set()? What does it do? I'm going to make a wild guess as to what you want to do. You want something like Pascal records or C structs, right? py> a = MyCustomShapeClass() py> print a # calls a.__repr__ for a nice printable representation [top = 0, bottom = 1, left = 5, right = 20, kind = "rect"] py> a.kind = "oval" py> a.bottom = 100 py> print a [top = 0, bottom = 100, left = 5, right = 20, kind = "oval"] Is that the sort of thing you are looking for? -- Steven From agriff at tin.it Sat Jun 18 08:46:57 2005 From: agriff at tin.it (Andrea Griffini) Date: Sat, 18 Jun 2005 12:46:57 GMT Subject: exceptions considered harmful References: <1119027185.832640.291760@g43g2000cwa.googlegroups.com> Message-ID: On Fri, 17 Jun 2005 20:00:39 -0400, Roy Smith wrote: >This sounds like a very C++ view of the world. In Python, for example, >exceptions are much more light weight and perfectly routine. The problem with exceptions is coping with partial updatd state. Suppose you call a complex computation routine (say a boolean operation between winged edge data structures representing nurbs boundary of two solids) and that you get back a "ZeroDivision" exception... how good is the data structure now ? Either you have some way to be able to easily *guarantee* coherence or you're doomed. Allowing the user to continue without being sure about what is in memory is not going to be that helpful; the result could be that instead of losing last ten minuts you're going to waste the last month of user work (because the user will save the corrupted data and will notice problems only much later). If however you can restore the situation by a rollback or by loading a preimage, or you know that the operation works only *reading* two solids and creating a new one *and* you know that it's not a problem to drop a broken solid data structure then I think it's ok to swallow an exception. IMO either you know exactly what caused the exception and how the state got influenced, or you must have thick logical walls protecting you and allowing the problem to not propagate (for example an RDBMS rollback facility). With python it's sort of easy to get rollback for class instances if the code to protect doesn't plays strange tricks. Even C++ is powerful enough to allow that. With C++ care must be taken to just avoid memory leaks or other resource related problem while in python this is rarely a problem; but the real issue with exception is partial state update and in this python is not different. If you really have to check every place for possible exceptions then the exception machinery is not such a big win compared to return codes. IMO exceptions are nice when there are many raise and few try or except in the code; but then either you have state protection or swallowing an exception is taboo. Andrea From jjl at pobox.com Tue Jun 7 19:02:57 2005 From: jjl at pobox.com (John J. Lee) Date: 07 Jun 2005 23:02:57 +0000 Subject: Controlling source IP address within urllib2 References: <1117839742.510669.245420@g14g2000cwa.googlegroups.com> <87slzxlppj.fsf@pobox.com> <1118094808.095632.134210@z14g2000cwz.googlegroups.com> Message-ID: <87u0k9db32.fsf@pobox.com> "Dan" writes: > John, > Thanks for your input. I can kind of see the light in this, but I'm > having difficulty knowing where the "do_open" method comes from. Also, AbstractHTTPHandler > I'll need to follow redirects, so I assume then I would add a > HTTPRedirectHandler instance to the urllib2.build_opener. (?) Thanks No. It does that by default. John From anthra.norell at tiscalinet.ch Wed Jun 1 06:28:26 2005 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Wed, 1 Jun 2005 12:28:26 +0200 Subject: Encryption with Python? References: <1115324411.952821.150780@o13g2000cwo.googlegroups.com><001301c552db$dd19d3e0$0201a8c0@mcuf7> <6vh881d59bbecnc45fojknt0rohgt27crl@4ax.com><7xsm09br0n.fsf@ruckus.brouhaha.com> Message-ID: <04fc01c56694$a5bf5560$0201a8c0@mcuf7> Thank you all, James, Dennis, Christos, Paul, Isn't it remarkable that it takes "foolishness" to earn "a little respect". Anyway, even as I write this, my account balance stands unchanged at ... no, come to think of it, the account balance is definitely not a part of the problem. I will volunteer the information, though, that the credit card is a debit card and is good for up to the balance of the account. In addition, I did contemplate a brute force attack. I also contemplated my belief that it takes no more than a few lines of code to keep a teraflop machine busy for a few billion years. So I would not discourage decoding attempts but will state that the game as I understand it does not have any implicit rules. Regards Frederic (I am not the OP. The OP was Blake T. Garretson who never returned, but whose problem I still consider the standard by which I wish my idea to be judged. I never intended to dabble in commercial cryptography.) ----- Original Message ----- From: "Christos TZOTZIOY Georgiou" Newsgroups: comp.lang.python To: Sent: Friday, May 27, 2005 11:52 AM Subject: Re: Encryption with Python? > On 26 May 2005 14:45:28 -0700, rumours say that Paul Rubin > might have written: > > >> That's all. I see you took up the challenge and indirectly replied to > >> my last question, and in good spirit I say you earned a little respect > >> from me, at least for standing up to your words. Now I hope no-one > >> gives a try to your data (for your own sake :) > > >I don't think the challenge was really accepted. The algorithm > >changed between when you issued the challenge, and when the sensitive > >data went up. A good algorithm doesn't need to change depending on > >the data. I agree with the poster who said that the strength of > >either one of the algorithms is irrelevant, if the keyspace is just 32 > >bits. > > You are correct; the algorithm changed, and the OP admitted it himself > in the post with the encrypted credit card data. > > However, on a practical level: before posting, I did a quick comparison, > and the only effective change to OP's algorithm was a the addition of a > `random.shuffle(sequence)', which AFAIU has no practical consequences as > to whether his algorithm is unbreakable or not. > > I could say that "hey, you changed the algorithm, and that means your > previous declaration of unbreakability wasn't." but honestly I was > overwhelmed by the audacity (and foolishness, if these are truly his > credit card data) of Frederic. > > > > ObSF: DNA; The Restaurant At The End Of The Universe; Marvin the > paranoid android faces a gigantic black tank in the H2G2 HQ. > -- > TZOTZIOY, I speak England very best. > "Be strict when sending and tolerant when receiving." (from RFC1958) > I really should keep that in mind when talking with people, actually... > -- > http://mail.python.org/mailman/listinfo/python-list From philippe at philippecmartin.com Mon Jun 27 16:37:15 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 27 Jun 2005 20:37:15 GMT Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <87ekanpoxg.fsf@lucien.dreaming> Message-ID: <%rZve.335$Ox3.111@newssvr12.news.prodigy.com> As well as wxDesigner (great!) http://www.roebling.de/ Regards, Philippe Bj?rn Lindstr?m wrote: > Apple Grew writes: > >> I think since speed is not such an issue (I heard that python can make >> faster GUI programs) you should use Visual Basic. It is very well >> suited for Windows programming. There is the good thing that you can >> visually create the GUI hence it is easier to create the GUI. > > Of course, you can do that with Python, too, with Glade > (http://www.jamesh.id.au/software/libglade/) or Boa Constructor > (http://boa-constructor.sourceforge.net/). (There might be more of > them.) > From michele.simionato at gmail.com Wed Jun 1 05:09:15 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 1 Jun 2005 02:09:15 -0700 Subject: scripting browsers from Python In-Reply-To: <1117542360.436302.207150@o13g2000cwo.googlegroups.com> References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> <1117542360.436302.207150@o13g2000cwo.googlegroups.com> Message-ID: <1117616955.339925.90800@g43g2000cwa.googlegroups.com> This looks interesting, but I need an example here. What would be the command to open Konqueror to a given page and to post a form with given parameters? kde.org has tons a material, but I am getting lost and I don't find anything relevant to my simple problem. Michele Simionato From rkern at ucsd.edu Tue Jun 7 18:31:43 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 07 Jun 2005 15:31:43 -0700 Subject: Reading a CSV file into a list of dictionaries In-Reply-To: <42a61971$0$306$7a628cd7@news.club-internet.fr> References: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> <42a5fc08$0$302$7a628cd7@news.club-internet.fr> <42A603C7.8000702@lexicon.net> <42a61971$0$306$7a628cd7@news.club-internet.fr> Message-ID: Laurent RAHUEL wrote: > I thought you knew the number of cols and what you should expect in each. > Then it sounded pretty easy to build a list of dictionaries. If you don't > know what you're supposed to find in your file and how this file is > structured I guess you don't know what you are doing. That's not what the OP asked about. [RFQ:] """So each line is intended to be: key1,value1,key2,value2,key3,value3... and each line is to be variable in length (although it will have to be an even number of records so that each key has a value).""" The rows are not all of the same format. The OP *does* know the structure, and he (?) *does* know what he's doing. It's just not the structure usually used in CSV files. The csv module, of course, still reads these rows just fine; they just need to be processed a bit to get the correct dictionaries. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From skn at skn.com Mon Jun 20 09:09:31 2005 From: skn at skn.com (skn) Date: Mon, 20 Jun 2005 18:39:31 +0530 Subject: Generating .pyo from .py References: Message-ID: Thanks a lot !! It works fine !! regards, skn "Leif K-Brooks" wrote in message news:JV9se.235$S17.48187 at monger.newsread.com... > skn wrote: > > Does the python compiler provide an option to generate a .pyo(optimized byte > > code file) from a .py (source file)? > > > > For generating .pyc I know that I only have to pass the source file name as > > an argument to py_compile.py. > > py_compile.py checks __debug__ to decide whether to use optimize mode, > and the -O option to Python turns __debug__ off, so: > > python -O py_compile.py foo.py From grante at visi.com Wed Jun 1 22:21:59 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 02 Jun 2005 02:21:59 -0000 Subject: Pressing A Webpage Button References: <119sqr8dihknie3@corp.supernews.com> Message-ID: <119sra7cit79816@corp.supernews.com> On 2005-06-02, Grant Edwards wrote: > On 2005-06-01, Elliot Temple wrote: > >> How do I make Python press a button on a webpage? > > You just do whatever action is specified for the form > containing the button. > >> I looked at urllib, but I only see how to open a URL with >> that. > > Guess what happens when you push that button: the browser > opens a URL. > >> I searched google but no luck. >> >> For example, google has a button how would i make a script to press that button? > > Find the
containing the button, and look to see what the > URL is specified. For Google, it looks something like this: > > > > So, /search is the URL you open. > >> Just for fun, is there any way to do the equivalent of typing >> into a text field like the google search field before hitting >> the button? (I don't actually need to do this.) > > Sure. Just send back the field value in the normal manner > using a GET. > >> If someone could point me in the right direction it'd be appreciated. > > You need an introductory book on HTTP and HTML. > > If all you care about is a google query here's a python program > that prints the URL you need to open for a google query: > > #!/usr/bin/python > import urllib,sys,os > queryString="whatever you're searching for" > print 'http://www.google.com/search?'+urllib.urlencode({'q':queryString}) > > I presume you can figure out how to open the URL instead of > printing it? Ah, never mind. That doesn't work. Google somehow detects you're not sending the query from a browser and bonks you. -- Grant Edwards grante Yow! ... I'm IMAGINING a at sensuous GIRAFFE, CAVORTING visi.com in the BACK ROOMof a KOSHER DELI -- From peter at engcorp.com Sat Jun 11 16:19:42 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Jun 2005 16:19:42 -0400 Subject: What is different with Python ? In-Reply-To: <42AB456C.5000505@v.loewis.de> References: <42AB456C.5000505@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Philippe C. Martin wrote: >>- 5) I have developed for many years (>18) in many different environments, >>languages, and O/S's (including realtime kernels) . > > 2. You may not have dealt with a weakly-typed language before. If > that is the case, your feeling of "something being different" > most likely comes from that difference. If he's done realtime kernels, he's most definitely worked with a weakly typed language before (assembly most likely), but I think you meant to say (or should have said) "dynamically typed". -Peter From tim.golden at viacom-outdoor.co.uk Wed Jun 29 09:26:15 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 14:26:15 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB952@vogbs009.gb.vo.local> [Greg Miller] | Unfortunately I have a "fire" to put out with a patch to the existing | machine code, I'll get back to looking into the problem a | little later. | Thanks very much for you assistance with this! I really didn't look | into the GetFileVersionInfo, can I assume that is a cytypes function? No, it's a function in the win32api module of the pywin32 extensions. (Although I imagine you could wrap it via ctypes, if you felt that way inclined). Did my earlier post make it through to the newsgroup/Google? It came through on the mailing list. Just in case, here is the code again: import os, sys import win32api dll_filepath = os.path.join (sys.exec_prefix, "python24.dll") for k, v in win32api.GetFileVersionInfo (dll_filepath, "\\").items (): print k, "=>", v Good luck with the firefighting. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From invalidemail at aerojockey.com Sun Jun 12 05:25:52 2005 From: invalidemail at aerojockey.com (invalidemail at aerojockey.com) Date: 12 Jun 2005 02:25:52 -0700 Subject: case/switch statement? In-Reply-To: <5DGqe.3570$%j7.3324@newssvr11.news.prodigy.com> References: <5DGqe.3570$%j7.3324@newssvr11.news.prodigy.com> Message-ID: <1118568352.029540.140260@o13g2000cwo.googlegroups.com> Philippe C. Martin wrote: > Leif K-Brooks wrote: > > > Joe Stevenson wrote: > >> I skimmed through the docs for Python, and I did not find anything like > >> a case or switch statement. I assume there is one and that I just > >> missed it. Can someone please point me to the appropriate document, or > >> post an example? I don't relish the idea especially long if-else > >> statements. > > > > If you really want one, you could use > > . > > I _love_ Python! Well, if you loved that, here's something even more evil. This was Bengt Richter's original idea that Cliff Wells and I improved upon. First define some functions and classes: . _cache = {} . . class _BaseCaseException(Exception): . pass . . def switch(v): . if v not in _cache: . class _CaseException(_BaseCaseException): . pass . _cache[v] = _CaseException . raise _cache[v] . . def case(v): . if v not in _cache: . class _CaseException(_BaseCaseException): . pass . _cache[v] = _CaseException . return _cache[v] . . default = _BaseCaseException Then you can define a switch statement like this: . x = 2 . . try: switch(x) . . except case(1): . print "Case 1" . . except case(2): . print "Case 2" . . except case(3): . print "Case 3" . . except default: . print "Default" . . except NameError: . print "You can still catch regular exceptions like NameError" I-love-Python-too-but-this-isn't-why-ly yr's, -- CARL BANKS From please_post at nomail.edu Fri Jun 17 17:48:49 2005 From: please_post at nomail.edu (bill) Date: Fri, 17 Jun 2005 21:48:49 +0000 (UTC) Subject: ISO authoritative Python ref Message-ID: I have to learn Python in a hurry. I learn fastest by reading the specs/reference manual, or something like it (e.g. "C: A Reference Manual", by Harbison and Steel). Is there a Python book that fits this description? Many thanks in advance, bill P.S. I avoid tutorials like the plague, and I loathe the typical O'Reilly "learn-through-examples" approach. I know a lot of people like this style of learning, but I find it to be a waste of time. From sakesun at boonthavorn.com Sun Jun 26 22:51:01 2005 From: sakesun at boonthavorn.com (Sakesun Roykiattisak) Date: Mon, 27 Jun 2005 09:51:01 +0700 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: <11bs1bc5jotvg9c@news.supernews.com> References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: <42BF6995.1050606@boonthavorn.com> >What's being ignored is that type information is useful for other things >than compile type checking. The major case in point is the way IDEs >such as IntelliJ and Eclipse use type information to do refactoring, code >completion and eventually numerous other things. A Java programmer >using IntelliJ or Eclipse can eliminate the advantage that Python >used to have, and possibly even pull ahead. > > 1. Automatic refactoring never solve the readability issue. 2. I've never been lucky enough to have enough resource for those IDE. 3. Python solve my problem. From agriff at tin.it Sun Jun 5 19:34:39 2005 From: agriff at tin.it (Andrea Griffini) Date: Sun, 05 Jun 2005 23:34:39 GMT Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> <3g5tlqFaq4meU1@news.dfncis.de> <927s915p5t5l302u8vcbpmvrokdm64hb39@4ax.com> <3g6n98Faps91U1@news.dfncis.de> <3gggfbFcaca8U1@news.dfncis.de> Message-ID: On Sun, 05 Jun 2005 16:30:18 +0200, Matthias Buelow wrote: >Quite embarrassing, but it's a runtime bug and got nothing to do with >the language per se. And it certainly manifests itself after the >hey-days of Turbo Pascal (when Borland seems to have lost interest in >maintaining it.) The point is not the bug, of course, but how borland handled it. It appeared when the user community of borland pascal was well alive and kicking, but borland didn't even invest 5 seconds for the issue. The users had to fix the library themselves (possible because at that time with Borland Pascal you were getting the whole source code of the library; but note that it was a 100% genuine bug due to misprogramming, fixing it even on a dead product would have been the a nice move from borland). The user community went even further, as so many executables were written witn borland pascal that a special tool for binary patching executables was built (actually a few of them, as being unofficial it wasn't that simple to get to know that such a tool existed, so different people independently resorted to the same solution). Andrea From jtr at ofb.net Fri Jun 17 16:33:41 2005 From: jtr at ofb.net (John Reese) Date: Fri, 17 Jun 2005 20:33:41 +0000 (UTC) Subject: Why is there no instancemethod builtin? Message-ID: Why hello there ha ha. I have got in the habit of testing the types of variables with isinstance and the builtin type names instead of using the types module, as was the style back around Python 2.1. That is, rather than if type(x) == types.ListType: I now do: if isinstance(x, list): It is my understanding that this is what people do nowadays. One problem I have, though, is that not all type names are available as builtins. Just looking through the types declared in types, the following are builtins: bool, buffer, complex, dict, file, float, list, long, object, slice, str, tuple, type, unicode, xrange, NoneType, NotImplementedType And the following are not: dictproxy, ellipsis, frame, function, instancemethod, module, traceback, instancemethod, NoneType, NotImplementedType So for any in the latter batch, I have to import types after all. I assume the dividing line is whether the name is useful as a constructor. Still, I feel there's some inconsistencies in the usefulness of the new type system. Why do str and unicode derive from basestring, while list and tuple are independent types? list and tuple support most of the same operations... it seems like either they should also have an abstract base class or str and unicode shouldn't, because duck typing doesn't really require that. It also seems like types may be on the way out, because I don't see constants for set or frozenset. I'm not sure I have a question here, just pointing out what I see as some flaws in the new type system. From nothingcanfulfill at gmail.com Thu Jun 30 22:48:46 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 30 Jun 2005 19:48:46 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> <1120184800.499445.240250@f14g2000cwb.googlegroups.com> Message-ID: <1120186126.464935.273970@g44g2000cwa.googlegroups.com> Sorry, I realized that shortly after my post =X From dalke at dalkescientific.com Tue Jun 14 22:20:00 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 15 Jun 2005 02:20:00 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118734620.851366.291360@f14g2000cwb.googlegroups.com> Message-ID: Andrea Griffini wrote: > Wow... I always get surprises from physics. For example I > thought that no one could drop confutability requirement > for a theory in an experimental science... Some physicists (often mathematical physicists) propose alternate worlds because the math is interesting. There is a problem in physics in that we know (I was trained as a physicist hence the "we" :) quantum mechanics and gravity don't agree with each other. String theory is one attempt to reconcile the two. One problem is the math of string theory is hard enough that it's hard to make a good prediction. Another problem is the realm where QM and GR disagree requires such high energies that it's hard to test directly. > I was told that > in physics there are current theories for which there > is no hypotetical experiment that could prove them wrong... > (superstrings may be ? it was a name like that but I > don't really remember). If we had a machine that could reach Planck scale energies then I'm pretty sure there are tests. But we don't, by a long shot. Andrew Dalke From python at rcn.com Tue Jun 7 04:29:14 2005 From: python at rcn.com (Raymond Hettinger) Date: 7 Jun 2005 01:29:14 -0700 Subject: the python way? References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> <1118127739.226122.280830@g47g2000cwa.googlegroups.com> Message-ID: <1118132954.374498.252190@g43g2000cwa.googlegroups.com> Doh! The ifilter() and ifilterfalse() calls should be swapped in the previous post. From almad at include.cz Fri Jun 24 17:54:38 2005 From: almad at include.cz (Almad) Date: Fri, 24 Jun 2005 23:54:38 +0200 Subject: Handling more zodb databases with zeo Message-ID: Hello, sorry for bothering with same question again. However, month ago, I have tried to handle more zodb databases with zeo as described here: http://mail.python.org/pipermail/python-list/2005-May/279915.html Since then, I don't have had a time to play with it and now I tried again. However, even after reading http://www.zope.org/Wikis/ZODB/FrontPage/guide/index.html few times, I have no idea how to handle this (as anywhere I read, client only connect to port and do not select filestorage). Only possibility I see is to run more zeo instances, which is not neccessary as I have read. Thank You for help, -- Lukas "Almad" Linhart [:: http://www.almad.net/ ::] From tjreedy at udel.edu Wed Jun 1 20:47:36 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 20:47:36 -0400 Subject: PySol not working on WinXP, SP2 References: Message-ID: "Rocco Moretti" wrote in message news:d7lb52$r62$1 at news.doit.wisc.edu... > Are you sure you're using the Python version (2.3, 2.4 etc) that the > Pysol .pyw files were compiled for? As I understand it, that's what the > "magic number" is - a versioning number for the .pyc/.pyw files which > changes when the Python version is upped. > > If you had multiple versions of Python installed on your machine, > upgrading to SP2 might have muddled your file associations. 2.4 came out about the same time as SP2. If the .pyc files worked with 2.3, I am pretty sure they will not work with 2.4 since I am pretty sure the marshal format (used to make .pycs) was changed slightly for 2.4 after no change for a few releases. It will change again for 2.5. Python is intended to be distributed as readable source. .pycs are intended to be temporary caches, only kept around to avoid recompiling with every run, but certainly disposable with version changes. Terry J. Reedy From andreas at kostyrka.org Thu Jun 9 04:19:10 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 9 Jun 2005 10:19:10 +0200 Subject: multiple inheritance In-Reply-To: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> References: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> Message-ID: <20050609081910.GA30672@heaven.kostyrka.org> I'm sure it's documented somewhere, but here we go :) The correct usage is super(MyClass, self) The idea is that super allows for cooperative calls. It uses MyClass to locate what class "above" to call. This way you can something like that: class A(object): def bar(self): print "A" #getattr(super(A, self),"bar", lambda : None)() class B(object): def bar(self): print "B" #getattr(super(B, self),"bar", lambda : None)() class C(A,B): def bar(self): print "C" getattr(super(C, self),"bar", lambda : None)() print "-" * 20, "no super in A/B" C().bar() class A(object): def bar(self): print "A" getattr(super(A, self),"bar", lambda : None)() class B(object): def bar(self): print "B" getattr(super(B, self),"bar", lambda : None)() class C(A,B): def bar(self): print "C" getattr(super(C, self),"bar", lambda : None)() print "-" * 20, "protected getattr/super in A/B" C().bar() class base(object): def bar(self): print "base" class A(base): def bar(self): print "A" getattr(super(A, self), "bar", lambda : None)() class B(base): def bar(self): print "B" getattr(super(B, self), "bar", lambda : None)() class C(A,B): def bar(self): print "C" getattr(super(C, self), "bar", lambda : None)() print "-" * 20, "base class without super call" C().bar() This produces: -------------------- no super in A/B C A -------------------- protected getattr/super in A/B C A B -------------------- base class without super call C A B base Andreas On Thu, Jun 09, 2005 at 12:56:53AM -0700, newseater wrote: > i don't know how to call methods of super classes when using multiple > inheritance. I've looked on the net but with no result :( > > class a(object): > def foo(self): > print "a" > > class b(object): > def foo(self): > print "a" > > class c(a,b) > def foo(self): > super( ???? a).foo() > super( ???? b).foo() > > r = c() > r.foo() > > -- > http://mail.python.org/mailman/listinfo/python-list From eloff777 at yahoo.com Wed Jun 22 16:15:29 2005 From: eloff777 at yahoo.com (Eloff) Date: 22 Jun 2005 13:15:29 -0700 Subject: Avoiding deadlocks in concurrent programming Message-ID: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> This is not really Python specific, but I know Python programmers are among the best in the world. I have a fair understanding of the concepts involved, enough to realize that I would benefit from the experience of others :) I have a shared series of objects in memory that may be > 100MB. Often to perform a task for a client several of these objects must be used. Since many clients can be making requests at once (>100 per second during peak load) these objects must be protected with some method of thread syncronization (threading.Lock would do fine.) This is somewhat complicated by a backup thread which takes the data every 10 minutes and exports it all to a format that can be saved to disk. Clearly the backup thread must have exclusive access to all of these objects at once, and there must be no half-completed transactions underway. The easiest way from a design stand point is have a single lock and let clients have exclusive access to everything even although they only ever need access to a fraction of the data. This makes it easy for the backup thread, and it ensures that there's no trouble with deadlocks or with partially completed transactions. However imagine what would happen if there's 100 clients in 100 threads waiting for access to that lock. One could be almost finished with it, and then 100 threads could get switched in and out, all doing nothing since they're all waiting for the lock held by the one thread. So I think you would need multiple locks so clients only acquire what they need. This would let multiple threads access the data at once. But now I have to deal with deadlocks since clients will usually acquire a resource and then block acquiring another. It is very likely that one client locks A, another locks B, then the guy with B waits for A and the guy with A waits for B. Worse yet the backup thread will go around trying to lock everything and will no doubt deadlock everybody. How do you avoid this? I thought instead of blocking forever you could try non-blocking acquires in a loop with a timeout of a few seconds, if the timeout is reached, release any locks held and try again later, with the backup thread being the only one to use blocking acquires since it would never complete it's task otherwise. No doubt this is a common problem, how would you people deal with it? -Dan From cantabile.03 at wanadoo.fr Mon Jun 13 18:14:47 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Tue, 14 Jun 2005 00:14:47 +0200 Subject: Get drives and partitions list (Linux) In-Reply-To: References: <42accf62$0$11720$8fcfb975@news.wanadoo.fr> Message-ID: <42ae0557$0$11720$8fcfb975@news.wanadoo.fr> Hi, Jeff Great help : this works like a charm. I think I can customize it to read from sfdisk. Do you agree with Peter Hansen (post below) about fdisk ? Jeff Epler wrote: > Using /proc/partitions is probably preferable because any user can read > it, not just people who can be trusted with read access to drives, and > because the format of /proc/partitions is probably simpler and more > stable over time. > > That said, what you do is > import commands > fdisk_output = commands.getoutput("fdisk -l %s" % partition) > followed by some specialized code to parse the output of 'fdisk -l' > The following code is not at all tested, but might do the trick. > > # python parse_fdisk.py > /dev/hda4 blocks=1060290 bootable=False partition_id_string='Linux swap' partition_id=130 start=8451 end=8582 > /dev/hda1 blocks=15634048 bootable=True partition_id_string='HPFS/NTFS' partition_id=7 start=1 end=1947 > /dev/hda3 blocks=9213277 bootable=False partition_id_string='W95 FAT32 (LBA)' partition_id=12 start=8583 end=9729 > /dev/hda2 blocks=52235347 bootable=False partition_id_string='Linux' partition_id=131 start=1948 end=8450 > > # This source code is placed in the public domain > def parse_fdisk(fdisk_output): > result = {} > for line in fdisk_output.split("\n"): > if not line.startswith("/"): continue > parts = line.split() > > inf = {} > if parts[1] == "*": > inf['bootable'] = True > del parts[1] > else: > inf['bootable'] = False > > inf['start'] = int(parts[1]) > inf['end'] = int(parts[2]) > inf['blocks'] = int(parts[3].rstrip("+")) > inf['partition_id'] = int(parts[4], 16) > inf['partition_id_string'] = " ".join(parts[5:]) > > result[parts[0]] = inf > return result > > def main(): > import commands > fdisk_output = commands.getoutput("fdisk -l /dev/hda") > for disk, info in parse_fdisk(fdisk_output).items(): > print disk, " ".join(["%s=%r" % i for i in info.items()]) > > if __name__ == '__main__': main() From darkpaladin79 at hotmail.com Thu Jun 9 12:25:30 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 12:25:30 -0400 Subject: Start application & continue after app exits In-Reply-To: <42A86953.9070201@ulmcnett.com> Message-ID: >From: Paul McNett

>To: python-list at python.org >Subject: Re: Start application & continue after app exits >Date: Thu, 09 Jun 2005 09:07:47 -0700 > >Guy Lateur wrote: > > I was wondering if it would be possible to launch an application, block > > until the app exits, and do some cleanup afterwards. > > > Maybe an example will be clearer: I would like to make a temperary >(text) > > file, open it with MS Word for the user to edit/layout/print, and then > > delete the temp file after the user shuts down Word. Is this feasible? > >Something like: > >import os >import tempfile > >testString = "Life is but a dream." >fileName = tempfile.mktemp() >print fileName >open(fileName, "w").write(testString) >os.system("gedit %s" % fileName) >os.remove(fileName) > >--- >Note that I'm on Linux, and instead of launching Word I'm launching an >editor named "gedit". You could likely change that call to winword.exe, >but I haven't tested it on Windows. > >Also note that this method of creating tempfiles is technically unsafe, >as it is theoretically possible that another process would create a file >of the same name in the same directory and then try to use it, resulting >in a race condition between the two processes. This is practically >unlikely, however, and I'm a pragmatist. > > >-- >Paul McNett >http://paulmcnett.com -- Perhaps try the sys.exitfunc or atexit modules: exitfunc This value is not actually defined by the module, but can be set by the user (or by a program) to specify a clean-up action at program exit. When set, it should be a parameterless function. This function will be called when the interpreter exits. Only one function may be installed in this way; to allow multiple functions which will be called at termination, use the atexit module. Note: The exit function is not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called. Deprecated since release 2.4. Use atexit instead. heres the link Hope it helps, -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From newsgroups at jhrothjr.com Tue Jun 28 14:01:15 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 28 Jun 2005 12:01:15 -0600 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> Message-ID: <11c343ho6i6hv17@news.supernews.com> "Reinhold Birkenfeld" wrote in message news:3ian37Fkjle0U1 at individual.net... > Hello, > > at the moment python-dev is discussing including Jason Orendorff's path > module > into the standard library. > > Do you have any other good and valued Python modules that you would think > are > bug-free, mature (that includes a long release distance) and useful enough > to > be granted a place in the stdlib? > > For my part, ctypes seems like a suggestion to start with. > > Reinhold I'd go with path. While I'm not at all certain that it's "the" way to go, it'll at least break the conceptual logjam caused by simply providing wrappers around the C library functions. I'd definitely like to see ctypes. I can agree with the segfault issue, but I think that some design work would eliminate that. PyChecker, rather obviously. Likewise I'd like to see something that would do a decent job of coverage analysis. Neither of the modules out there at the moment is ready for prime time. I don't have enough experience with interactive mode to have an opinion on IPython. What I would like to see is a Python based shell that could compete with either ksh or Monad. John Roth From fredrik at pythonware.com Mon Jun 13 05:29:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Jun 2005 11:29:51 +0200 Subject: ElementTree Namespace Prefixes References: Message-ID: Chris Spencer wrote: > If an XML parser reads in and then writes out a document without having > altered it, then the new document should be the same as the original. says who? > With Elementtree this isn't so. Lundh apparently believes he knows > better than you and I on how our namespaces should be represented. do you even understand how XML namespaces work? From bdesth.quelquechose at free.quelquepart.fr Sun Jun 12 16:02:11 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 12 Jun 2005 22:02:11 +0200 Subject: How to test if an object IS another object? In-Reply-To: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> Message-ID: <42ac8f0e$0$17478$636a15ce@news.free.fr> dan.eloff at gmail.com a ?crit : > If two objects are of equal value you can compare them with ==. What I > want to do is find out if two objects are actually just references to > the same object, how can I do this in Python? The most obvious way (as usual ?): if obj1 is obj2: // your code here From donn at u.washington.edu Wed Jun 15 12:53:38 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 15 Jun 2005 09:53:38 -0700 Subject: FAQ: __str__ vs __repr__ References: <42b021ba$1@griseus.its.uu.se> Message-ID: In article <42b021ba$1 at griseus.its.uu.se>, Jan Danielsson wrote: > Sorry, but I Just Don't Get It. I did search the 'net, I did read the > FAQ, but I'm too dumb to understand. > > As far as I can gather, __str__ is just a representation of the > object. No, it is not. It is a conversion to string. The result has no trace of the original object, per se -- in principle, many different kinds of object could yield the same result. Suppose str(x) -> "42". Is x an int? a string? an XMLParseResult? AnswerToLifeTheUniverseAndEverything? You don't want to know, that's why you use str(). The "friendly" idea is vacuous if you look hard enough at it, and won't really help. > However, I don't understand what __repr__ should be. There's a phrase > in the documentation which makes it highly confusing for a beginner like > me: "If at all possible, this should look like a valid Python expression > that could be used to recreate an object with the same value (given an > appropriate environment).". What does that mean? It's kind of a bad idea that the Python world isn't ready to let go of yet. repr() is really the representation of the object. If you look at the result of repr(x), you should indeed see some clue to the original object. I guess this is what gives people the idea that str() is friendly, because as a rule users are not interested in the original object -- but there are exceptions, for example you may find the quotes useful around a string, depending on the situation. The object information also leads to the marshalling idea, but of course this isn't (and can't be) implemented for many objects so we can't expect this to work reliably with random objects. The price we pay for the notion is mostly in the "fix" for float repr, which now displays the float in all its imprecise glory and routinely confounds people who don't understand what that's about. Donn Cave, donn at u.washington.edu From tdwdotnet at gmail.com Mon Jun 27 18:52:11 2005 From: tdwdotnet at gmail.com (Tim Williams (gmail)) Date: Mon, 27 Jun 2005 23:52:11 +0100 Subject: Plain text email? In-Reply-To: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Message-ID: <9afea2ac0506271552336573ba@mail.gmail.com> On 27 Jun 2005 15:38:59 -0700, Inkiniteo wrote: > Hi guys. I have a script that sends the info by email, but i'd like to > avoid the convertion to HTML by the email client or Gmail, because it > ruins all the formatting i did (with tabs, mostly). Briefing, i wanna > be able to send SMTP mail and the receiver only get it in plain text. > Can you give a short example of how you are building the email ? From tim.golden at viacom-outdoor.co.uk Thu Jun 30 04:08:38 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Jun 2005 09:08:38 +0100 Subject: Open running processes Message-ID: <9A28C052FF32734DACB0A288A3533991EBB956@vogbs009.gb.vo.local> [DeRRudi] | Well i want a external app to maximize and minimize my app. | And later on i want the external one to send some data. Thought this | would be the most easy (and fast) way! | | Greetz | Rudi. I, at least, am reading this via the mailing list, not via Usenet nor via Google. This means that if you don't put any kind of context in what you post, I have to guess at what you're responding to. (All I see is the exact text you typed, nothing else). Assuming that you're answering my question: why use mmap and not just two events? I understand what your overall plan is, and it looks like you have a way to solve it. It just seemed that you might be able to achieve the same thing with two events: one for maximize and one for minimize. Why would this be better? Well, only because it seems to me slightly simpler than one event and a separate mmap mechanism. But I've never done what you're doing, so I may well be completely wrong. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From http Fri Jun 3 18:03:36 2005 From: http (Paul Rubin) Date: 03 Jun 2005 15:03:36 -0700 Subject: provide 3rd party lib or not... philosophical check References: Message-ID: <7x4qcfjdxj.fsf@ruckus.brouhaha.com> Maurice LING writes: > Just a philosophical check here. When a program is distributed, is it > more appropriate to provide as much of the required 3rd party > libraries, like SOAPpy, PLY etc etc, in the distribution itself or it > is the installer's onus to get that part done? If you absolutely need a 3rd party library, you have to make a careful decision whether to include it or not. Generally when in doubt, I'd say include it. But if you can, try to avoid needing external modules and instead use what comes in the Python distro so your code is otherwise self-contained. That is the Python philosophy of "using the batteries". If writing an extra ten lines of code or sacrificing an unimportant feature lets you do something with the Python library that you could do in 1 line with a 3rd party module, then write the ten lines or drop the feature, and get rid of the external dependency. If the module saves a big amount of work or does something important, then use it, but if the library's usefulness extends to many other developers, maybe that means you should start making the case to get the 3rd party module included in future Python releases, assuming the module's license permits it. From http Sat Jun 18 03:43:17 2005 From: http (Paul Rubin) Date: 18 Jun 2005 00:43:17 -0700 Subject: smtplib and TLS References: <1119034830.168876.26290@f14g2000cwb.googlegroups.com> <7xmzposrod.fsf@ruckus.brouhaha.com> <1119079978.179618.262380@o13g2000cwo.googlegroups.com> Message-ID: <7xmzpoyusq.fsf@ruckus.brouhaha.com> "Matthias Kluwe" writes: > Hmm. I tried > > server.sock.realsock.shutdown(2) > before server.quit() with the result of I don't think that's exactly what you want. You need to send a specific TLS message BEFORE shutting down the socket, to tell the other end that the TLS connection is ending. That tells the server that it shouldn't accept a TLS session resumption later. The close notify message is required because if you don't send it, an attacker could truncate one of your TLS messages by cutting your connection. Basically the socket library's SSL implementation is pretty crude. You might try http://trevp.net/tlslite for a pure-Python implementation that's also still missing stuff, but is getting there. From jzgoda at gazeta.usun.pl Tue Jun 28 17:37:10 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 28 Jun 2005 23:37:10 +0200 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <11c3cib5nv1d65a@corp.supernews.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c3c3uipbjcg58@corp.supernews.com> <11c3cib5nv1d65a@corp.supernews.com> Message-ID: Grant Edwards napisa?(a): >>>>To be blunt, I have no idea what this has to do with Python. >>>Monty Python was mostly Brits? >> >>Wasn't they all Brits? > > Nope. Terry Gilliam was from Minneapolis. Are you sure there are no Brits in Minneapolis? -- Jarek Zgoda http://jpa.berlios.de/ From exarkun at divmod.com Sat Jun 25 06:50:07 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 25 Jun 2005 06:50:07 -0400 Subject: Background thread In-Reply-To: Message-ID: <20050625105007.26278.141725025.divmod.quotient.295@ohm> On Sat, 25 Jun 2005 11:36:57 +0100, Jorge Louis De Castro wrote: >Hi, > >I'm new to python and I'm having trouble figuring out a way to have a thread running on the background that over rules the raw_input function. The example I'm working on is something like having a thread that prints "You're taking too long" every 10 seconds, while waiting for input from the user. >The problem is that I can only read (and in batch) the thread printout messages on the console after giving something to raw_input. >Is it not possible to have the thread print its stuff and then return to raw_input() ? Any code examples or pseudo-code or documentation directions will be highly appreciated. > >Thanks in advance > Here's one way you might do it without threads or raw_input() from twisted.protocols import basic, policies class AnnoyProtocol(basic.LineReceiver, policies.TimeoutMixin): from os import linesep as delimiter def connectionMade(self): self.setTimeout(10) def timeoutConnection(self): self.resetTimeout() self.sendLine("You're taking too long!") def lineReceived(self, line): self.resetTimeout() self.sendLine("Thank you for the line of input!") from twisted.internet import reactor, stdio stdio.StandardIO(AnnoyProtocol()) reactor.run() For fancy line editing support, twisted.conch.recvline might be of interest. Hope this helps, Jp From rrr at ronadam.com Wed Jun 15 19:11:09 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 15 Jun 2005 23:11:09 GMT Subject: "also" to balance "else" ? In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > Ron Adam wrote: > >> It occurred to me (a few weeks ago while trying to find the best way >> to form a if-elif-else block, that on a very general level, an 'also' >> statement might be useful. So I was wondering what others would think >> of it. > > But the feature is already there: Yes, that was pointed out to me, I was first interested in it as an if-also, which I found a few uses for and thought that it might naturally be extended to for and while, but the interpretation of the else in for loops conflicts with it, so it's ruled out in that form. See the last message I posted in this thread for a more explicit alternative that is more flexible and have less of a tenancy to be counter intuitive. Although a bigger change overall. I don't expect too much support for that one either, but who knows. The conversation is interesting (to me). ;-) Cheers, Ron From andreas at kostyrka.org Mon Jun 20 02:24:35 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 20 Jun 2005 08:24:35 +0200 Subject: Can we pass some arguments to system("cmdline")? In-Reply-To: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> References: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> Message-ID: <20050620062434.GA25097@heaven.kostyrka.org> On Sun, Jun 19, 2005 at 11:12:05PM -0700, Didier C wrote: > Hi! > I was wondering if we can pass some arguments to system("cmdline")? > > E.g in Perl, we can do something like: > > $dir="/home/cypher"; > > system("ls $dir"); > > which would instruct Perl to do an "ls /home/cypher" > > But in python, doing something like > > dir="/home/cypher" > system("ls dir") system("ls %(dir)s" % locals()) system("ls %s" % dir) system("ls %(name)s" % dict(name=dir) But you should consider if you really really want to do this. What happens when " " in dir? What happens when dir == "; rm -Rf /" Andreas From mm at newsgroups.com Thu Jun 2 19:48:05 2005 From: mm at newsgroups.com (MM) Date: Fri, 03 Jun 2005 11:48:05 +1200 Subject: odbc and python Message-ID: Are there any other odbc packages other than the win32all and mxodbc ones? The win32all odbc.pyd can't access table structure info like SQLColumns, and mxobdc requires a commercial license which is unjustifiable for this tiny project. Any other OS alternatives for win32?. Thanks. From bronger at physik.rwth-aachen.de Fri Jun 17 09:16:38 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 17 Jun 2005 15:16:38 +0200 Subject: Unbound names in __del__ References: Message-ID: Hall?chen! Peter Hansen writes: > [...] > > What's your use case for del? Every instance represents a "session" to a measurement instrument. After the instance is deleted, the session should be closed to free resources. If the program exists, this is actually not necessary, because then all resources are freed anyway. __del__ is called nevertheless. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From gcholakidis at hotmail.com.spam-remove Tue Jun 21 09:21:35 2005 From: gcholakidis at hotmail.com.spam-remove (Grigoris Tsolakidis) Date: Tue, 21 Jun 2005 16:21:35 +0300 Subject: Python can do it for me? References: <1119357359.145942.139840@g43g2000cwa.googlegroups.com> Message-ID: PyQt for example will do all this + Python but the desition is not that easy.... wrote in message news:1119357359.145942.139840 at g43g2000cwa.googlegroups.com... > Hello people! I think it is my first message here. > > Well, I would go to start a Delphi database program, but now my client > want a program that runs in Linux. So I want to know your opinion: > what best language/IDE I can use for my purposes? I need mainly: > > MySQL or Potsgree SQL ***remote connection***(it's the most important). > GUI interface. > Report generator. > Barcode printing. > > I just remember that for now... > > Maybe PyGTK can do it for me? What do you think? > > What do you think? > > Thank you! Bye! > From eloff777 at yahoo.com Wed Jun 22 17:15:02 2005 From: eloff777 at yahoo.com (Eloff) Date: 22 Jun 2005 14:15:02 -0700 Subject: MySQLdb reconnect In-Reply-To: <42b9a0d0_2@x-privat.org> References: <42b9a0d0_2@x-privat.org> Message-ID: <1119474902.809020.294840@g43g2000cwa.googlegroups.com> I don't beleive that it does. You can however call ping() on the connection which should attempt an automatic reconnection. See the docs for mysql_ping: http://dev.mysql.com/doc/mysql/en/mysql-ping.html I've never tested that, but I have a need for it also so let me know if it works or not. -Dan From cam.ac.uk at mh391.invalid Thu Jun 23 20:02:48 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 24 Jun 2005 01:02:48 +0100 Subject: Listening for a Keypress (Console, not GUI) In-Reply-To: <1119570015.859996.231510@z14g2000cwz.googlegroups.com> References: <1119570015.859996.231510@z14g2000cwz.googlegroups.com> Message-ID: brettk at gmail.com wrote: > So, my question is, using a regular console, is there a way I can get > python to listen for a specific keystroke? I'm using signal handling > to deal with ^C, could I also do something like that? This might help: http://www.python.org/doc/faq/windows.html#how-do-i-check-for-a-keypress-without-blocking -- Michael Hoffman From curi at curi.us Fri Jun 3 22:03:40 2005 From: curi at curi.us (Elliot Temple) Date: Fri, 3 Jun 2005 19:03:40 -0700 Subject: Scope Message-ID: <0F30BFA0-4245-404E-BC14-F5D69C3D692A@curi.us> I want to write a function, foo, so the following works: def main(): n = 4 foo(n) print n #it prints 7 if foo needs to take different arguments, that'd be alright. Is this possible? I already tried this (below), which doesn't work. foo only changes the global n. n = 3 def main(): def foo(var, context, c2): exec var + " = 7" in context, c2 n = 4 foo("n", locals(), globals()) print n if __name__ == '__main__': main() print n And of course I tried: >>> def inc(n): ... n += 3 ... >>> a = 4 >>> inc(a) >>> a 4 -- Elliot Temple http://www.curi.us/ --- [This E-mail scanned for viruses by Declude Virus] From peter at somewhere.com Mon Jun 27 10:21:04 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 27 Jun 2005 16:21:04 +0200 Subject: Daten Kinderheilkunde In-Reply-To: References: Message-ID: Peter Maas schrieb: > vielen Dank f?r die Zusendung der Daten. Es handelt sich allerdings > nicht um jpeg-Dateien, wie die Erweiterung nahelegt. Wir konnten sie > nur mit dem PictureViewer auf einem Apple anzeigen. Sie werden unter > MacOS als Adobe-Photoshop-Dokument angezeigt. Sorry, my fault. Please disregard this :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From rkern at ucsd.edu Sat Jun 4 20:30:19 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 04 Jun 2005 17:30:19 -0700 Subject: Sorted List (binary tree) why no built-in/module? In-Reply-To: <7AA3576E-AE6E-4C0D-AF69-253B28968646@advfn.com> References: <7AA3576E-AE6E-4C0D-AF69-253B28968646@advfn.com> Message-ID: Alex Stapleton wrote: > Unless I've totally missed it, there isn't a binary tree/sorted list > type arrangement in Python. Is there a particular reason for this? > Sometimes it might be preferable over using a list and calling > list.sort() all the time ;) Well, I believe that list.sort() has been optimized for the case where an item has been appended to the end of a sorted list. Also, look at the bisect module. > On a somewhat unrelated note, does anyone know how python searches > lists when you do things list list.index(n), is it a binary search, > or does it just scan the list? It just scans the list since there is no guarantee that it is sorted. The bisect module has a binary search for sorted lists. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rrr at ronadam.com Wed Jun 15 14:07:17 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 15 Jun 2005 18:07:17 GMT Subject: "also" to balance "else" ? In-Reply-To: References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: Fredrik Lundh wrote: > Ron Adam wrote: > > >>So the (my) confusion comes from the tendency to look at it in terms of >>overall program flow rather than in terms of the specific conditional >>logic. >> >>In a for loop the normal, as in terminating normally, behavior of a loop >>is one where the loop test evaluates as 'False' ending the loop. And >>the abnormal or counter behavior is when a break statement executes. >>Thus the 'else' block is the normal result, and the skipping the 'else' >>block becomes the abnormal counter behavior. > > > a typical use-case for for-in-else is a search loop: > > for item in collection: > if predicate(item): > print "found", item > break > else: > print "not found" > return > > print "use", item > > where your "abnormal behaviour" is, of course, the expected > behaviour. if you insist on looking at things the wrong way, > things will look reversed. > > It isn't so much as reading it the wrong way, as it is to how it reads in the context it is used in. In the above it works out that the negative search result is a successful loop completion, so the else reads correctly in that context. If the context was one of verifying completeness or correctness of a collection, then the context would be reversed and the else would indicate success instead of failure. I do see it both ways. Testing for an item in a list is probably the more common occurrence. If anything, this just points out the error of trying to apply code logic to a larger context. They aren't always the same. It is nice when code logic matches the context it's used in, as it makes the code much easier to read and understand. My initial thought of adding 'also' was that it might lead to being able to write more code where the code logic more directly parallels the context it's used in. From the few example uses I've found in the library, it looks like it wouldn't make that big of a difference. Maybe someone else can find more uses than I have. I tried. Regards, Ron From thomasbartkus at comcast.net Wed Jun 22 13:31:27 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 22 Jun 2005 12:31:27 -0500 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: <0sOdnXfcRNBzAiTfRVn-sQ@telcove.net> "Dan" wrote in message news:UJgue.20$jv6.1349 at news.uswest.net... > On 6/22/2005 11:38 AM, Thomas Bartkus wrote: > > Will McGugan" wrote in message > > news:42b97240$0$24467$da0feed9 at news.zen.co.uk... > > > > And then XP Autoupdate executes, some of those Access/MSDE libraries are > updated, and you app is broken. Hasn't happened yet! For the record - I wouldn't recommend automatic updates of any kind for a Linux/MySQL system either. For precisely the same reasons. Thomas Bartkus From fredrik at pythonware.com Tue Jun 14 01:37:16 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 07:37:16 +0200 Subject: ElementTree Namespace Prefixes References: <1118680405.635415.110740@f14g2000cwb.googlegroups.com> Message-ID: Oren Tirosh wrote: > It all boils down to how you define "the same". Which parts of the XML > document are meaningful content that needs to be preserved and which > ones are mere encoding variations that may be omitted from the internal > representation? > > Some relevant references which may be used as guidelines: > > * http://www.w3.org/TR/xml-infoset > The XML infoset defines 11 types of information items including > document type declaration, notations and other features. It does not > appear to be suitable for a lightweight API like ElementTree. > > * http://www.w3.org/TR/xpath-datamodel > The XPath data model uses a subset of the XML infoset with "only" seven > node types. > > http://www.w3.org/TR/xml-c14n > The canonical XML recommendation is meant to describe a process but it > also effectively defines a data model: anything preserved by the > canonicalization process is part of the model. Anything not preserved > is not part of the model. you forgot http://effbot.org/zone/element-infoset.htm which describes the 3-node XML infoset subset used by ElementTree. From bill.mill at gmail.com Tue Jun 14 10:41:07 2005 From: bill.mill at gmail.com (Bill Mill) Date: Tue, 14 Jun 2005 10:41:07 -0400 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42AED7B3.8060009@carmen.se> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <42AED7B3.8060009@carmen.se> Message-ID: <797fe3d40506140741714694f1@mail.gmail.com> On 6/14/05, Magnus Lycka wrote: > Andrew Dalke wrote: > > Andrea Griffini wrote: > > > >>This is investigating. Programming is more similar to building > >>instead (with a very few exceptions). CS is not like physics or > >>chemistry or biology where you're given a result (the world) > >>and you're looking for the unknown laws. In programming *we* > >>are building the world. This is a huge fundamental difference! > > > > Philosophically I disagree. Biology and physics depends on > > models of how the world works. The success of a model depends > > on how well it describes and predicts what's observed. > > > > Programming too has its model of how things work; you've mentioned > > algorithmic complexity and there are models of how humans > > interact with computers. The success depends in part on how > > well it fits with those models. > > And this is different from building? I don't disagree with the > other things you say, but I think Andrea is right here, although > I might have said construction or engineering rather than building. > > To program is to build. While scientists do build and create things, > the ultimate goal of science is understanding. Scientists build > so that they can learn. Programmers and engineers learn so that > they can build. > > > It seems to me that *real* computer scientists are very rare. I'd like to say that I think that they do, in fact, exist, and that it's a group which should grow and begin to do things more like their biological counterparts. Why? Because, as systems get more complex, they must be studied like biological systems. I spent a while in college studying latent semantic indexing (LSI) [1], which is an algorithm that can be used to group things for clustering, searching, and other uses. It is known *to* be effective in some circumstances, but nobody (at least when I was studying it ~2 years ago) knows *why* it is effective. With the help of my professor, I was helping to try and determine that *why*. We had a hypothesis [2], and my job was basically to build experiments to test our hypothesis. First, I built a framework to perform LSI on arbitrary documents (in python of course, let's keep it on topic :), then I started to do experiments on different bodies of text and different variations of our hypothesis. I kept a lab journal detailing what I had changed between experiments, some of which took days to run. I believe that there are at least a fair number of computer scientists working like this, and I believe that they need to recognize themselves as a separate discipline with separate rules. I'd like to see them open source their code when they publish papers as a matter of standard procedure. I'd like to see them publish reports much more like biologists than like mathematicians. In this way, I think that the scientific computer scientists could begin to become more like real scientists than like engineers. Just my 2 cents. Peace Bill Mill [1] http://javelina.cet.middlebury.edu/lsa/out/lsa_definition.htm [2] http://llimllib.f2o.org/files/lsi_paper.pdf From uche.ogbuji at gmail.com Sun Jun 26 09:34:05 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 26 Jun 2005 06:34:05 -0700 Subject: formatted xml output from ElementTree inconsistency In-Reply-To: <1119676855.035495.182190@f14g2000cwb.googlegroups.com> References: <1119646423.324518.220710@o13g2000cwo.googlegroups.com> <4cmpb1hnu62j7gkk8qanl6a7a9d40gi3v1@4ax.com> <1119676855.035495.182190@f14g2000cwb.googlegroups.com> Message-ID: <1119792845.345651.57480@o13g2000cwo.googlegroups.com> Patrick Maupin wrote: """ Dennis Bieber wrote: > Off hand, I'd consider the non-binary nature to be because the > internet protocols are mostly designed for text, not binary. A document at http://www.w3.org/TR/REC-xml/ lists "the design goals for XML". One of the listed goals is "XML documents should be human-legible and reasonably clear". """ Yes. Thanks for mentioning this, because people too often forget it. minidom, 4Suite's Domlette and Amara all provide good pretty-print output functions. The latter two use rules from the XSLT spec, which is designed by people who have the above design goal well in their blood. -- Uche http://copia.ogbuji.net From socyl at 987jk.com.invalid Fri Jun 17 12:20:00 2005 From: socyl at 987jk.com.invalid (kj) Date: Fri, 17 Jun 2005 16:20:00 +0000 (UTC) Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? Message-ID: I'm a Perlhead (there, I said it). Years ago I made a genuine attempt to learn Python, but my intense disappointed with the way Python deals with scopes ultimately sapped my enthusiasm. I couldn't live without closures and without the fine control over scopes that Perl provides. I've been wanting to make another attempt to (re)learn Python for a while, but this scopes business remained a major damper. What's pushing me over my reluctance is having to work with a large in-house package developed in Python. I am hoping that it may be better this time around. For one thing, like Perl, Python was then (and maybe still is) a "work in progress." So I figure that Python scoping may have improved since then. Even if not, I think that Python is mature enough by now that adequate alternatives must have been devised for the Perlish features that I missed during my first attempt. My question is: is there any tutorial on Python scoping aimed at diehard Perlheads? Thanks! kj -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From claird at lairds.us Fri Jun 17 13:08:06 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 17 Jun 2005 17:08:06 GMT Subject: Back to the future - python to C++ advice wanted References: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> <42b2e74d$0$8916$636a15ce@news.free.fr> Message-ID: <53cbo2-igv.ln1@lairds.us> In article <42b2e74d$0$8916$636a15ce at news.free.fr>, bruno modulix wrote: >George Sakkis wrote: . . . >> learned in similar situations. How one can avoid the frustration of >> having to work with a low level language once he has seen the Light ? >> >Well, I'm lucky enough to not to have to use C++ again, so I can't >answer directly. But I think this might interest you: >http://www.boost.org/ >(NB : never tried it myself, but seems to be a nice job) . . . That's one approach. Here's another: read Scott Meyer's latest *Effective C++*, follow his advice, and become familiar with idioms (and libraries, to the extent they're available!) that make C++ a rather high-level language. From eurleif at ecritters.biz Sun Jun 19 12:46:50 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 19 Jun 2005 16:46:50 GMT Subject: Shortcut to initialize variables In-Reply-To: <42b31929$1_2@newspeer2.tds.net> References: <1119032651.912256.319140@o13g2000cwo.googlegroups.com> <42b31929$1_2@newspeer2.tds.net> Message-ID: <_jhte.703$S17.89343@monger.newsread.com> Kent Johnson wrote: > letters = {} > for letter in ascii_lowercase: > letters[letter] = 0 Or more simply: letters = dict.fromkeys(ascii_lowercase, 0) From roy at panix.com Thu Jun 30 20:25:17 2005 From: roy at panix.com (Roy Smith) Date: Thu, 30 Jun 2005 20:25:17 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> Message-ID: Ivan Van Laningham wrote: > It really was used "for everything"; C compilers have *always* let you > include assembler, with the "asm" keyword. Unless you're talking about > the early days of DOS/Windows compilers, about which I know little, but > all *K&R* compilers had asm. If you wanted to write kernel code and > device driver code (including disk drivers) for large Unix systems, asm > was a requirement. The ability to embed assembler in-line with C code is only a convenience. For the extremely small amount of assembler code required in a typical kernel, it's easy enough to write small routines directly in assembler, and call them from your C code like you would any other function. The last time I was inside a Unix kernel was the pdp-11 days. The pdp-11 was a memory-mapped machine, which meant almost all hardware interactions were done by loading and reading fixed memory locations. So, you could do things like (I'm doing this from memory, so it's only vaguely correct): struct dr11regs { unsigned int cmd; unsigned int status; unsigned int count; unsigned int base; }; struct dr11regs *drptr = 0177540; char buf[MAXBUF]; drptr->base = buf; drptr->count = MAXBUF; drptr->cmd =& DR_START; while ((drptr->status & DR_REMAIN) > 0) { wait(); } That's a lot of low-level bit fiddling right down on the bare metal, and not a line of assembler in sight. From guettli at thomas-guettler.de Thu Jun 23 10:21:55 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 23 Jun 2005 16:21:55 +0200 Subject: Allowing only one instance of a script? References: <1119509361.208748.247400@g49g2000cwa.googlegroups.com> Message-ID: Am Wed, 22 Jun 2005 23:49:21 -0700 schrieb Ali: > Hi, > > I have a script which I double-click to run. If i double-click it > again, it will launch another instance of the script. > > Is there a way to allow only one instance of a script, so that if > another instance of the script is launched, it will just return with an > error. Hi, Create a file which contains the PID (process ID) of the current process in a directory. If the file already exists, the file is running. If your script dies without removing the pid-file, you need to look during the start if the PID which is in the file is sill alive. There is a small race condition between os.path.exists() and writing the file. If you want to be 100% sure you need to use file locking. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From paulm at barley.vel.net Thu Jun 30 17:12:56 2005 From: paulm at barley.vel.net (paulm) Date: Thu, 30 Jun 2005 16:12:56 -0500 Subject: Newbie backreference question Message-ID: Hi, In perl I can do something like: $a = 'test string'; $a =~ /test (\w+)/; $b = $1; print $b . "\n"; and my output would be "string". How might this snippet be written in python? Thanks to all... From mfranklin1 at gatwick.westerngeco.slb.com Wed Jun 15 02:39:10 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 15 Jun 2005 07:39:10 +0100 Subject: Tkinter question In-Reply-To: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> References: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> Message-ID: Nicholas.Vaidyanathan at aps.com wrote: > I'm sure there must be a way to do this, but I can't figure it out for > the life of me? I'm writing a program where I would like to use a > button's text field as part of an if statement. I set up my button like > this: > > i = [ "7", "8","9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", > ".", "=", "+"] > t = 0 #iterator through the sequence > > for x in range(4): > for y in range(4): > self.buttonx = Button(self, text = "%s" %i[t] , > width=10, command = self.pressed) > self.buttonx.grid( row=x+1, column = y, sticky = W+E+S) > t+=1 > > What I would like to do is is check which buttons' text values are > digits, and if the text is, I would like to append the number to a > label. But: > > if(self.buttonx.title.isdigit): > To get the text of a button: self.buttonx["text"] From miki.tebeka at zoran.com Thu Jun 9 05:06:29 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 9 Jun 2005 12:06:29 +0300 Subject: killing process in windows In-Reply-To: <20050606134839.36485.qmail@web32510.mail.mud.yahoo.com> References: <20050606134839.36485.qmail@web32510.mail.mud.yahoo.com> Message-ID: <20050609090629.GM3544@zoran.com> Hello Veronica, > I am using Trent's process.py but I have a problem with killing the > processes in windows. > For example : > > import process,time > > p=process.ProcessOpen('C:\Program Files\Windows Media > Player\wmplayer') > time.sleep(3) > p.kill() > > will start Media Player without terminating it. > Any suggestions? A brutal way will be to use win32process.TerminateProcess (from win32all package - http://starship.python.net/crew/mhammond/). HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From richardlewis at fastmail.co.uk Tue Jun 21 10:20:13 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Tue, 21 Jun 2005 15:20:13 +0100 Subject: Python can do it for me? In-Reply-To: <1119361876.273665.114710@f14g2000cwb.googlegroups.com> References: <1119357359.145942.139840@g43g2000cwa.googlegroups.com> <1119361876.273665.114710@f14g2000cwb.googlegroups.com> Message-ID: <1119363613.7016.236838726@webmail.messagingengine.com> On 21 Jun 2005 06:51:16 -0700, "silasju at gmail.com" said: > Really? I see Python is very good general-purpose language. I studing > TCL, C++ and Java too. > > And remote conection? Do you know something? > You mean connecting to a database from a remote machine? Most (probably all) database modules for Python allow you to access the database using the server/host name of the database server. So as long as your database server accepts connections from remote machines this will not be a problem. Cheers, Richard From scottakirkwood at gmail.com Fri Jun 3 10:19:32 2005 From: scottakirkwood at gmail.com (Scott Kirkwood) Date: Fri, 3 Jun 2005 11:19:32 -0300 Subject: Just remember that Python is sexy In-Reply-To: <20050530215739.1464717829.whereU@now.com> References: <1116899839.323185.58350@g49g2000cwa.googlegroups.com> <20050530215739.1464717829.whereU@now.com> Message-ID: Yes, but we don't want it to get out of hand, like calling it orgy() instead of join(). Or condom() instead of secure(). Or onClimax() instead of onFinished() :-) On 5/31/05, Eric Pederson wrote: > > > I often can't remember that to remove spaces from a string whether it's > > strip() or trim(), and when finding patterns with the re library > > whether it's find() or search() and when iterating over key, values of > > a dictionary whether it's items() or entries(). > > But then I remember that Python is "sexy". > > It is sexier to strip() than to trim(). > > You do a strip search() not a find() search. > > And you remove items() of clothing and not entries() of clothing. > > > Genius! I will never perplex myself with string_foo.trim() again. (I do > forget) > > I recommend this be adopted as a naming standard for Python methods: > > "The method name should have a sexy connotation" > > > > > > > > > > > > > Eric Pederson > http://www.songzilla.blogspot.com > ::::::::::::::::::::::::::::::::::: > domainNot="@something.com " > domainIs=domainNot.replace("s","z") > ePrefix="".join([chr(ord(x)+1) for x in "do"]) > mailMeAt=ePrefix+domainIs > ::::::::::::::::::::::::::::::::::: > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From domma at procoders.net Fri Jun 3 02:59:21 2005 From: domma at procoders.net (Achim Domma (Procoders)) Date: Fri, 03 Jun 2005 08:59:21 +0200 Subject: read input for cmd.Cmd from file Message-ID: Hi, I'm writing a simple shell using cmd.Cmd. It would be very usefull if I could read the commands as batchjob from a file. I've tried the following: class MyShell(cmd.Cmd): def __init__(self,stdin): cmd.Cmd.__init__(self,stdin=stdin) ... ... if __name__=='__main__': if len(sys.argv)==2: shell=MyShell(file(sys.argv[1])) else: shell=MyShell(sys.stdin) shell.cmdloop() Calling 'myshell.py inputfile' with an invalid inputfile, I get an error, so it seems that the file is opened. But the shell starts as usuall, ignoring the content of the file. There is no output and no errors (if I write nonsens into the inputfile). Could anybody help? regards, Achim From snail at objmedia.demon.co.uk Fri Jun 3 07:36:32 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 3 Jun 2005 12:36:32 +0100 Subject: Problem calling Python methods from C References: Message-ID: In message , Stephen Kellett writes Following my posting with the solution for anyone else that wants to know the answer. The solution appears to be not to use: >module = PyImport_AddModule("gc"); But to use module = PyImport_ImportModule("gc"); Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From just at xs4all.nl Wed Jun 1 14:06:26 2005 From: just at xs4all.nl (Just) Date: Wed, 01 Jun 2005 20:06:26 +0200 Subject: metaclass that inherits a class of that metaclass? References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> <1117648438.079178.92490@z14g2000cwz.googlegroups.com> Message-ID: In article <1117648438.079178.92490 at z14g2000cwz.googlegroups.com>, "infidel" wrote: > [ ... ] type is, from my trivial understanding, the > base type and base metaclass for everything else in python. Saying > "type is an object" is only confusing you into thinking it is a > subclass of object, which is not the case. Sure is: >>> type.__bases__ (,) > object is a class, which I > believe has type as it's metaclass (though I could be mistaken - this > gets terribly confusing very quickly). Correct: >>> object.__class__ type also has type as its metaclass: >>> type.__class__ In other words, type is an instance of itself. Just From hancock at anansispaceworks.com Wed Jun 1 17:07:15 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Jun 2005 16:07:15 -0500 Subject: idiom for constructor? In-Reply-To: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <200506011607.15219.hancock@anansispaceworks.com> On Wednesday 01 June 2005 12:50 pm, Mac wrote: > Is there a nice Python idiom for constructors which would expedite the > following? > > class Foo: > def __init__(self, a,b,c,d,...): > self.a = a > self.b = b > self.c = c > self.d = d > ... > > I would like to keep the __init__ parameter list explicit, as is, > rather than passing in a dictionary, as I want the code to be explicit > about what arguments it expects... in effect enforcing the right number > of arguments. Well, it's hard to automate it and keep the parameter list explicit, but you could do this, of course: class Foo: def __init__(self, *args): maps = zip(('a','b','c','d'), args[:4]) for map in maps: setattr(self, map[0], map[1]) Which *will* limit the arguments to the ones specified. As an additional tweak, you could make this a base class and put the argument list in the subclass to hide the magic: class Args: argspec = () def __init__(self, *args): maps = zip(self.argspec, args[:len(self.argspec)]) for map in maps: setattr(self, map[0], map[1]) class Foo(Args): argspec = ('a', 'b', 'c', 'd') Or even better, use a method, so you can customize: class Args: argspec = () def _get_args(self, *args): maps = zip(self.argspec, args[:len(self.argspec)]) for map in maps: setattr(self, map[0], map[1]) class Foo(Args): argspec = ('a', 'b', 'c', 'd') def __init__(self, *args): self._get_args(*args) This version silently ignores extra arguments, but you might want to raise an exception instead: class Args: argspec = () def _get_args(self, *args): expected = len(self.argspec) given = len(args) if expected != given: raise TypeError("__init__ takes exactly %d arguments (%d given)" % (expected, given)) maps = zip(self.argspec, args[:expected]) for map in maps: setattr(self, map[0], map[1]) Using this, I get the following response to too many arguments: >>> g = Foo(1, '3', 4.0, 'spam', 'eggs') Traceback (most recent call last): File "", line 1, in ? File "", line 4, in __init__ File "", line 7, in _get_args TypeError: __init__ takes exactly 4 arguments (5 given) HTH Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From wpeterson1 at socal.rr.com Thu Jun 30 16:46:22 2005 From: wpeterson1 at socal.rr.com (Bill) Date: 30 Jun 2005 13:46:22 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <1120164382.757002.18930@o13g2000cwo.googlegroups.com> James Stroud wrote: > Frankly, I can't watch Shakespeare or movies like "the full monty" or > "trainspotting" because I can't understand a damn word they say. British talk > sounds like gibberish to me for the most part. Have you had your hearing checked recently? Seriously. I have a hearing defect and speakers from the UK give me by far the most difficulty. People speaking English as a second language are more understandable. From guettli at thomas-guettler.de Thu Jun 23 10:45:16 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 23 Jun 2005 16:45:16 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: Am Wed, 22 Jun 2005 17:57:14 +0200 schrieb Riccardo Galli: > Hi, > I noticed that when I use os.listdir I need to work with absolute paths > 90% of times. > While I can use a for cycle, I'd prefere to use a list comprehension, > but it becomes too long. Hi, I like it. But as you noticed, too, "join" would be better than "abs". Example: # mylistdir.py import os import sys def mylistdir(dir, join=False): for file in os.listdir(dir): yield os.path.join(dir, file) print list(mylistdir(sys.argv[1])) Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From rune.strand at gmail.com Wed Jun 1 20:13:50 2005 From: rune.strand at gmail.com (Rune Strand) Date: 1 Jun 2005 17:13:50 -0700 Subject: Strange KeyError using cPickle Message-ID: <1117671230.384189.120030@f14g2000cwb.googlegroups.com> I'm experiencing strange errors both with pickle and cPickle in the below code: import cPickle as pickle #import pickle from string import ascii_uppercase from string import ascii_lowercase def createData(): d1 = list("Something's rotten") d2 = tuple('in the state of Denmark') d3 = [('a', 'b'), ('c', 'd')] #d3 = [('s a', 's b'), ('s c', 's d')] #d3 = [('sa', 'sb'), ('sc', 'sd')] #d3 = [['s a', 's b'], ['s c', 's d']] d4 = dict(zip(ascii_uppercase,ascii_lowercase)) return [d1, d2, d3, d4] def doPickle(data, pickleFile = 'pickleTest.p', proto = 2): f = XWwz(pickleFile, 'w') p = pickle.Pickler(f, proto) p.dump(data) f.close() def doUnpicle(pickleFile = 'pickleTest.p'): f = XWwz(pickleFile, 'rb') up = pickle.Unpickler(f) data = up.load() f.close() return data data = createData() doPickle(data) xdata = doUnpicle() 1) The above code works, but if I use pickle instead of cPickle, I get "KeyError: '\n'" when unpickling. 2) If I uncomment any of the other d3 bindings in createData(), I get "KeyError: '\n'", or "cPickle.UnpicklingError: invalid load key, ''" (newline) 3) If I don't use the d1, d2 and d4 bindings, no error occurs. I can't find the explanation. Why the newline error? There are no newlines in the data. Are not all those structures pickable? Thanks for all help! (on WinXP, CPython 2.4.1) From adsheehan at eircom.net Wed Jun 8 10:06:18 2005 From: adsheehan at eircom.net (adsheehan at eircom.net) Date: 8 Jun 2005 07:06:18 -0700 Subject: Embedding: many interpreters OR one interpreter with many thread states ? Message-ID: <1118239578.831376.218370@o13g2000cwo.googlegroups.com> Hi, Does anyone know the reasoning or pros/cons for either (in a multi-threaded C++ app): - creating many sub-interpreters (Py_NewInterpreter) with a thread state each Or - creating one interpreter with many thread states (PyThreadState_New) When do I choose one approach over the other and why ? Thanks Alan From joch at [remove-before-replying]blueyonder.co.uk Mon Jun 20 15:14:01 2005 From: joch at [remove-before-replying]blueyonder.co.uk (John Ochiltree) Date: Mon, 20 Jun 2005 19:14:01 GMT Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? References: <9s77b1h8195sgmvb8p4e9qp8qts1tokprl@4ax.com> Message-ID: <2005062020140116807%joch@removebeforereplyingblueyondercouk> On 2005-06-18 05:26:13 +0100, Dennis Lee Bieber said: > On Sat, 18 Jun 2005 03:02:13 +1000, Steven D'Aprano > declaimed the following in > comp.lang.python: > >> >> The language is *always* spelt without the "a", and usually all in >> lower-case: perl. >> > Given that, at least one well known, book relates the name to > Practical Extraction (&) Report Language, whether that was a retrofit or > not -- I'd be tempted to user PERL for the name... All lowercase most > likely reflects the standard habits of Linux/Unix command naming. I'd heard it was pathologically eclectic rubbish lister, but then you can't believe everything you hear :-) John Ochiltree -- 667 - The Neighbour of the Beast From tjreedy at udel.edu Thu Jun 16 11:51:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 16 Jun 2005 11:51:59 -0400 Subject: Unbound names in __del__ References: Message-ID: "Torsten Bronger" wrote in message news:m34qby1kaq.fsf at bob.ipv.kfa-juelich.de... >Is there a way to detect whether the program is being terminated? See atexit module to register cleanup functions that run *before* the interpreter starts haphazardly deleting stuff. Terry J. Reedy From jabel at plus.net Fri Jun 10 10:19:23 2005 From: jabel at plus.net (John Abel) Date: Fri, 10 Jun 2005 15:19:23 +0100 Subject: Perl s/ To Python? In-Reply-To: <150e7uha8wt38$.wsnjzb0472n3$.dlg@40tude.net> References: <150e7uha8wt38$.wsnjzb0472n3$.dlg@40tude.net> Message-ID: <42A9A16B.8060007@plus.net> JZ wrote: >Dnia Fri, 10 Jun 2005 14:57:21 +0100, John Abel napisa?(a): > > > >>$testVar =~ s#/mail/.*$##g >> >>The only way I can think of doing it, is: >> >>mailPos = testVar.find( "mail" ) >>remainder = testVar[ :mailPos ] >> >>Any ideas would be appreciated. I'm iterating over a lot of entries, >>and running these lines for each entry. >> >> > >import re >testVar = re.compile(r'/mail/.*$').sub('', testVar) > >-- >JZ > > That's brill. Never even thought if using re. Thank you! J From andrea.valle at unito.it Sun Jun 5 06:22:35 2005 From: andrea.valle at unito.it (andrea valle) Date: Sun, 5 Jun 2005 12:22:35 +0200 Subject: executing a command In-Reply-To: References: Message-ID: Thanks, I solved it. The problem depended on IDLE. If I invoke a file from command line with os.exec* everything works perfectly.- Best -a- On 5 Jun 2005, at 01:07, Tiago St?rmer Daitx wrote: > Hello, > > When you use one of the os.exec*p functions python looks for the > specified file in the directories refered by os.environ['PATH']. If > and _only_ if your os.enviroment['PATH'] isn't set then it looks in > os.defpath - you can check this at > http://www.python.org/doc/current/lib/os-path.html#l2h-1557 > > So, my advice is that you first try printing your os.environ['PATH'] > to check wheter it includes the program that you are calling or not > (and then you will have to include it). In the case that it isn't set, > then check os.defpath. > > Also, when you use one of the functions os.exec that requires a path > variable to be passed (ie. the ones that doesn't have 'p' in their > names) the path can be relative or absolute, but it must include the > file name (and not only the dir where the file is). > > And for each one of these os.exec* functions the first argument will > always be used as the program "name" (argv[0]), so unless you a reason > to do otherwise, pass the same name as the file that you are calling. > > > Regards, > Tiago S Daitx > > On 6/4/05, andrea valle wrote: >> Hi to all, >> I need to run a program from inside python (substantially, algorithmic >> batch processing). >> I'm on mac osx 10.3.8 with python 2.3 framework and macpython. >> >> Trying to use exec*, I checked references, Brueck & Tanner, and then >> grab this code from effbot: >> >>>>> program = "python" >>>>> def run(program, *args): >> os.execvp(program, (program,) + args) >> print "ok" >> >>>>> run("python", "/Users/apple/Desktop/prova.py") >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> run("python", "/Users/apple/Desktop/prova.py") >> File "", line 2, in run >> os.execvp(program, (program,) + args) >> File >> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/os.py", line 336, in execvp >> _execvpe(file, args) >> File >> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/os.py", line 374, in _execvpe >> func(fullname, *argrest) >> OSError: [Errno 45] Operation not supported >> >> This OSError seems to be consistend with all exec family. What does it >> mean and how to use exec? >> >> I also tried with. os.system. It works if I invoke python, but it >> fails >> (in a way I don't know) when I invoke other programs. >> >> For example: >> command = "python /Users/apple/Desktop/test.py" >>>>> os.system(command) >> 0 >> (test.py write a string in a file. It works) >> >> But with lilypond or with latex I have no output (and in fact it >> doesn't give 0 as result): >> >>>>> command = "lilypond /Users/apple/Desktop/test.ly" >>>>> os.system(command) >> 32512 >>>>> command = "latex /Users/apple/Desktop/test.tex" >>>>> os.system(command) >> 32512 >> >> Any help is much appreciated >> >> Thanks a lot >> >> -a- >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle at unito.it From bkhl at stp.ling.uu.se Wed Jun 29 06:12:38 2005 From: bkhl at stp.ling.uu.se (=?utf-8?q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Wed, 29 Jun 2005 12:12:38 +0200 Subject: map vs. list-comprehension References: <42c27238$0$26269$626a14ce@news.free.fr> Message-ID: <87irzxtqsp.fsf@lucien.dreaming> "F. Petitjean" writes: > res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] > > Hoping that zip will not be deprecated. Nobody has suggested that. The ones that are planned to be removed are lambda, reduce, filter and map. Here's GvR's blog posting that explains the reasons: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From kay.schluehr at gmx.net Wed Jun 8 01:49:09 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 7 Jun 2005 22:49:09 -0700 Subject: computer algebra packages In-Reply-To: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> Message-ID: <1118209749.248567.168700@g49g2000cwa.googlegroups.com> Rahul wrote: > Hi. > Well is there an open source computer algebra system written in python > or at least having a python interface? > I know of 2 efforts: pythonica and pyginac...are there any others? > > rahul Not in the moment. But I have a question to you: why do you seek for a CAS in Python? I ask this because I'm interested in such kind of stuff and secretly working on one, but this is highly experimental, a proof of the concept work and will probably not provide the amount of features/packages of a commercial CAS like Mathematica and Maple in a dozend years. There are also a couple of free CAS like Octave or Yacas, that do their job. Why do people ask periodically for a CAS in Python in this place? I'm just curious about it. Kay From fredrik at pythonware.com Wed Jun 8 13:59:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 8 Jun 2005 19:59:21 +0200 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> Message-ID: Jordan Rastrick wrote: > I just spent a long, long time tracking down a bug in a program that > results from this behaviour. > > Surely the != operator should, if no __ne__ method is present for > either object, check to see if an __eq__ method is defined, and if so, > return its negation? > > Actually, that brings me to a wider question - why does __ne__ exist at > all? Surely its completely inconsistent and unnessecary to have > seperate equals and not equals methods on an object? a != b should just > be a short way of writing not (a == b). The fact the two can give a > different answer seems to me to be utterly unintuitive and a massive > pitfall for beginners (such as myself). surely reading the documentation would be a great way to avoid pitfalls? http://docs.python.org/ref/customization.html __lt__, __le__ (etc) New in version 2.1. These are the so-called "rich comparison" methods, and are called for comparison operators in preference to __cmp__() below. /.../ There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__, one should also define __ne__ so that the operators will behave as expected. /.../ __cmp__ Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. /.../ for a number of situations where __ne__ cannot be derived from __eq__, see: http://www.python.org/peps/pep-0207.html 0 From max at alcyone.com Mon Jun 20 11:50:57 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 20 Jun 2005 08:50:57 -0700 Subject: Python choice of database In-Reply-To: <9yBte.372$W74.334@newssvr30.news.prodigy.com> References: <9yBte.372$W74.334@newssvr30.news.prodigy.com> Message-ID: Philippe C. Martin wrote: > Well that would be shelve I guess ... with the restrictions I mentioned. I was talking about pickle, not shelve. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I used to walk around / Like nothing could happen to me -- TLC From sjmachin at lexicon.net Wed Jun 29 22:45:06 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 30 Jun 2005 12:45:06 +1000 Subject: Help please: How to assign an object name at runtime In-Reply-To: <1120092944.710361.309310@g44g2000cwa.googlegroups.com> References: <1120092944.710361.309310@g44g2000cwa.googlegroups.com> Message-ID: <42C35CB2.1040204@lexicon.net> c0chong at gmail.com wrote: > Good day: > Probably the answer to my question is staring me in the face, but the > solution escapes me. > > The following is the input line of the file: SoftDict-.csv: > ca1017,GRPHScriptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14 > > I expected an instance of Machine() to be created with a name ca1017. There is absolutely no basis at all for this expectation. How did you arrive at it? > > Instead, an object is assigned to l[0] named: > <__main__.Machine instance at 0x01282558> The object is assigned to l[0] exactly as you dictated, i.e. its name is l[0]. The former referent of l[0] i.e. the string whose value is "ca1017" is no longer in view and will be garbage-collected. What are you really wanting to do? BTW, don't use "l". > > ----------------------------- > Here is my code: > > class Machine: > def __init__(self): > self.software = []# Holds attributes of the instance Do you mean like self.software ultimately = ['GRPHScriptSet', 'ADD/REM', 'Adobe Acrobat 4.0=2005/06/14'] ? That's not quite what the man meant when he said 'object-oriented'!! > def add(self, sware): > self.software.append(sware)# Append attribute > return self.software > def show(self): > return self.software > def __call__(self): > return [ e for e in self.software] Isn't that the same as "return self.software"? So obj.show() and obj() return an attribute of obj? That's an "interesting" interface. Lose the __call__ -- you don't need it. > def cnt(self): > return '%s' % (len(self.software)) Why not just return the length as an integer??? > def installed(self, sware): > if sware in self.software: > return True > else: > return False Try "return sware in self.software" > > class FileList: > def __init__(self, filename): > self.file = open(filename, 'r') # open and save file > def __getitem__(self, i): # overload indexing > line = self.file.readline() > if line: > return line # return the next line > else: > raise IndexError # end 'for' loops, 'in' > def __getattr__(self, name): > return getattr(self.file, name) # other attrs > > > if __name__ == '__main__': > > import sys, fileinput, os, string # when run, not imported > > for line in FileList('SoftDict-.csv'): # Treat .csv as a text > if len(line)==1: break # Quit processing; end of file > l=line.split(',')# Split the line into constituent parts > l[0]=Machine() # Create a Machine() object named: ca1017 > ------------------------------------------- > > That's it. I evidently have no idea what I am doing. The whole FileList class is pointless. Step 1: replace """for line in FileList(filename):""" with """for line in open(filename):""" and lose the """if .... : break""" line. Step 2: read up on the csv module, and lose the "split". Step 3: you are unlikely to *ever* need the string and fileinput modules Step 4: you import 4 modules you don't use. Why? Oh and BTW Step 0: what are the requirements for this exercise, what do the fields in the file actually represent, what is that bloody = sign between 'Adobe Acrobat' and the date aaaarrrggghhhh words fail me [finally] ... exiting in pursuit of paracetamol, John From python-url at phaseit.net Wed Jun 29 14:18:35 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 29 Jun 2005 18:18:35 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) Message-ID: QOTW: "And what defines a 'python activist' anyway? Blowing up Perl installations worldwide?" - Ivan Van Laningham "Floating point is about nothing if not being usefully wrong." - Robert Kern Sibylle Koczian needs to sort part of a list. His first attempt made the natural mistake - sorting a *copy* of part of the list: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9b7da3bed2719f18 Kevin Dangoor compares ZODB and pysqlite with SQLObject: http://www.blueskyonmars.com/2005/06/18/zodb-vs-pysqlite-with-sqlobject/ Uwe Mayer needs a little convincing about "consenting adults" philosophy: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d4d8738a6e8281ff Zope 2.8.0 is released: http://article.gmane.org/gmane.comp.web.zope.announce/987 Guido's ITC audio interview sparks off a discussion about the advantages of static typing in terms of tool support: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5aee06316a0412b Only c.l.py can go *this* far off topic without flames: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1be27ccd50534e1b Is there any good stuff left that Python should steal from other languages? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d297170cfbf1bb34 Peter Gengtsson reminds himself and us how useful the \b regular expression special element is: http://www.peterbe.com/plog/slash_b Are there any 3rd party modules that you'd like to see included in the standard library? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cd236084973530dc Is Python a good language for teaching children to program? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/68a3ac09b4937c88 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From andreas at kostyrka.org Thu Jun 23 05:34:02 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 23 Jun 2005 11:34:02 +0200 Subject: PEP ? os.listdir enhancement In-Reply-To: References: Message-ID: <20050623093402.GA3319@heaven.kostyrka.org> What's wrong with (os.path.join(d, x) for x in os.listdir(d)) It's short, and easier to understand then some obscure option ;) Andreas On Thu, Jun 23, 2005 at 11:05:57AM +0200, Riccardo Galli wrote: > On Wed, 22 Jun 2005 11:27:06 -0500, Jeff Epler wrote: > > > Why not just define the function yourself? Not every 3-line function > > needs to be built in. > > Of course I can code such a function, and I agree with the second > sentence, but I think that obtaining absolutes path is a task so commonly > needed that adding a keyword to an existing function would give a plus to > the library without adding complexity (speaking of number of modules). > > Usually when you use os.listdir do you end using os.path.join to obtain > absolutes path? I'm interested to know if the task is so common as I > think, or if I'm wrong. > > Thank you, > Riccardo > > > -- > Riccardo Galli > Sideralis Programs > http://www.sideralis.net > -- > http://mail.python.org/mailman/listinfo/python-list From martin.witte at gmail.com Mon Jun 13 16:17:33 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 13 Jun 2005 13:17:33 -0700 Subject: recursive import list In-Reply-To: References: Message-ID: <1118693853.601057.92730@g44g2000cwa.googlegroups.com> If you use your own import function, like below, you could create a list of all imported modules. #!/usr/bin/env python mod_list = [] def my_import(name, globals = None, locals = None, fromlist = None): mod_list.append(name) mod = __import__(name, globals, locals, fromlist) return mod os = my_import('os') print os.name print mod_list sys = my_import('sys') print sys.version print mod_list From peter at engcorp.com Sat Jun 18 12:23:15 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:23:15 -0400 Subject: Shortcut to initialize variables In-Reply-To: <1119035246.014322.132790@g47g2000cwa.googlegroups.com> References: <1119032651.912256.319140@o13g2000cwo.googlegroups.com> <42b31929$1_2@newspeer2.tds.net> <1119035246.014322.132790@g47g2000cwa.googlegroups.com> Message-ID: Andrew wrote: > I'm writing a program that will take substitution and transposition > cipher texts and spit out plain text with no human input. So I suppose > I'll have dictionaries of digraphs and trigraphs too; for frequency > analysis. > Do you think this is to heavy of a project to learn the language? Not at all, provided you're somewhat expert in the domain already, and are just using it as a means to help learn Python. If you are learning both Python and how to break ciphers at the same time, I'd personally call it a "little" heavy... ;-) -Peter From steve at REMOVEMEcyber.com.au Thu Jun 9 01:03:44 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 09 Jun 2005 15:03:44 +1000 Subject: Incorrect number of arguments Message-ID: <42A7CDB0.4030703@REMOVEMEcyber.com.au> I'm trying to keep an open mind, but I am perplexed about something in Python that strikes me as a poor design. py> def func(a,b): py> print a,b py> func(1) Traceback (most recent call last): File "", line 1, in ? TypeError: func() takes exactly 2 arguments (1 given) Why is the exception raised by passing the wrong number of arguments a TypeError instead of a more specific exception? I'm asking because of a practical problem I had. I have written some test suites for a module, and wanted a test to ensure that the functions were accepting the correct number of arguments, eg if the specs say they take three arguments, that they actually do fail as advertised if you pass the wrong number of arguments. That should be simple stuff to do. Except that I have to distinguish between TypeErrors raised because of wrong argument counts, and TypeErrors raised inside the function. To add an extra layer of complication, the error string from the TypeError differs according to how many parameters were expected and how many were supplied, eg: func() takes exactly 2 arguments (1 given) func() takes at least 2 arguments (1 given) func() takes at most 1 argument (2 given) etc. I worked around this problem by predicting what error message to expect given N expected arguments and M supplied arguments. Yuck: this is a messy, inelegant, ugly hack :-( Thank goodness that functions are first class objects that support introspection :-) So, I'm wondering if there is a good reason why TypeError is generated instead of (say) ArgumentError, or if it is just a wart of the language for historical reasons? -- Steven. From peter at somewhere.com Thu Jun 2 03:41:47 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 02 Jun 2005 09:41:47 +0200 Subject: The need to put "self" in every method In-Reply-To: References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: Aahz schrieb: >>Because Python has no declarations there must be a different way to >>indicate in which category an identifier falls. [...] > Any objection to swiping this for the FAQ? (Probably with some minor > edits.) There is already a 'self' section (1.4.4) in the official Python FAQ. Looks like this has been forgotten. Perhaps it would be helpful to create a short version of the FAQ with the top most frequently asked questions/stumbling blocks/annoyances titled "top 10 things you always wanted to know about Python and didn't dare to ask" and post it weekly in this newsgroup :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From tjarko at dutlbcz.lr.tudelft.nl Thu Jun 23 10:28:42 2005 From: tjarko at dutlbcz.lr.tudelft.nl (Tjarko de Jong) Date: Thu, 23 Jun 2005 16:28:42 +0200 Subject: os.system(cmd) isn't working References: Message-ID: On Thu, 23 Jun 2005 00:02:55 -0400, Gregory Pi?ero wrote: >Hi guys, > >I'm trying to run this statement: > >os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' >"www.blendedtechnologies.com"') > >The goal is to have firefox open to that website. > >When I type r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' >"www.blendedtechnologies.com"' in the python interpreter I get: > >'"C:\\Program Files\\Mozilla Firefox\\firefox.exe" >"www.blendedtechnologies.com"' > >And when I copy this into my command prompt (less outermost ' ) >firefox opens up to that page like I would expect. However in python >nothing happens and I get exit status 1. > >I'm using Python 2.3 on Windows XP pro service pack 2. What is wrong with: os.startfile("www.blendedtechnologies.com") From sjmachin at lexicon.net Wed Jun 22 15:35:37 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 23 Jun 2005 05:35:37 +1000 Subject: oddness in shelve module In-Reply-To: <20050622124441.GV18460@rabbit.digitaltorque.ca> References: <42B8CFFF.5020101@lexicon.net> <20050622124441.GV18460@rabbit.digitaltorque.ca> Message-ID: <42B9BD89.9070607@lexicon.net> Michael P. Soulier wrote: >On 22/06/05 John Machin said: > > > >>AFAICT, wrong "it". The "item assignment" which is alleged not to be >>supported is of this form: an_object[some_key] = a_value >> >>I.e. "self.db" is the suspect, not "sample" >> >> > >Ah. Let me test that it is in fact being created properly then. I >expected an error more like, "object has no property db" in that case. > >Mike > > > sorry, perhaps I wasn't clear enough -- you seem to think I meant "self" has no attribute called "db". No, "self.db" exists, but it doesn't support the activity of assigning to an indexed item, like a dictionary. The interactive interpreter is your friend: >>> adict = {} >>> adict[3] = 4 >>> notlikeadict = 666 >>> notlikeadict[3] = 4 Traceback (most recent call last): File "", line 1, in ? TypeError: object does not support item assignment >>> This is the message that you are thinking about, the word is "attribute", not "property". >>> class Dummy: ... pass ... >>> x = Dummy() >>> x.dc Traceback (most recent call last): File "", line 1, in ? AttributeError: Dummy instance has no attribute 'dc' From mwm at mired.org Fri Jun 10 18:31:09 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 10 Jun 2005 17:31:09 -0500 Subject: Fast text display? References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> <863brr6xiw.fsf@guru.mired.org> <7xzmtzm9vi.fsf@ruckus.brouhaha.com> <86is0n57u4.fsf@guru.mired.org> <7xis0n9ei9.fsf@ruckus.brouhaha.com> Message-ID: <86br6d6dzm.fsf@guru.mired.org> Paul Rubin writes: >> > What about wxwidgets, which wxpython requires? >> >> If the package needs something and it's not installed, the package >> system will get it and install it. That's the *point* of a package >> system. > > Not really. A package system turns a software distro into a single > file you can install. In some instances a package depends other > packages and some package managers can then go chase down the > dependencies, but that's not characteristic of packages per se, and > while it's better than nothing, it's best to avoid it since the mechanism > breaks a lot. Tcl/tk is a boneheaded system in many ways, but it's > been very successful partly through the strategy of avoiding installation > hassle by minimizing dependencies. The crucial word in what I said was "system". You're right that packages per se don't handle dependencies. That's up to the package system. In my experience, the "breaks a lot" depends on the system you've got, and how you use it. I've spent a lot of time cursing RPMs because the dependency system does seem to break a lot. On the other hand, the only times I've had the FreeBSD package system break is when I was trying to force it to build things that weren't in the package system as supplied. >> The package system can be configured in a number of different ways. My >> configuration - with a broadband network connection - is to check the >> local disk cache, then download anything that's missing. You can >> preload the disk cache by doing "make fetch-recursive" if you >> want. You can preload the cache by hand if you want, but the package >> system is very picky about the version numbers of things it's trying >> to build, so that'd be a pain. > > Best is to have just one package that doesn't depend on any other > packages and doesn't need any further downloads, so once you've > installed it, you're done. This is the best solution for a naive user with a primitive package system. If either condition doesn't hold, it's no longer clear that that's the case. With a good package system, the dependencies will be handled invisibly and transparently, and the only way to find out that multiple packages were installed after you're done is by checking the installed packages database. If the user is advanced, they may prefer not to have multiple versions of the dependency installed, or that it be installed where it's available to other packages instead of just the installing package - or vice versa. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tim.golden at viacom-outdoor.co.uk Tue Jun 14 06:18:47 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Jun 2005 11:18:47 +0100 Subject: Where is Word? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8CE@vogbs009.gb.vo.local> [Guy Lateur] | Unfortunately, I need to open/edit a (temporary) text file | with Word, and | those are opened by default with UltraEdit (or Notepad or..). | Thanks for the | tip, though. | | Anything else? Do I need to read the registry? | | g OK, you have a couple of options (at least). Easiest, probably is to read the app paths from the registry. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths You're looking for winword.exe. An alternative is to use WMI to interrogate the Win32_Product classes and then to pick out the Software Elements etc. It's a bit messy, so I'd stick to the the AppPath approach if I were you. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From michele.simionato at gmail.com Sun Jun 12 11:12:14 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 Jun 2005 08:12:14 -0700 Subject: Code documentation tool similar to what Ruby (on Rails?) uses In-Reply-To: References: Message-ID: <1118589134.311882.5490@z14g2000cwz.googlegroups.com> What about doing it yourself? >>> import inspect, os >>> print "

%s
" % inspect.getsource(os.makedirs)
def makedirs(name, mode=0777):
    """makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.
    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.  This is
    recursive.

    """
    head, tail = path.split(name)
    if not tail:
        head, tail = path.split(head)
    if head and tail and not path.exists(head):
        makedirs(head, mode)
        if tail == curdir:           # xxx/newdir/. exists if
xxx/newdir exists
            return
    mkdir(name, mode)
Michele Simionato From kbilsted at hotmail.com Thu Jun 9 03:56:53 2005 From: kbilsted at hotmail.com (newseater) Date: 9 Jun 2005 00:56:53 -0700 Subject: multiple inheritance Message-ID: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> i don't know how to call methods of super classes when using multiple inheritance. I've looked on the net but with no result :( class a(object): def foo(self): print "a" class b(object): def foo(self): print "a" class c(a,b) def foo(self): super( ???? a).foo() super( ???? b).foo() r = c() r.foo() From zsolt-google1 at mailblocks.com Fri Jun 3 13:00:22 2005 From: zsolt-google1 at mailblocks.com (pythonUser_07) Date: 3 Jun 2005 10:00:22 -0700 Subject: Python Win32 and Condor In-Reply-To: <_rKdnRBkh8UXkwLfRVnyvA@giganews.com> References: <_rKdnRBkh8UXkwLfRVnyvA@giganews.com> Message-ID: <1117818022.493927.268560@o13g2000cwo.googlegroups.com> It's been a while since I've experimented with Condor, but it looks like " 'Access is denied.'", You might want to figure out what user the condor service is running as and log in as that user and try to run your code. From news at NOwillmcguganSPAM.com Fri Jun 10 10:38:00 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Fri, 10 Jun 2005 15:38:00 +0100 Subject: Dealing with marketing types... In-Reply-To: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <42a9a5c8$0$22628$da0feed9@news.zen.co.uk> flyingfred0 wrote: > A small software team (developers, leads and even the manager when he's > had time) has been using (wx)Python/PostgreSQL for over 2 years and > developed a successful 1.0 release of a client/server product. > > A marketing/product manager has brought in additional management and > "architecture" experts to propose moving the entire thing to a Java > (application server) platform for the next release. They want a > "scalable, enterprise solution" (though they don't really know what that > means) and are going crazy throwing around the Java buzzwords (not to > mention XML). > > The developers (including myself) are growing uneasy; the management is > continuing to push their requirements and ignore the engineers. I think > there's still hope, but I'm at a loss for ideas beyond pointing out the > success stories of Python and Zope and language comparisons between > Python and Java. > > What experiences have those in the Python community had in these kinds > of situations? Marketing types need a bandwagon to jump on. Point out that Google is used by Google, ILM and NASA. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From jheasly at guardnet.com Tue Jun 14 18:15:15 2005 From: jheasly at guardnet.com (John Heasly) Date: Tue, 14 Jun 2005 15:15:15 -0700 Subject: Cause for using objects? In-Reply-To: References: Message-ID: > John Heasly wrote: >> Given: >> [{"mugshot": "nw_gradspeaker4_0608", "width": 67.0, "height": >> 96.0}, \ >> {"mugshot": "nw_gradspeaker2_0608", "width": 67.0, "height": >> 96.0}, \ >> {"freehand": "b1.developreport.0614", "width": 154.0, "height": >> 210.0}, \ >> {"graphic": "bz_cafeparadiso_0613", "width": 493.0, "height": >> 341.0}] >> >> Return: >> {"mugshot1": "nw_gradspeaker4_0608", "mugshot1.width": 67.0, >> "mugshot1.height": 96.0,\ >> "mugshot2": "nw_gradspeaker2_0608", "mugshot2.width": 67.0, >> "mugshot2.height": 96.0, \ >> "freehand1": "b1.developreport.0614", "freehand1.width": 154.0, >> "freehand1.width": 210.0, \ >> "graphic1": "bz_cafeparadiso_0613", "graphic1.width": 493.0, >> "graphic1.height": 341.0} >> >> I'm trying to teach myself some OOP. Does grinding the Given above >> into >> the Return seem like a good candidate? > > If that's all you're doing, and you must use that output format, then > I'd say no. OOP is not a panacea. > > Now if you're going to *do* something with the return information, then > I would say yes. But in that case, don't use a single dict as a return, > use objects. > -- > Michael Hoffman Michael, Thanks. I'm thinking maybe list comprehension is a more appropriate tool. And I need to keep the return a single dict 'cause that's what the next step in the process expects. John From tim.golden at viacom-outdoor.co.uk Wed Jun 22 04:49:06 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 22 Jun 2005 09:49:06 +0100 Subject: Reading registry export files Message-ID: <9A28C052FF32734DACB0A288A3533991EBB91C@vogbs009.gb.vo.local> [George] | Hi, | | I have exported some registry-keys using Regedit to a number of | .reg-files. I can open these files using any text editor. Now | I wanted | to write a simple Python script to concatenate all these files to one | output file. (Please note that I'm a newbie). | | However, if I do something like: | | >>> f=open('c:/documents and settings/myname/desktop/test.reg','r') | >>> r=f.read() | >>> print r It's encoded with utf-16. You need to do something like this: import codecs f = codecs.open ("c:/temp/temp.reg", encoding="utf_16") # .reg files seems to have an initial BOM so need need to specify endianness text = f.read () f.close () print text TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dalke at dalkescientific.com Sun Jun 12 17:07:48 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 12 Jun 2005 21:07:48 GMT Subject: Code documentation tool similar to what Ruby (on Rails?) uses References: <1118589134.311882.5490@z14g2000cwz.googlegroups.com> Message-ID: Ksenia Marasanova responsded to Michele Simionato >> >>> print "
%s
" % inspect.getsource(os.makedirs) > > That's easy, thanks! I guess I'll submit a patch for Epydoc with the > functionality I've mentioned :) Before doing that, add a "cgi.escape()" to the text. Otherwise embedded [<>&] characters will be interpreted as HTML. Andrew dalke at dalkescientific.com From ods at strana.ru Thu Jun 30 11:07:36 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Thu, 30 Jun 2005 19:07:36 +0400 Subject: python commmand line params from c++ In-Reply-To: <1120143124.925422.290980@g44g2000cwa.googlegroups.com> References: <1120143124.925422.290980@g44g2000cwa.googlegroups.com> Message-ID: <20050630190736.4925654d@ods.pravda.rfn.ru> On 30 Jun 2005 07:52:04 -0700 "Wesley Henwood" wrote: > What is the proper way to pass command line parameters to a python > script called from C++? I'm tryng this: Have you tried PySys_SetArgv? > path = "c:\\someDir\\someScript.py param1 param2 param3"; > PyRun_SimpleFile(PyFile_AsFile( PyFile_FromString( path, "r")), > "someScript.py"); This code looks strange: you open file and create Python file object from its descriptor (PyFile_FromString), then get descripto back (PyFile_AsFile) to pass it to PyRun_SimpleFile. Why don't you just use C fopen function? > I'm getting a "format error someScript.py, line 1" when the code is > executed. > > Note: The strange appearannce of the 3 python function calls nested is > not a bug, but required to prevent a run-time error. I believe it's due to PyFile_FromString failing to open non-existent file. You must check return value of it. -- Denis S. Otkidach http://www.python.ru/ [ru] From hancock at anansispaceworks.com Wed Jun 15 13:27:15 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 15 Jun 2005 12:27:15 -0500 Subject: What is different with Python ? In-Reply-To: References: Message-ID: <200506151227.15350.hancock@anansispaceworks.com> On Tuesday 14 June 2005 02:12 pm, Andrew Dalke wrote: > Teaching kids is different than teaching adults. The > latter can often take bigger steps and start from a > sound understanding of logical and intuitive thought. > "Simple" for an adult is different than for a child. Of course, since children are vastly better at learning than adults, perhaps adults are stupid to do this. ;-) Quantum mechanics notwithstanding, I'm not sure there is a "bottom" "most-reduced" level of understanding. It's certainly not clear that it is relevant to programming. It is invariably true that a deeper understanding of the technology you use will improve your power of using it. So, I have no doubt that knowing C (and the bits-and-bytes approach to programming) will improve your performance as a programmer if you started with Python. Just as learning assembler surely made me a better C programmer. But I could write quite nice programs (nice enough for my needs at the time) in BASIC, and I certainly can in Python. Sometimes, you just don't care if your algorithm is ideal, or if "it will slow to a crawl when you deliver it to the customer". When did the "customer" get into this conversation? I mean, you're a neophyte who just learned how to program, and you're already flogging your services on the unsuspecting masses? In my experience, people first learn to program for their own needs, and it's only a long time later that somebody decides they want to become a professional. And maybe, when you're a pro, knowledge of machine details is really important. But an awful lot of people just want to putz around with the computer (or more accurately just want to solve their own problems using it). Surely, they don't need to know anything about quantum transitions, transistors, or malloc to do that. In fact, I find such stuff introduces a lot of noise in my thinking with Python. Awhile back I wanted to write a program that would take a title like "My fun trip to Europe, and a thousand and one things I saw there" and make a mnemonic file-name less than 32 characters long out of it, that obeyed simple naming conventions. I wanted it to spit something out like "trip_europe_1001_things", the way a human might name such a file. Well, first of all, with all the clutter involved in processing strings, I would never have tried this in C, it would've taken me a month! But my real point follows ... I used several different methods to go about squeezing down a title to get rid of "less important" words. For one, I wanted to know what the most common words were, so I could make a hit list of words to delete from titles. I did this using three or four titles from Project Gutenberg, and the Python interpretor. It took maybe fifteen minutes, and went something like this: s = open('cia_factbook', 'r').read() + open('pride_prej', 'r').read() + open('alice', 'r').read() words = s.split() unique_words = {} for word in words: unique_words[word] = unique_words.get(word, 0) + 1 word_freqs = unique_words.items() word_freqs.sort(lambda a,b: cmp(a[1],b[1])) for word, freq in word_freqs[:100]: print "%5d: %s" % (word, freq) This is, of course, totally brutal on my computer's memory allocation, because the source data is quite large. So, my C programming instincts would've encouraged me to do all kinds of optimizing. But why bother? Like I said, it took 15 minutes. Done. And that includes the programming time. I took a completely naive approach and it worked, so why should I bother making it hard for myself? Sure, in the profession of writing commercial, off-the-shelf word counting software to sell to "the customer", I should be truly ashamed, but who cares? I didn't even save this program to disk, I've just tried to rewrite it from memory here. The idea that one must learn assembler to learn C and in turn to learn Python strikes me as elitist or protectionist --- just another way to turn people away from programming. You should learn that stuff when it becomes obvious that you need it, not from the outset. And for many people, it simply may never be needed. Python is actually remarkably good at solving things in a nearly optimal way. This program also had another interesting property -- it couldn't have a rigid specification. There's no way to write one, it has to succeed intuitively, by producing output that is "mnemonic". But there's no way to unit test for that. ;-) So no amount of "deep understanding of what the machine is doing" would've really helped that much. I think there's an awful lot of programming out there that is like that -- the problem is about solving a problem with appropriate *ideas* not trying to find the most efficient *methods*. Often, it's not how efficiently I can do a thing that interests me, but whether it can be done at all. I don't think total reductionism is particularly useful for this. My thermodynamics professor once argued that, never having seen any, but only knowing the laws of physics and thermodynamics, that physicists would never have predicted the existence of *liquids*, let alone oceans, nucleic acids, and life forms. The formation of those things is still far beyond us on first-principles, and surely even if we do come to an understanding of such things, the particular biology of, say, flowering plants will be almost completely unaffected by such knowledge. Likewise, the creation and study of more complex ideas in software is unlikely to benefit much from assembler-level understanding of the machines on which it runs. It's simply getting too close to the problem --- assembly language problems have become so well understood, that they are becoming a domain for automated solution, which is what high-level programming is all about. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steven.bethard at gmail.com Sat Jun 4 19:36:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 17:36:57 -0600 Subject: method = Klass.othermethod considered PITA In-Reply-To: <87oeallp44.fsf@pobox.com> References: <87oeallp44.fsf@pobox.com> Message-ID: John J. Lee wrote: > It seems nice to do this > > class Klass: > > def _makeLoudNoise(self, *blah): > ... > > woof = _makeLoudNoise Out of curiosity, why do you want to do this? > 1. In derived classes, inheritance doesn't work right: > > >>>>class A: > ... def foo(s):print 'foo' > ... bar = foo > ... >>>>class B(A): > ... def foo(s):print 'moo' > ... >>>>b = B() >>>>b.bar() > foo Depends on what you mean by "work right". It does do what you asked it to do. You asked class A to store the "foo" object under the name "bar". When you create an instance of B, and ask for the "bar" attribute, it isn't found in class B, so Python looks to the parent class. The parent class, A, does have an object named "bar", so Python returns that. And that object is the same object that you asked be named bar, namely the "foo" function. If you want "bar" to be a function that *calls* the "foo" function, declare it as such: py> class A(object): ... def foo(self): ... print 'foo' ... def bar(self): ... return self.foo() ... py> class B(A): ... def foo(self): ... print 'moo' ... py> B().bar() moo > 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do > this. In Python 2.4: py> class A(object): ... def foo(self): ... print 'foo' ... bar = foo ... py> import pickle py> pickle.loads(pickle.dumps(A)).bar py> pickle.loads(pickle.dumps(A())).bar() foo Or maybe I misunderstand you? STeVe From ajikoe at gmail.com Sun Jun 19 17:45:37 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 19 Jun 2005 14:45:37 -0700 Subject: tab 2 into tab 4 ? In-Reply-To: References: <1119205602.922944.204990@g44g2000cwa.googlegroups.com> Message-ID: <1119217537.684103.276990@g14g2000cwa.googlegroups.com> Thanks it works! pujo From steve at REMOVETHIScyber.com.au Mon Jun 13 04:43:10 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 18:43:10 +1000 Subject: Dynamic Lists, or...? References: <1118511053.455332.231570@g44g2000cwa.googlegroups.com> Message-ID: On Sat, 11 Jun 2005 10:30:53 -0700, Lorn wrote: > I'm trying to figure out a way to create dynamic lists or possibly > antother solution for the following problem. I have multiple lines in a > text file (every line is the same format) that are iterated over and > which need to be compared to previous lines in the file in order to > perform some simple math. Each line contains 3 fileds: a descriptor and > two integers. Here is an example: > > rose, 1, 500 > lilac, 1, 300 > lilly, 1, 400 > rose, 0, 100 > > The idea is that the 0/1 values are there to let the program know > wether to add or subtract the second integer value for a specific > descriptor (flower in this case). So the program comes upon rose, adds > the 500 to an empty list, waits for the next appearance of the rose > descriptor and then (in this case) subtracts 100 from 500 and prints > the value. If the next rose was a 1 then it would have added 100. Why not just use a leading minus sign for the number if it is to be subtracted? > I'm uncertain on how to approach doing this though. My idea was to > somehow be able to create lists dynamically upon each new occurence of a > descriptor that currently has no list and then perform the calculations > from there. Unfortunately, the list of descriptors is potentially > infinte, so I'm unable to previously create lists with the descriptor > names. Could anyonw give any suggestions on how to best approach this > problem, hopefully I've been clear enough? Any help would be very gratly > appreciated. Use a dictionary: def update_dict(D, key, sign, value): """Update dictionary D item with key by adding or subtracting value.""" if not sign: value = -value x = D.get(key, 0) D[key] = x + value def split_line(s): """Split a string s into a tuple (key, sign, value), ignoring whitespace.""" L = s.split(",") return L[0].strip(), L[1].strip(), L[2].strip() # WARNING: insufficient error checking for real world use. Then call them like this: D = {} for line in sourcetext: key, sign, value = split_line(line) update_dict(D, key, sign, value) Oh, by the way... just in case this is homework, which I'm sure it isn't , I've deliberately left a teeny tiny bug in the code. You'll find the bug pretty much the first time you run it, and the fix is very simple. -- Steven. From reder at jpl.nasa.gov Fri Jun 24 13:22:13 2005 From: reder at jpl.nasa.gov (Leonard J. Reder) Date: Fri, 24 Jun 2005 10:22:13 -0700 Subject: Looking for Python Finite State Machine Implementations Message-ID: Hello, Although posted this a few weeks ago I still have gotten much feedback so I want to put this out again and see if the response gets a bit more interesting. I have been searching on the web for a while now for a specific Python implementation of an FSM. More specifically what I am looking for is a Python implementation of the so called UML Harel State Machine notion of a state machine. These are multi-threaded capable state machines with hierarchical representation capability (nested instances of state machines). They also have a unique conditional trigger symbol scheme for event representation and state machine transitions. I have seen some great implementations of simple FSMs and some interesting descriptions of how generator/yeild python keywords can be used. I think python has all the pieces to make a Heral implementation. Does anyone know of a Python implementation of FSM that comes close to this functionality? Any comments or recommendation for FSM packages that I could add this functionality to would also be welcome. I certainly think someone has done something that approaches this already. All replies are very much appreciated. If I get enough response I will post a summary of findings to this group. Thanks for reading this and any replies. Regards, Len -- ____________________________________________________ Leonard J. Reder Jet Propulsion Laboratory Interferometry Systems and Technology Section 383 Email: reder at huey.jpl.nasa.gov Phone (Voice): 818-354-3639 Phone (FAX): 818-354-4357 Mail Address: Mail Stop: 171-113 4800 Oak Grove Dr. Pasadena, CA. 91109 --------------------------------------------------- From Danielnord15 at yahoo.se Wed Jun 8 14:03:09 2005 From: Danielnord15 at yahoo.se (Svennglenn) Date: 8 Jun 2005 11:03:09 -0700 Subject: Make Tkinter child window active Message-ID: <1118253789.591161.88220@o13g2000cwo.googlegroups.com> How do i make a child window "active" like the root window? from Tkinter import * def open_child(): c = Toplevel(root) c.title("Child window") c.geometry('200x160+230+130') Label(c, text="Child window").grid() root = Tk() root.title("root window") Button(root, text="Open child window", command=open_child).grid() root.mainloop() When the child windows opens i would like it to be active like the root window, how can i easily do that? From simon.brunning at gmail.com Tue Jun 21 04:37:26 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 21 Jun 2005 09:37:26 +0100 Subject: py2exe problem In-Reply-To: References: Message-ID: <8c7f10c605062101372849e219@mail.gmail.com> On 6/21/05, Austin wrote: > I use py2exe to build python program to "aa.exe". > If this program has a bug, after closed this program, it will show > "aa.exe.log" in this folder. > Is there any ways to avoid this log file? It's probably best just have a try/except at the very top level of your app that logs the exception the way you want it logged. So, if you currently have: if __name__ == '__main__': main() you should instead have: if __name__ == '__main__': try: main() except exception: print >> mylog, exception # or whatever... You are free to ignore the exception altogether if you want to, but I promise you, you don't want to. ;-) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From chinook.nr at tds.net Sun Jun 26 03:22:13 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 26 Jun 2005 03:22:13 -0400 Subject: OO approach to decision sequence? References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> <42be2920.217477255@news.oz.net> Message-ID: <0001HW.BEE3CFE50019A9C6F0407550@news.gmane.org> On Sun, 26 Jun 2005 00:54:42 -0400, Bengt Richter wrote (in article <42be2920.217477255 at news.oz.net>): > On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek > wrote: > [...] >> >> Now, the same sort of behaviour where the "if type" testing has been >> replaced with code more in keeping with the OOP approach: >> >>>>> class C(object): >> ... def report(self): >> ... print "Found a C" >> ... >>>>> class D(object): >> ... def report(self): >> ... print "Found a D" >> ... >>>>> c = C() >>>>> d = D() >>>>> for item in (c, d): >> ... item.report() >> ... >> Found a C >> Found a D >>>>> >> > > The OP might want to consider factoring report into a base class, e.g., > > >>> class Base(object): > ... def art_name(self): > ... cname = type(self).__name__ > ... art = 'an'[:1+(cname.upper() in 'A E F H I L M N O R S X' or > ... len(cname)>1 and cname.upper()[0] in 'AEIOU')] > ... return art, cname > ... > >>> class A(Base): pass > ... > >>> class B(Base): pass > ... > >>> class F(Base): pass > ... > >>> class Foo(Base): pass > ... > >>> class U(Base): pass > ... > >>> class Uhuh(Base): pass > ... > >>> items = A(), B(), F(), Foo(), U(), Uhuh() > >>> for item in items: print 'Found %s %s' % item.art_name() > ... > Found an A > Found a B > Found an F > Found a Foo > Found a U > Found an Uhuh > > Returning info rather than printing to stdout allows you > to access and use it differently, e.g., > > >>> items[3].art_name() > ('a', 'Foo') > >>> items[3].art_name()[1] > 'Foo' > > (Don't know if the a/an logic is really general ;-) > > Regards, > Bengt Richter > Thanks Bengt, I'm just in the middle of refactoring my perfectly good top down utility to an OO approach. It's going to be a much more abstract and verbose animal, but that's OK because it's a learning exercise. To make use of the abstraction I'm providing for output options of either .csv or .html table, and I was approaching such with a separate output base class. I don't have the nuances of the language down yet, but you might say I'm taking an AO approach to OO refactoring??? :~) Streatching it a bit probably in calling processing and reporting the two main aspects of an AO approach, but it's fun and keeps my head busy. I've got a trial mockup of my decision sequence factory pattern working, so at least I'm making progress towards incomprehensible abstraction :<)) To avoid duplication I'm using code objects with my factory pattern to create applicable class methods for an instance. Yea, I'm overdoing it, but as I said it's a learning exercise. I'll study what you supplied in the morning to see if I understand. That and continue putting up firewood for next winter - tiring work in the 90 degree weather we're having in northern NE - especially at my age. Thanks again, Lee C From daniel.dittmar at sap.corp Fri Jun 17 04:36:17 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 17 Jun 2005 10:36:17 +0200 Subject: Multiple instances of a python program In-Reply-To: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> References: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> Message-ID: Rahul wrote: > Hi. > I am part of a group in my univ where we organize a programming > contest. In this contest we have a UDP based server. The server > simulates a game and each contestant is to develop a team of virtual > players. Each team is composed of 75 similar bots...i.e. governed by > the same logic. Thus the contestant submits a single copy of the client > and we instantiate the same program 75 times at the same time. > The problem is that while executables from C source files are small and > we can make 75 processes but we dont know what to do with python. > > If you have a python script and you want that 75 copies of the script > be run simultaneously how will you do it? Is there anyway to do so > without running 75 copies of the python interpreter simultaneously? > The technical way would be to use threads. Of course it could be that the rules of the game explicitly forbid that bots of a group communicate other than through the server. And it is easier to cheat there when you have only one Python program running. Daniel From phillip.watts at anvilcom.com Wed Jun 29 18:57:49 2005 From: phillip.watts at anvilcom.com (phil) Date: Wed, 29 Jun 2005 17:57:49 -0500 Subject: Boss wants me to program References: Message-ID: <42C3276D.4090104@anvilcom.com> > Wow! How about a sextant? > Simple device really. And a great practical demonstration of trigonometry. > Excellent idea, even found a few how to sites. We'll do it. Any others? I think I am going to have them build a shed because they need to get their hands on SOMETHING. But the geometry/time ratio is pretty poor. Anyone have any construction ideas: High geometry/low work would be great. From sjmachin at lexicon.net Sun Jun 12 23:47:53 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 13 Jun 2005 13:47:53 +1000 Subject: How to use 8bit character sets? In-Reply-To: References: Message-ID: <42ad01e9@news.eftel.com> copx wrote: > For some reason Python (on Windows) doesn't use the system's default > character set and that's a serious problem for me. > I need to process German textfiles (containing umlauts and other > 7bit > ASCII characters) and generally work with strings which need to be processed > using the local encoding (I need to display the text using a Tk-based GUI > for example). The only solution I managed to find was converting between > unicode and latin-1 all the time (the textfiles aren't unicode, the output > of the program isn't supposed to be unicode either). Everything worked fine > until I tried to run the program on a Windows 9x machine.. It seems that > Python on Win9x doesn't really support unicode (IIRC Win9x doesn't have real > unicode support so that's not suprising). > Is it possible to tell Python to use an 8bit charset (latin-1 in my case) > for textfile and string processing by default? > > copx 1. Your description of your problem is extremely vague. If you were to supply a minimal script that "works" [on what platform?? what version of Python??], with a description of what you understand by "works", and what happens differently when you run that script on a Win9x box [for what value(s) of x?? what version of Python??], we might be able to help you. N.B. somewhere near the top of the script you should have something like: import sys print "Python version:", sys.version print "platform:", sys.platform print "default encoding:", sys.getdefaultencoding() try: print "Windows version:", sys.getwindowsversion() except AttributeError: print "sys.getwindowsversion not available" 2. You should read this: http://www.catb.org/~esr/faqs/smart-questions.html 3. You should not rely on a crutch like a default encoding, especially one obtained by a kludge like sitecustomize.py. If your app expects to receive data in encoding x and send data in encoding y, these facts are properties of the application and the data, NOT the box you are running on. If you had a requirement to read MacCyrillic from a Classic Mac and write KOI8 for consumption on a Windows PC, you should be able to do it on a SPARC Solaris box in Timbuktu or Walla Walla, Wa., without having to fiddle with site-wide configuration. 4. AFAIK, support for Unicode is provided by Python with no assistance from the operating system. The multitudinous deficiencies in Win9x should have no bearing on the problem. Have you tried to run your program on a Win2K or WinXP box? HTH, John From roccomoretti at hotpop.com Wed Jun 8 14:41:16 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 08 Jun 2005 13:41:16 -0500 Subject: Annoying behaviour of the != operator In-Reply-To: <1118255048.849018.259500@g14g2000cwa.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> Message-ID: Jordan Rastrick wrote: > Unless someone can explain some sort of problem that arises from having > != take advantage of a __eq__ method where present, I'd suggest that it > should do so in Python 2.5. If you're serious about this proposal, please formalize it in a PEP. Things to specify: How extensive are these changes? Is it just !=, or if __eq__ is not defined, will it be equal to "not __ne__()"? __lt__/__gt__? __le__/__ge__? Do you simulate __le__ with '__lt__ or __eq__'? How about __lt__ with '__le__ and __ne__'? > I'd be surprised if such a change broke so much as a single line of > existing Python code. Well, since it currently raises an error when __ne__ is not defined, I'd say your right on that account. The only corner case is when people would rely on 'a != b' to be implicitly translated to 'b != a'. If 'a != b' gets translated to 'not a == b', this may change semantics if the two are not equivalent. From fredrik.johansson at gmail.com Mon Jun 27 15:09:02 2005 From: fredrik.johansson at gmail.com (Fredrik Johansson) Date: Mon, 27 Jun 2005 21:09:02 +0200 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: <3d0cebfb05062712092e21b3e6@mail.gmail.com> On 6/27/05, Reinhold Birkenfeld wrote: > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? First of all, numeric/numarray, obviously! I'd also like to see wxPython, pygame and SciPy, but these may be too heavy-weight. A good distribution system for widely used packages may be a better solution than including everything in the standard library. > For my part, ctypes seems like a suggestion to start with. I think ctypes simply *must* go in there sooner later. My experience dealing with binary data in Python is that it's a pain in the neck compared to C, and the more machine-like behaviour and elegant code you want, the slower it gets. I have refrained from using ctypes for a number of reasons, but I would probably use it if it was in the standard library. -- Fredrik Johansson From fphsml at gmail.com Mon Jun 27 20:47:23 2005 From: fphsml at gmail.com (James) Date: 27 Jun 2005 17:47:23 -0700 Subject: Boss wants me to program In-Reply-To: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: <1119919643.539404.281910@g44g2000cwa.googlegroups.com> xeys_00 at yahoo.com wrote: > I'm a manager where I work(one of the cogs in a food service company). > The boss needed one of us to become the "tech guy", and part of that is > writing small windows programs for the office. He wants the development > work done in house, and he knows I am in school for a CS minor. I know > basic C++(Part 2 of that is in the fall), and I will be taking Java 1 > in the fall also. What is the easiest way for me to make windows > programs that will do basic things like(Inventory, Menu Management, > etc...)? I have heard visual basic is where it's at. I want to keep an > open mind though, so I am wondering if python could be an option. The > programs have > no speed requirement. But they must be pretty, and not confuse my > boss. Plus he wants well documented help for each function. I asked the > windows programming group, but I thought I would ask here also. Thanks. > > Xeys Since you already know a bit of C++, you can try C++ Builder 6 from Borland. It's old but you may even get the Personal Edition for free if you download the Nokia toolkit. Personal edition doesn't have database components included however. C++ is not an easy language beyond class room use but C++ Builder is about as easy as it can be made. You don't need to truly understand C++ and OOP to get by with some simple Windows apps in C++ Builder. And most of what you learn about VCL (GUI library in C++ Builder) will more or less translate to other toolkits. Stay off VC++. You need some expertise to use it. C++.NET may be OK for you too. C# will also be natural to someone with C++ know how. Visual Studio.NET(C# and C++.NET in your case) and Delphi are other good options. SharpDevelop (.NET) is free and should be very easy to understand for beginners. You can also look at the (free trial) beta release of Visual Studio 2005 if you want something a little more sophisticated but SharpDevelop is probably better to start with (not too many features to overwhelm). Boo is a Python like language that works with .NET and is well integrated with SharpDevelop. Java GUI toolkits (Swing and SWT) use sophisticated OOP designs and are very complex. Not easy for beginners to wrap their minds around. Non professionals should stay off them. Your Java 1 will not prepare you enough for them. While Python is a wonderful language, GUI Builders (Boa, PythonCard, Glade etc) available for it are nowhere close in maturity compared to the ones I mentioned above. So stay off Python for GUIs for now. You can come back once you have understood programming better. As for Visual Basic, version 6 is very easy to learn and use for basic applications but is no longer sold (other than used copies at eBay). The new VB.NET is a bit more sophisticated. You will be better off with C# rather than VB.NET (both are essentially the same) here since it will be a more familiar syntax for you. The best advice I can give is to pick a language/IDE with which you can get some live help (friend/neighbor/colleage) who can hold your hands for a while. From idontneednostinkinid at yahoo.com Wed Jun 1 16:31:21 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 13:31:21 -0700 Subject: bug with isinstance() ? Message-ID: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> Under certain circumstances isinstance() seems to return incorrect value for me. I'm using Python 2.3 (latest from Debian's unstable). Here's a sample program... the multi-module nature of the code is key. === test.py === class Foo: pass def test(): from test2 import make_me_a_foo foo = make_me_a_foo() if isinstance(foo, Foo): print "is a Foo" else: print "is NOT a Foo!" if __name__ == "__main__": test() === test2.py === from test import Foo def make_me_a_foo(): return Foo() --8<-- When I run "python test.py", I get "is NOT a Foo!", when the object clearly IS a Foo! Am I missing something, or is this a bug? From steve at REMOVETHIScyber.com.au Sun Jun 12 11:26:47 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 01:26:47 +1000 Subject: case/switch statement? References: Message-ID: On Sun, 12 Jun 2005 08:33:32 -0400, Dan Sommers wrote: >> I've never understood why something like: > >> if x = 5: >> do_this >> elif x = 6: >> do_that >> else: >> do_something_else > >> is supposed to be "bad", but > >> case of: >> x = 5: >> do_this >> x = 6: >> do_that >> otherwise: >> do_something_else > >> is supposed to be "good". > > In the truly general case, I agree. > > But twist your second example slightly into this: > > case x of: > 5: do_this > 6: do_that > otherwise: do_something_else > > and the goodness is obvious: we're choosing functionality based on the > value of x, so it's nice to see x in only one place. Yes. But now change the references to do_this and do_that to ten lines of in-line code each, and add another dozen similar tests for 7, 8, etc, and by the time you get to the third page you've forgotten what the variable being tested is. Now, you or I will obviously never write such hard-to-maintain code , but some people will, and we'll have to maintain it. It isn't at all obvious that case statements are more readable than if...elif, nor are they necessarily faster at runtime, although they can be. Against that occasional optimization and sometimes increase in readability, you have disadvantages: more keywords, implicit tests instead of explicit, new syntax to learn. >> Arguably, a case statement *might* allow the compiler to optimize the >> code, maybe, sometimes. But in general, no such optimization is >> possible, so a case statement is merely equivalent to a series of >> if...elif... statements. > > I agree that in general, optimizing a series of if/elif statements is > tricky, but your first example is very command and exactly the kind of > code that a good optimizer *can* optimize (as long as "x" isn't > pathological in the sense that evaluating it also changes its value or > has other side effects). Yes. But that's also the sort of optimization that could be done for if...elif as well, without introducing new syntax and new reserved words. Case statements seem to be one of those things that Python newbies from other languages automatically ask for, but the case for introducing case (pun intended) doesn't appear to be strong enough to justify the amount of verbiage spent on it. And on that note, I will say no more on the subject. -- Steven. From philippe at philippecmartin.com Sun Jun 26 10:56:21 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sun, 26 Jun 2005 14:56:21 GMT Subject: Big problem fetching members from dynamically loaded module References: Message-ID: > My French is mostly read-only, so let me rephrase: Thank you :-) > from module import *, try ... except, eval(), exec all work together to > make your program harder to understand and more likely to fail in obscure > ways. What would you suggest then, I just want my code to 1) be sturdy 2) some of the modules might not be there depending on the configuration, and I want their members in the menus if they are installed. If there is a cleaner way, I'm ready to try it. > eval("BC", self.m_process_global, self.m_process_local) > > to ensure that eval() and exec share the same namespace. > Generally speaking, I would prefer (I hope I got that right) That was it, thank you! > > module = __import__("package.module", globals(), locals(), ["module"]) > members = inspect.getmembers(module) > > Members of the module would then be accessed via getattr(): > > member = getattr(module, member_name) > I will study that. Many thanks Philippe Peter Otten wrote: > Philippe C. Martin wrote: > >> OK Peter, first of all thanks. >> >> You seem to be German and although I leave in the states, I'm French and >> your english is clearly far more advanced than mine: I have yet to >> understand a few of your comments ;-) > > My French is mostly read-only, so let me rephrase: > > from module import *, try ... except, eval(), exec all work together to > make your program harder to understand and more likely to fail in obscure > ways. > >>> Care to provide the traceback? >> >> Traceback (most recent call last): >> File "SC_Shell.py", line 1095, in ? >> l_d = SC_Shell() >> File "SC_Shell.py", line 326, in __init__ >> self.__Make_Menu_Area() >> File "SC_Shell.py", line 828, in __Make_Menu_Area >> l = inspect.getmembers(eval(c)) >> File "", line 0, in ? >> NameError: name 'BC' is not defined > > That traceback and the code you posted do not fit together. So back to > square one. > > Staring at the code you posted, I think one thing you could try would be > to modify the eval() to > > eval("BC",?self.m_process_global, self.m_process_local) > > to ensure that eval() and exec share the same namespace. > Generally speaking, I would prefer (I hope I got that right) > > module = __import__("package.module", globals(), locals(), ["module"]) > members = inspect.getmembers(module) > > Members of the module would then be accessed via getattr(): > > member = getattr(module, member_name) > > Peter From tjreedy at udel.edu Fri Jun 3 03:44:33 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Jun 2005 03:44:33 -0400 Subject: optparse.py: FutureWarning error References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> Message-ID: "kosuke" wrote in message news:1117765604.103092.154190 at g47g2000cwa.googlegroups.com... > man python --- > > COMMAND LINE OPTIONS This should REALLY be on the doc page of the Python site. I remember asking for this about 7 years ago and being ridiculed for only having Windows. It is really time to stop pretending that the only Python users that count have a *nix on their desk. Terry J. Reedy From sjmachin at lexicon.net Wed Jun 1 17:42:46 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 07:42:46 +1000 Subject: Calculating Inflation, retirement and cost of living adjustments over 30 years In-Reply-To: References: Message-ID: <429e2bd5$1@news.eftel.com> rbt wrote: > Is this mathematically correct? > > > def inflation(): > start = int(str.strip(raw_input("How much money do you need each > month at the start of retirement: "))) > inflation = float(str.strip(raw_input("What will inflation average > over the next 30 years(.03, .04, etc): "))) > > for x in xrange(30): > start = start*inflation+start > print start > > inflation() The *arithmetic* is tedious but "correct" -- we won't concern ourselves with rounding errors here. The *mathematics* might be better expressed as required = start * (1.0 + inflation_rate_per_period) ** number_of_periods From bdesth.quelquechose at free.quelquepart.fr Wed Jun 29 17:38:39 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 29 Jun 2005 23:38:39 +0200 Subject: Inheriting from object In-Reply-To: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> Message-ID: <42c30ea5$0$31301$636a15ce@news.free.fr> Fuzzyman a ?crit : > Hello, > > To create a classic (old style) class, I write : > > class foo: > pass > > To do the equivalent as a new style class, I write : > > class foo(object): > pass > > *Should* I in fact write : > > class foo(object): > def __init__(self, *args, **kwargs): > object.__init__(self) > > ? Nope. > Also, can anyone explain any tangible benefit of inheriting from > object, when not explicitly using any features of new style classes ? old-style classes are deprecated. They are still in the language (for how much time ?) for compatibility reasons, but they won't last forever. That should be a good enough reason to avoid them, given that the only thing you have to do is to inherit from object... From mwm at mired.org Fri Jun 10 19:49:49 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 10 Jun 2005 18:49:49 -0500 Subject: Start application & continue after app exits References: <9G3qe.15862$TR5.692@news.edisontel.com> Message-ID: <86y89h4vs2.fsf@guru.mired.org> "Guy Lateur" writes: > To be honest, I don't really understand what it means to have the same file > open for writing by several processes. You don't want to modify data which > is already being modified by someone else, do you? I mean, how do you > determine what changes to apply first, and to what version? Or is the file > just constantly being overwritten on a first-come-first-served basis? Unix believes (well, it used to...) that the programmer should be given all the rope they feel they need. If that means they get enough rope to hang themselves, so be it. That means that when two processes write to a file, what they write will be written to the file in the order the writes occur. So a later process can well overwrite what an earlier process wrote. On the other hand, it doesn't have to do that. If the file being written has a binary record structure of some kind, then it's perfectly reasonable for two processes to update different records in the file "at the same time". utmp and lastlog are standard Unix accounting files where this happens every time someone logs in. Requiring each user that logged in to wait until all the previous login processes had finished and closed the file would unnecessarily delay a user logging in to a multi-user system. I've done this kind of thing with dbm files, but later recanted and used a real database. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From benyang22 at yahoo.com Thu Jun 16 14:57:52 2005 From: benyang22 at yahoo.com (benyang22 at yahoo.com) Date: 16 Jun 2005 11:57:52 -0700 Subject: whos -- a function listing objects Message-ID: <1118948272.051392.323240@g14g2000cwa.googlegroups.com> I have been a long time Matlab user. I Python, I miss Matlab's whos command. So I have written a little utility whos.py, which can be downloaded here: http://beluga.eos.ubc.ca/~tang/softwares/python/ Here is the doc string: # Before using whos, do: execfile('whos.py') #=== EXAMPLES === # to see a list of all objects in the global scope whos() # to see a list of functions whos('f') # to see a list of variables (also their values) whos('v') # to see a list of Numeric array whos('a') # to see a list of variables in module os import os whos('v', module=os) # to see a list of variables whose name contains 'path' whos('v', sstr='path') # to see a list of variables whose name contains 'path' (case insensitive) whos('v', sstr='path', casesen=0) Argument what can be one of the following: A -- all a -- array f -- function m -- module v -- variable From sutram at gmail.com Sun Jun 5 23:05:05 2005 From: sutram at gmail.com (Mahesh) Date: 5 Jun 2005 20:05:05 -0700 Subject: urllib2 pinger : insight as to use, cause of hang-up? In-Reply-To: References: Message-ID: <1118027105.196810.127490@o13g2000cwo.googlegroups.com> Timing it out will probably solve it. From d at e.f Sun Jun 19 22:35:50 2005 From: d at e.f (D H) Date: Sun, 19 Jun 2005 21:35:50 -0500 Subject: calling subclass constructor question In-Reply-To: References: Message-ID: <2LCdnctEYLcXtivfRVn-rA@comcast.com> In Han Kang wrote: > So each of the sub classes plots a different type of graph. The > superclass defines methods that are the same for all the plots. I want > to be able to pick some points and be able to generate a more plots. > What I was wondering if I could define in a method in the superclass of > an object the ability to make a brand new subclass (new plot). So > basically, one plot makes another plot, but it'd be nice if i could put > all the code in the superclass. Right, I agree with Steven, that you are probably wanting something like the factory pattern. Here's something modified from Steven's example more like what you are asking for: class Plot(object): #you need to subclass object to get __subclasses__ @staticmethod def getplot(name): return [plot for plot in Plot.__subclasses__() if plot.__name__ == name][0]() class LinePlot(Plot): pass class BarGraph(Plot): pass lp = Plot.getplot("LinePlot") bar = Plot.getplot("BarGraph") See also: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/86900 From jepler at unpythonic.net Sat Jun 11 09:04:22 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 11 Jun 2005 08:04:22 -0500 Subject: Hiding X windows In-Reply-To: References: Message-ID: <20050611130419.GA17037@unpythonic.net> You may want to use a standalone program to do this. "xwit" has the ability to iconify a window which can be selected in a variety of ways. http://hpux.connect.org.uk/hppd/hpux/X11/Misc/xwit-1.0/man.html There's a direct Python interface to the X protocol in python-xlib. You could re-write the common function "Select_Window()" from dsimple.c in the X source distribution. One (old) copy is here: http://ftp.rge.com/pub/X/X11R6.4/xc/programs/xwininfo/dsimple.c Having done that, I'm not entirely sure how you proceed to hide the window. You might follow the directions in the ICCCM on how to iconify or withdraw a window (http://tronche.com/gui/x/icccm/sec-4.html#s-4.1.4), or you might follow the EWMH document (http://standards.freedesktop.org/wm-spec/wm-spec-1.4.html#id2507242) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From me at privacy.net Wed Jun 29 21:31:06 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 29 Jun 2005 21:31:06 -0400 Subject: Help please: How to assign an object name at runtime References: <1120092944.710361.309310@g44g2000cwa.googlegroups.com> Message-ID: On 29 Jun 2005 17:55:44 -0700, "c0chong at gmail.com" wrote: > The following is the input line of the file: SoftDict-.csv: > ca1017,GRPHScriptSet,ADD/REM,Adobe Acrobat 4.0=2005/06/14 > I expected an instance of Machine() to be created with a name ca1017. > Instead, an object is assigned to l[0] named: > <__main__.Machine instance at 0x01282558> > ----------------------------- > Here is my code: [ ... ] machines = {} > for line in FileList('SoftDict-.csv'): # Treat .csv as a text > if len(line)==1: break # Quit processing; end of file > l=line.split(',')# Split the line into constituent parts Delete this: > l[0]=Machine() # Create a Machine() object named: ca1017 And add this in its place: machines[l[0]] = Machine() This will create a dictionary that maps the string 'ca1017' to a newly created Machine object. HTH, Dan -- Dan Sommers From lee_cullens at mac.com Wed Jun 8 09:33:17 2005 From: lee_cullens at mac.com (Lee Cullens) Date: Wed, 8 Jun 2005 09:33:17 -0400 Subject: OO re-factoring (was Pythonese/Efficiency/Generalese critique [on Tutor]) In-Reply-To: References: Message-ID: <37C75270-7649-46F8-A5B4-2E8CE5D870F6@mac.com> Than Thanks for the reply Dan, Yes, my take was flawed, and a number of individuals on the Tutor list pointed me in the right direction. Thanks again, Lee C > From: Dan Sommers > Date: June 8, 2005 8:22:39 AM EDT > To: python-list at python.org > Subject: Re: OO re-factoring (was Pythonese/Efficiency/Generalese > critique [on Tutor]) > > > On Wed, 8 Jun 2005 00:52:06 -0400, > Lee Cullens wrote: > > >> ... My thinking is that class/subclass method instances would replace >> the recursive functions approach, but have as yet not formed the >> coding in my mind. >> > > I don't remember the original post, but methods and recursion are > *not* > mutually exclusive (e.g., an Integer class with a factorial method, > or a > binary tree class whose nodes are also binary trees). > > Regards, > Dan > > -- > Dan Sommers > -------------- next part -------------- An HTML attachment was scrubbed... URL: From roccomoretti at hotpop.com Wed Jun 1 17:54:09 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 01 Jun 2005 16:54:09 -0500 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> Message-ID: Skip Montanaro wrote: > Thomas> The Python world lacks the phenomenally successful development > Thomas> models enjoyed by the now ancient Turbo Pascal, Delphi and > Thomas> Visual Basic. > Thomas> AND > Thomas> If the likes of Visual Basic can have it, then it becomes > Thomas> really, *really* hard to convince the world that Python is a > Thomas> serious, professional system. > > Remember, in the open source community we all pretty much just scratch our > itches. It's worth mentioning that although we all scratch our own itches, not everyone can make their own benzocaine lotion. I.e. we all have wants and desires, but for most people the time/expertise available to them is insufficient to satisfy those needs. So answering "You know what would be great ..." with "Scratch your own itch!" is presumptuous, bordering on rude. That said, you're right: > Given that for the most part nobody in the Python community has a > handle on any other Python person's paycheck, it's unlikely that enough of > the community ... Given that we're all volunteers here (or at least volunteers w/r/t random usenet posters) anyone *demanding* something out of the Python community is vastly overstepping their position. But that doesn't mean they can't wish for it politely. Random usenet posters willing to throw money at the problem, though, are another thing all together ... From newsgroups at jhrothjr.com Fri Jun 24 09:47:43 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 24 Jun 2005 07:47:43 -0600 Subject: Two questions on lambda: References: Message-ID: <11bo3o0fvdus40c@news.supernews.com> "Xavier D?coret" wrote in message news:d9gvl9$lo2$1 at trompette.imag.fr... > Hi, > > I cannot find the way to do generic lambda functions using the lambda > syntax in python. I am probably missing a point. You are. Lambda is restricted to a _single expression_. Your first example is a statement, not an expression. Your second example attempts to do an assignment in the body of a lambda (although that's not what the code actually says) and assignment is a statement, not an expression. Lambda is intended for very simple, one line functions. It's also likely to go away in Python 3.0. Python, for better or worse, is a multi-paradigm language combining the object and procedural paradigms. It is not, and it is not intended to be, a functional style language. John Roth > > For example, the code > > # f = lambda : print "hello" > # f() > > does not compile, although: > > # def f(): > # print "hello" > # f() > > does compile. Is there a particular syntax for lambda that I am missing or > is it simply limited and I cannot do what I want with lambda. > > In the same spirit, how can I do to compute intermediary values in the > body of a lambda function. Let's say (dummy example): > > f = lambda x : y=x*x,y+y > > > In languages like Caml, you can do: > > let f = function x -> let y=x*x in y+y;; > > Does the lambda : syntax in python allow for the same kind of constructs? > > Thanks. From steve at holdenweb.com Mon Jun 6 22:43:12 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Jun 2005 22:43:12 -0400 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: max wrote: > Steven D'Aprano wrote in > news:pan.2005.06.06.16.52.03.904880 at REMOVETHIScyber.com.au: > > >>On Mon, 06 Jun 2005 16:12:18 +0000, max wrote: >> >> >>>This is one thing that bothers me about the gpl. It essentially >>>tries to create 'code as a legal entity'. That is, it gives >>>rights not to the creator of some code, but to the code itself. >> >>Can you please show me where in the GPL it gives rights to the >>code itself? Because, frankly, I think you are mistaken. >> >>Of course, I might be wrong in this instance, and I always >>welcome corrections. >> >> >>>For me, the fact >>>that corporations are considered people by the law is >>>ridiculous. >> >>Ridiculous? I don't think so. Take, for example, Acme Inc. Acme >>purchases a new factory. Who owns the factory? The CEO? The >>Chairperson of the Board of Directors? Split in equal shares >>between all the directors? Split between all the thousands of >>shareholders? Society has to decide between these methods. >> >>(Of course, society can choose to hedge its bets by creating >>multiple entities that use different rules, such as partnerships, >>trusts, public corporations, limited corporations, etc.) >> >>None of these alternatives are *wrong*, but they all have various >>disadvantages. The legal fiction that corporations are legally >>persons is a work-around for these disadvantages, and it works >>quite well in many circumstances. To call it ridiculous is, well, >>ridiculous. Ownership is a legal fiction in any case, so it is no >>more ridiculous to say that a collective entity such as a >>corporation owns property than it is to say that an individual >>being owns property. >> >>However, if you wanted to argue that giving corporations all the >>privileges of legal personhood with none of the responsibilities >>caused more harm than good, I would agree with you. I take it >>you've seen "The Corporation"? >> > > > I haven't seen "The Corporation", but yes, I was reaching for the > priviledges/responsibilities balance. > > >>>Using a license that ends up doing the same thing with code >>>leaves a bad taste in my mouth. >> >>Of course you are free to use some other licence. But without >>evidence, I do not accept that the GPL attempts to give rights to >>code. >> >> > > Perhaps 'attempts' is too strong a word. Maybe 'ends up giving' would > help my argument more. The best example I can come up with at the > moment is programmer A releases a project under the gpl. Programmer B > makes a substantial contribution to the project, which pA reads > through and accepts. Later, pA decides that he would like to release > the project under a more liberal license. To me, whether he legally > can under the gpl is a very murky subject, as pB might not agree, and > pA, having looked through/thought about pB's contribution might have > some trouble proving that he implemented any matching functionality > without referencing pB's earlier contribution, which if he did > reference it(even by memory), would presumably require him to continue > using the gpl. > > I guess my argument is that with multiple contributors, the gpl, in > comparison to say, a BSD style license, grants power to the code. If 3 > people work on a gpl project, they must agree to any changes. If 3 > people work on a BSD style project, they each can do whatever the hell > they like with the code. So, in my opinion, the gpl ends up giving > perhaps not rights, but certainly power, to the actual code base. > That argument is bogus if you do what the PSF is attempting to do, which is to ask contributors to grant the PSF rights to redistribute under its chosen license. After that you can take your contribution and publish it in a book, republish it under a different license, whatever. The fact that the PSF has a license to redistribute your contribution can't be rescinded by your subsequently changing the license you use to distribute the software. How do you manage to equate "must agree to any changes" with "granting power to the code"? > > > Based on the limited coherence of this answer I probably need to think > about it somemore, > max > :-) Licensing is unfortunately less trivial that we would like it to be. the-road-t-hell-is-paved-with-good-intentions-ly y'rs - steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From http Sun Jun 12 14:15:35 2005 From: http (Paul Rubin) Date: 12 Jun 2005 11:15:35 -0700 Subject: Scaling down (was Re: Dealing with marketing types...) References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <7x7jh0l5kg.fsf@ruckus.brouhaha.com> <7xwtp09jh3.fsf@ruckus.brouhaha.com> Message-ID: <7xhdg3xwzc.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > So what? I think you're missing the real point of the article: using > LAMP scales *DOWN* in a way that enterprise systems don't. Getting your > first prototype up and running is far more important than sheer > scalability, There comes a day when your first prototype can no longer handle the traffic. The question then is how do you deal with that. > and LAMP does have many mechanisms to obtain scalability when it's > needed. LAMP seems to have no solution other than scaling (i.e. blowing more money on hardware and colo space). One really gets the impression that a more thoughtful design could handle the traffic without needing to scale the hardware. From mtammerman at gmail.com Wed Jun 8 04:12:52 2005 From: mtammerman at gmail.com (Mike Tammerman) Date: 8 Jun 2005 01:12:52 -0700 Subject: Garbage collection with QT In-Reply-To: <42a683b0$1@news.vo.lu> References: <42a683b0$1@news.vo.lu> Message-ID: <1118218372.094185.185890@g14g2000cwa.googlegroups.com> Not all leakage problems caused by qt or python. There is a wrapping layer between Qt and Python provided by SIP. Therefore, SIP may cause leakages. Also PyQt had a paintCell memory leakage problem several months ago. If you're using an old snapshot of PyQt or SIP, that would be a problem. Try using the latest snapshots. Also mention your versions and problems to the PyKDE mailinglist, it could be more helpful. If you want to delete C++ objects in Qt, consider using QObject.deleteLater() method. IMHO, this won't help. Mike From thecollector.2k at gmail.com Thu Jun 30 14:48:31 2005 From: thecollector.2k at gmail.com (The Collector) Date: 30 Jun 2005 11:48:31 -0700 Subject: Controlling WinAMP (WM_COPYDATA problem) Message-ID: <1120157311.921062.21570@o13g2000cwo.googlegroups.com> Hi, I've been looking for almost two full days now to get full control of WinAMP using python. Simple play/stop functions are no problem. It's the WM_COPYDATA that's used by IPC_PLAYFILE (=add a file to the playlist) that's giving me troubles big time! My latest test code: --------------------------------------- from win32gui import FindWindow from win32api import SendMessage import struct import array WM_USER = 0x400 # WM-ID for a WinAMP user command WM_COPYDATA = 0x004A # WM-ID for a WinAMP copyData command IPC_PLAYFILE = 100 # WM-ID for WinAMP to add item to WinAMP playlist hWnd = FindWindow('Winamp v1.x', None) # Find the WinAMP window-handle (receiver) def packData( dwData, lpData ): lpData_ad = array.array('c', lpData).buffer_info()[0] # calculate the pointer address for the lpData cbData = array.array('c', lpData).buffer_info()[1] # calculate the length of the lpData (=cbData) cds = struct.pack("IIP", dwData, cbData, lpData_ad) # pack dwData, cbData and lpData into a copyDataStruct cds_ad = array.array('c', cds).buffer_info()[0] # find the pointer address of the copyDataStruct return cds_ad # return the copyDataStruct pointer-address def addItemToPlaylist( item ): uInt = IPC_PLAYFILE # ID for adding an item to the WinAMP playlist wParam = 0 # Not defined (leave at zero) lParam = packData( uInt, item ) # create the copyDataStruct-pointer SendMessage( hWnd, uInt, wParam, lParam ) # Send the data to the WinAMP window file = r"C:\Party Animals - Atomic.mp3" addItemToPlaylist( file ) --------------------------------------- the code runs fine, no errors, but nothing happens!! I've already had a test in which garbage was added to the playlist, but that's it... Anybody, any ideas on the problem? tnx... From d at e.f Fri Jun 24 10:17:00 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 09:17:00 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <7MSdnead08J-iCHfRVn-1g@comcast.com> Joseph Garvin wrote: > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? You can try out new features yourself now using various python extensions or descendants: http://livelogix.net/logix/ - macros, no statement/expression distinction http://students.ceid.upatras.gr/~sxanth/pyc/ - assignments are expressions, you can try other features never added python like a ternary operator (x ? true action:false action) http://boo.codehaus.org/ assignments are expressions, macros, static typing, no more "self" required, ... From peter at engcorp.com Thu Jun 9 14:46:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 14:46:29 -0400 Subject: Any way to not create .pyc files? In-Reply-To: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <8cGdnaHABLhlEzXfRVn-oQ@powergate.ca> Lonnie Princehouse wrote: > We have a site-specific package installed on a network drive[1]. When > anyone with write access imports this package, the network drive gets > spammed with .pyc files. > > If these .pyc files exist, they appear to cause problems when other > users' Python interpreters use them instead of the .py files. (I know, > they *should* work, but they don't). You didn't really describe the nature of the problem. Perhaps the whole .pyc thing is a bit of a red herring, and the real problem lies elsewhere? What are the actual symptoms of your problem? From davecook at nowhere.net Sun Jun 19 12:54:31 2005 From: davecook at nowhere.net (Dave Cook) Date: Sun, 19 Jun 2005 16:54:31 GMT Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> <1119111817.610572.73580@g14g2000cwa.googlegroups.com> Message-ID: On 2005-06-18, cpunerd4 wrote: > I see your point, although I don't think there is much a 14 year old > can do to sue someone. . . I'm sure my code won't be that valuable > untill I'm older though. Thanks It's valuable as something to show prospective employers or clients: "I wrote and maintained blahblah.sourceforge.net and foobar.sourceforge.net." Dave Cook From stuart at stuartbishop.net Fri Jun 17 00:13:49 2005 From: stuart at stuartbishop.net (Stuart Bishop) Date: Fri, 17 Jun 2005 14:13:49 +1000 Subject: DB API 2.0 and transactions In-Reply-To: <42AD5EB4.4060807@carmen.se> References: <42AD5EB4.4060807@carmen.se> Message-ID: <42B24DFD.7080204@stuartbishop.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Magnus Lycka wrote: > Another option would be to investigate if any of the other postgreSQL > drivers have a more correct behaviour. The non-standard behaviour that > you describe it obvious from the pgdb source. See: > http://www.pygresql.org/cvsweb.cgi/pygresql/module/pgdb.py?rev=1.27 fwiw psycopg 1.1.18 has the correct behavior (as usual). I can add this test to the DB-API 2.0 Anal Compliance Test Suite if we want, although it sounds like it is only an issue with PostgreSQL drivers. - -- Stuart Bishop http://www.stuartbishop.net/ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFCsk3oAfqZj7rGN0oRAjHAAJ4kQzxJXFW6hX6Q1t896fMzT0EUjACgkBhw X4wB17+4FwO9TsKpiIBJB50= =mYfn -----END PGP SIGNATURE----- From ccurvey at gmail.com Mon Jun 6 19:49:34 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 6 Jun 2005 16:49:34 -0700 Subject: help with sending mail in Program In-Reply-To: References: Message-ID: <1118101774.792153.203440@z14g2000cwz.googlegroups.com> Maybe you could give us a little more info about where you're getting messed up. The message body is just a string, so if you can build a string out of variables, you should be able to do it. From beliavsky at aol.com Sun Jun 12 07:46:51 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 12 Jun 2005 04:46:51 -0700 Subject: What language to manipulate text files References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> <1118569126.540000.217730@o13g2000cwo.googlegroups.com> Message-ID: <1118576811.816071.65590@z14g2000cwz.googlegroups.com> ross wrote: > Roose wrote: > > Why do people keep asking what language to use for certain things in the > > Python newsgroup? Obviously the answer is going to biased. > > > > Not that it's a bad thing because I love Python, but it doesn't make sense > > if you honestly want an objective opinion. > > > > R > > What usenet group is it best to ask in then? > Is there one where people have good knowledge of many scripting > languages? "What programming language is best for x" questions can be asked in comp.programming and/or comp.lang.misc , and possibly in a domain-specific newsgroup if it exists, for example sci.math.num-analysis if x = scientific computing. The resulting debates contain both heat and light :). From ptmcg at austin.rr.com Wed Jun 29 12:48:57 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 29 Jun 2005 09:48:57 -0700 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <1119883969.197756.22140@f14g2000cwb.googlegroups.com> <1119888923.782530.286990@g44g2000cwa.googlegroups.com> <1119928779.725558.211940@g47g2000cwa.googlegroups.com> Message-ID: <1120063737.916228.273700@g49g2000cwa.googlegroups.com> Steve - Good catch - in v1.3, I added some Unicode support for pyparsing, although I have not gotten much feedback that anyone is using it, or how well it works. So it is preferable to test against basestring instead of str. -- Paul From philippe at philippecmartin.com Fri Jun 10 09:32:55 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 10 Jun 2005 13:32:55 GMT Subject: Generating HTML from python References: <1118342111.655843.85940@o13g2000cwo.googlegroups.com> Message-ID: Thanks Walter D?rwald wrote: > Cappy2112 wrote: >> I looked at HTMLGen a while ago- I didn't see what the advantage was. >> I wrote soem code similar to the example above, to generate a page.. >> It worked out fine. >> >> However, I want to add HTML ouput to many of my other python programs, >> and I don't want to re-write this for each program. So some higher >> level of abastraction is needed, but I don't know how just yet. >> >> HTMLGen is no longer maintained, so I don't know what the best choice >> is. > > If you want an alternative to HTMLGen that is still maintained, you > might want to try XIST (http://www.livinglogic.de/Python/xist) > > A few simple examples can be found here: > http://www.livinglogic.de/Python/xist/Examples.html > > Bye, > Walter D?rwald From rabkin at mweb[DOT]co[DOT]za Thu Jun 23 15:02:26 2005 From: rabkin at mweb[DOT]co[DOT]za (Max) Date: Thu, 23 Jun 2005 21:02:26 +0200 Subject: Annoying behaviour of the != operator In-Reply-To: <1118255048.849018.259500@g14g2000cwa.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> Message-ID: Jordan Rastrick wrote: > I don't want to order the objects. I just want to be able to say if one > is equal to the other. > > Here's the justification given: > > The == and != operators are not assumed to be each other's > complement (e.g. IEEE 754 floating point numbers do not satisfy > this). It is up to the type to implement this if desired. > Similar for < and >=, or > and <=; there are lots of examples > where these assumptions aren't true (e.g. tabnanny). > > Well, never, ever use equality or inequality operations with floating > point numbers anyway, in any language, as they are notoriously > unreliable due to the inherent inaccuracy of floating point. Thats > another pitfall, I'll grant, but its a pretty well known one to anyone > with programming experience. So I don't think thats a major use case. > I think this is referring to IEEE 754's NaN equality test, which basically states that x==x is false if-and-only-if x.isNaN() is true. From tzot at sil-tec.gr Tue Jun 14 09:31:29 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 14 Jun 2005 16:31:29 +0300 Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: <4omta11gfr8ha5ma0nlt12iq2lgivfgn76@4ax.com> On Tue, 14 Jun 2005 07:20:06 GMT, rumours say that Andrew Dalke might have written: >Given the Python maxim of > There should be one-- and preferably only one --obvious way to do it. > >which of these is the preferred and obvious way? > >while f(): > print "Hello!" > if g(): > break >else: > print "this is a test" >also: > print "this is not a pipe" > > -or- > >while f(): > print "Hello!" > if g(): > print "this is a test" > break >else: > print "this is not a pipe" >I prefer the second over the first. I am not advocating for either side AFA python 2 is concerned (however I would substitute "then" for "also"), however the second way does not handle /elegantly/ multiple break points. I'm +1 for making "else" the target for break in Py3K though, given an elegant "also"/"then" keyword. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fredrin at ifi.uio.no Mon Jun 27 07:26:12 2005 From: fredrin at ifi.uio.no (Fredrik Normann) Date: Mon, 27 Jun 2005 13:26:12 +0200 Subject: Reading files in /var/spool/rwho/whod.* Message-ID: Hello, I'm trying to read the binary files under /var/spool/rwho/ so I'm wondering if anyone has done that before or could give me some clues on how to read those files. I've tried to use the binascii module without any luck. Best regards, -fredrik-normann- From apardon at forel.vub.ac.be Thu Jun 9 06:42:34 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 Jun 2005 10:42:34 GMT Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118251198.426673.108180@g49g2000cwa.googlegroups.com> Message-ID: Op 2005-06-08, Mahesh schreef : > No, why should Python assume that if you use != without supplying a > __ne__ that this is what you want? Without direction it will compare > the two objects which is the default behavior. > > So, s != t is True because the ids of the two objects are different. > The same applies to, for example s > t and s < t. Do you want Python to > be smart and deduce that you want to compare one variable within the > object if you don't create __gt__ and __lt__? I do not want Python to > do that. Python is already smart. It deduces what you want with the += operator even if you haven't defined an __iadd__ method. If python can be smart with that, I don't see python being smart with !=. -- Antoon Pardon From ognjen at mailshack.com Sat Jun 4 16:50:40 2005 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Sat, 04 Jun 2005 21:50:40 +0100 Subject: If - Or statements In-Reply-To: <42A1804B.6090504@ucsd.edu> References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> <42A175E0.8040800@mailshack.com> <42A1804B.6090504@ucsd.edu> Message-ID: <42A21420.80109@mailshack.com> Robert Kern wrote: > Ognjen Bezanov wrote: > >> Robert Kern wrote: >> >> >>> Ognjen Bezanov wrote: >>> >>> >>>> Another newbie-ish question. >>>> >>>> I want to create an if statement which will check if a particular >>>> variable matches one of the statements, and willl execute the >>>> statement >>>> if the variable matches any of the statements. >>>> >>>> I have tried the following (the pass is just used for testing) >>>> >>>> >>>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] == >>>> "aac" or ext[1] != "wma": >>>> print "we have a valid extension: " + ext[1] #here would go the >>>> code for decoding the above >>>> pass >>> >>> >>> >>> It works fine for me. Could you post the smallest complete program >>> (one that defines ext) that displays the behavior and its entire >>> output? >>> >>> As an aside, is 'ext[1] != "wma"' correct or should it be ==? As >>> written, you could collapse the whole thing to 'if ext[1] != "wma":' >>> but I presume it is a typo. >> >> >> filelist = os.listdir('/mnt/cdrom/') #get a list of files from the cdrom >> drive >> for thefile in filelist[:]: #for each file in the filelist >> if thefile.find(".") != -1: #if the file has an extenstion >> at all >> ext = thefile.split('.') #get the file extension >> ext[1] = ext[1].lower() #convert to lowercase >> print ext[1] #debugging, to see the variable before >> passed to if statement >> >> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" >> or ext[1] == "aac" or ext[1] == "wma": >> print "we have a valid extension: " + ext[1] #here >> would go the code for decoding the above >> pass > > > It works just fine for me. Note that you could (and probably should) > write the if statement as > > if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'): > > but I really don't think that's your problem. Could you also post the > output, too? > > In [1]:filelist = os.listdir('./') > > In [2]:for thefile in filelist: > ...: if '.' in thefile: > ...: ext = thefile.split('.') > ...: ext[1] = ext[1].lower() > ...: print ext[1] > ...: if (ext[1] == 'mp3' or ext[1] == 'mp4' or ext[1] == > 'ogg' or ext[1] == 'aac' or ext[1] == 'wma'): > ...: print 'We have a valid extension: %s' % ext[1] > ...: > ogg > We have a valid extension: ogg > [etc.] > I dont know what the problem was, but before posting the output i replaced: if (ext[1] == 'mp3' or ext[1] == 'mp4' or ext[1] == 'ogg' or ext[1] == 'aac' or ext[1] == 'wma'): with: if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'): And it worked perfectly, thanks for that tip. Not only does it work, but it is less messy to look at. And re. some other posts, yes the code is quite a hack, but once I get it working i will resort to cleaning it up and stripping all the unrequired blocks of code. Cheers everyone who helped! you made my life easier :) From dave.opstad at monotypeimaging.com Wed Jun 22 16:01:24 2005 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Wed, 22 Jun 2005 13:01:24 -0700 Subject: Odd slicing behavior? Message-ID: Take a look at this snippet: >>> class L(list): ... def __init__(self, v): ... super(L, self).__init__(v) ... def __setitem__(self, key, value): ... print key.indices(len(self)) ... >>> v = L(range(10)) >>> v [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> v[::] = [1] (0, 10, 1) >>> v[0:10:1] = [1] (0, 10, 1) So both assignments result in slices with exactly the same start, stop and step values: 0, 10 and 1. Also, the __setitem__ method is being called, not the older __setslice__ method; we can tell this because it hit the print statement. However, actually trying to make a slice assignment on a regular list in these two ways behaves differently: >>> v2 = range(10) >>> v2[0:10:1] = [1] Traceback (most recent call last): File "", line 1, in ? ValueError: attempt to assign sequence of size 1 to extended slice of size 10 >>> v2[::] = [1] >>> v2 [1] So given the equality of their slice representations, why do the v2[::] and v2[0:10:1] assignments behave differently? My reading of section 5.3.3 of the manual suggests that these should behave the same. If I'm just not seeing something obvious, please let me know! Thanks, Dave From hammer at maxwell.com Fri Jun 17 10:56:00 2005 From: hammer at maxwell.com (Maxwell Hammer) Date: Fri, 17 Jun 2005 10:56:00 -0400 Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') References: Message-ID: On Thu, 16 Jun 2005 16:20:23 -0400, Peter Hansen wrote: > Maxwell Hammer wrote: >> This is related to an earlier post 'Help with thread related >> tracebacks'...for which I have had no feedback yet :-( > > If the question was well formulated, and it's been more than a couple of > days, you should consider reposting. It's very unusual for a post with > such a subject (if it was a clear question) to get _no_ feedback around > here. Fair enough. The question is not expressed clearly for others. Do you have any suggestions as to how to describe the problem clearer? I can think of no other way but to say I have an app that when I terminate it, completes ok, However the last thing that happens before the shell prompt returns is that there is a traceback *within* python. (The actual post goes into more details of course.) I just took a guess that it is *thread* related from the output of the traceback. I'm still learning python, so how could one pose the problem *clearer*? And thanks for the feedback regarding threads, by the way. Max From here at there.net Wed Jun 22 08:15:22 2005 From: here at there.net (Drazen Gemic) Date: Wed, 22 Jun 2005 14:15:22 +0200 Subject: A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> Message-ID: Take your political propaganda somewhere else. DG From cjbottaro at alumni.cs.utexas.edu Fri Jun 3 17:17:00 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Fri, 03 Jun 2005 16:17:00 -0500 Subject: how to get name of function from within function? Message-ID: I want to get the name of the function from within the function. Something like: def myFunc(): print __myname__ >>> myFunc() 'myFunc' Really what I want to do is to easily strip off the prefix of a function name and call another function. Like this: def prefix_myFunc(a, b, c): name = __myname__[7:] call(name, a, b, c) That would call myFunc(a, b, c). How do I accomplish this 'elegantly', err...'pythonicly'..=) Also, is there a way to turn normal positional args into a tuple without using *? Like this: def f(a, b, c): print get_args_as_tuple() >>> f(1, 2, 3) (1, 2, 3) I don't want to use def f(*args): print args because I want to keep the error checking capability that comes with using a fixed number of positional args. Thank you for the help. From guy at NOSPAM.r-e-d.co.nz Fri Jun 24 18:04:59 2005 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Sat, 25 Jun 2005 10:04:59 +1200 Subject: howto load and unload a module In-Reply-To: <42BC0495.9080900@lexicon.net> References: <42BC0495.9080900@lexicon.net> Message-ID: > BTW, question for the OP: what on earth is the use-case for this? Bulk > checking of scripts written by students? > > Cheers, > John I've embedded python in an application which has a .NET API. So users can write scripts in python that access the .NET API. Because of the way the API works running scripts is a 2 stage process. First you select a script from a list then run the selected script. All scripts must therefore share a common calling function name and I wanted to test this function existed. I will have no idea the name or how many or how complicated the scripts will be so it seemed a good idea to try and free up memory from the scripts that won't be run. >(It's hard to judge a poster's level of expertise in Python without any example >code from him. I'm not a professional programmer so my terminology is probably confusing.It looks like I shouldn't worry about memory issues. Thanks for your help Peter and John, Guy From greg at cosc.canterbury.ac.nz Wed Jun 8 23:50:42 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 15:50:42 +1200 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: <3gpsl0Fdhq0mU1@individual.net> Rocco Moretti wrote: > The main problem is that Python is trying to stick at least three > different concepts onto the same set of operators: equivalence (are > these two objects the same?), ordering (in a sorted list, which comes > first?), and mathematical "size". A possible compromise would be to add a new special method, such as __equal__, for use by == and != when there is no __eq__ or __ne__. Then there would be three clearly separated levels of comparison: (1) __cmp__ for ordering, (2) __equal__ for equivalence, (3) __eq__ etc. for unrestricted semantics. > This gives the wacky world where > "[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't. To solve that, I would suggest a fourth category of "arbitrary ordering", but that's probably Py3k material. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From applegrew at gmail.com Thu Jun 23 16:02:55 2005 From: applegrew at gmail.com (Apple Grew) Date: Fri, 24 Jun 2005 01:32:55 +0530 Subject: Help me to log-in Message-ID: <42BB156F.3060305@gmail.com> Well can anyone tell me how do I login into newsgroup using Mozilla 1.7.7. What should be the username? (I tried with with my e-mail address I subscribed with but failed to log-in). The password asked during log-in is the one I subscribed with? -Apple From zunbeltz at gmail.com Tue Jun 21 10:54:01 2005 From: zunbeltz at gmail.com (Zunbeltz Izaola) Date: Tue, 21 Jun 2005 16:54:01 +0200 Subject: asynchronous comunication, wxPython and threads. References: Message-ID: On Tue, 21 Jun 2005 15:30:41 +0100, Toby Dickenson wrote: > On Tuesday 21 June 2005 14:22, Zunbeltz Izaola wrote: > > > I guess you are accessing the socket from both your GUI thread and > communications thread. Dont do that. An action in the GUI thread should > signal the communictions thread, then the communictions thread talks to the > socket. > I see ..., Could be the problem that the socket is created in the GUI thread? the function that end the theraded function (abort()) set want_abort = True This make the Measurement() function to return. The Measurement() funtion is called by startmeasurement() which is the threaded funciton. After aborting i execute a function that FinalizeMeasuremnt() that does comunication to some adjustament in the machine. Maybe i have to move this portion to the threaded funtion. > > Using non-blocking sockets in the GUI thread may cause the opposite problem to > the one that led you to use threads in the first place: a blocking operation > in the GUI may freeze the communications. Maybe that isnt a problem for you. > If it is, I suggest sticking to two threads. > Yes, i think i have to stick to two threads. > > If you are talking to only one device, then using blocking sockets is a good > approach. However Ive never written an application like this that didnt need > to support a second (or third) machine sooner or later, and three > communictions threads is starting to get ugly. A framework like Twisted will > let you handle many machines in the one thread, but it still makes sense to > keep a second one for the GUI. I didn't get this. What do you do when you have more tham one device; use thread or use Twisted? Did you use it whit wxPython. I think thereis some problems of compatibility. Thank you very much. Zunbeltz From steven.bethard at gmail.com Sat Jun 4 03:16:02 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 01:16:02 -0600 Subject: how to get name of function from within function? In-Reply-To: References: Message-ID: Christopher J. Bottaro wrote: > I haven't tried it yet, but this is what I would do with __call(): > > function __call($name, $args) { > $name .= 'IMPL'; > try { $this->$name($args); } > except { # error handling; } > } > > function funcA() { > # do something > } > > function funcBIMPL($a, $b) { > # do something > } > > So I imagine it would work like this: > > $obj = new MyClass(); > $obj->funcA(); # actually calls funcA because the function > # exists in the class > $obj->funcB($a, $b); # funcB doesn't exist, so __call() gets called with > # args 'funcB', array($a, $b) > # so inside __call(), we append 'IMPL' to $name, then invoke > # $this->funcBIMPL($a, $b) > > Using this setup, when I want to add a new function called mySuperFunc(), I > merely have to define mySuperFuncIMPL() and magically the wrapper is "made > for me"...=) Something like this might work: py> class C(object): ... def func_a(self): ... print "func_a" ... def func_b_impl(self): ... print "func_b" ... raise Exception ... def __getattr__(self, name): ... func = getattr(self, '%s_impl' % name) ... wrapped_func = self._impl_wrapper(func) ... setattr(self, name, wrapped_func) ... return wrapped_func ... def _impl_wrapper(self, func): ... def wrapper(*args, **kwargs): ... try: ... return func(*args, **kwargs) ... except: ... print "entered except" ... raise ... return wrapper ... py> c = C() py> c.func_a() func_a py> c.func_b() func_b entered except Traceback (most recent call last): File "", line 1, in ? File "", line 15, in wrapper File "", line 6, in func_b_impl Exception The idea here is that __getattr__ is called whenever the class doesn't have a particular function. The __getattr__ method then tries to find a corresponding _impl function, wraps it with appropriate try/except code, and returns the wrapped function. HTH, STeVe From gsakkis at rutgers.edu Wed Jun 22 08:01:06 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 22 Jun 2005 05:01:06 -0700 Subject: Compiling C++ extensions with distutils on Cygwin References: <1119400086.958159.182110@g44g2000cwa.googlegroups.com> Message-ID: <1119440695.435038.79820@g49g2000cwa.googlegroups.com> "George Sakkis" wrote: > I'm trying to build a C++ extension on Cygwin, but it fails because > distutils invokes gcc instead of g++. Looking into distutils internals, > it turns out that compilation is assumed to be independent of the > target language, while linking is not (CCompiler.compile() doesn't take > a target_lang argument but CCompiler.link() does). Is there a good > reason for this ? Is this a coincidence or what ? A patch for exactly this issue was posted just five days ago (http://python.org/sf/1222585), so it should be fixed in 2.5. George From __peter__ at web.de Tue Jun 28 02:22:13 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Jun 2005 08:22:13 +0200 Subject: OO refactoring trial ?? References: Message-ID: Chinook wrote: > 3) Any other comments you might offer > if?tv?==?'relates?to?A': > return?True > else: > return?False Make that return tv == 'relates to A' lest your zen master hit you. Peter From renting at astron.nl Thu Jun 30 03:47:33 2005 From: renting at astron.nl (Adriaan Renting) Date: Thu, 30 Jun 2005 09:47:33 +0200 Subject: Reading output from a child process non-blockingly Message-ID: I use the pty module, in combination with select.select. Search for Pexpect for an elaborate example. It basically goes something like this: ------------------------------------------------- import os, select, pty pid, fd = pty.fork() fd_eof = 0 if pid == 0: os.execvp('ls',['ls']) # child process else: # parent proces while not fd_eof: ready = select.select([fd], [], [], 0.25) if fd in ready[0]: text = os.read(fd, 1024) if text == '': fd_eof = 1 else: print text ------------------------------------------------------------- In 2.3.4 this exits with an exception OSError: [Errno 5] Input/output error after showing the 'ls' output, I have a problem that this works in 2.3.4 but in 2.3.5 this just keeps running indefinately. In my own code I handle the OSError by setting fd_eof=1. This onyl works on Unix. Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> Yuan HOng 06/29/05 10:08 AM >>> In my program I have to call an external program and parse its output. For that I use the os.popen2 function, and then read the output stream. But the complexity is that the external program gives back its output in a piecemeal manner, with long delays between the outputs. In the main program I want to therefore read the output in a non-blocking manner, to read as many bytes as the child process is spitting out. The question is, how can I achieve that? I tried use select.select on the output stream returned by os.popen2, but it returns a readable file descriptor only after the whole child process ends. Here is a script simulating the external program: test.py: import sys, time print 'hello\n'*500 sys.stdout.flush() time.sleep(100) print 'world\n'*500 And here is what I am tring to do in the main program to read its output: import os, select cmd = 'python test.py' pin, pout = os.popen2(cmd) while not select.select([pout], [], [], some_timeout)[0]: pass pout.readline() I hope to get the first return very soon, before the external program sleeps, but instead only after the whole program exits do I get any output. Can anyone give me a hint? -- Hong Yuan www.homemaster.cn -- http://mail.python.org/mailman/listinfo/python-list From chris.levis at gmail.com Wed Jun 15 17:13:09 2005 From: chris.levis at gmail.com (chris) Date: 15 Jun 2005 14:13:09 -0700 Subject: pyunit: remove a test case on the fly Message-ID: <1118869989.840138.16520@g44g2000cwa.googlegroups.com> We have a number of TestCase classes that have multiple test methods. We are interested in removing any of the individual test methods on the fly (dynamically, at runtime, whatever). We currently have an "isSupported" method in the TestCase classes that return a bool by which the greater test harness decides whether to run the enclosed test methods or not. We would like to have per-test-method granularity, however, for essentially skipping that particular test method; basically another isSupported call within the individual methods. We took a quick look at such options as: generating the entire test suite, then iterating through and renaming SomeTestClass.testSomeTest to SomeTestClass.SKIPsomeTest, and seeing if PyUnit would skip it (since the method name no longer starts with "test"). But this seemed pretty unwieldy. We have also considered breaking up the test class to a number of smaller test classes and calling isSupported with that finer-granularity set of test classes. That is probably the easiest way, but we do still want to consider alternatives. Here's to hoping that other folks out there have had experience with removing test methods on the fly, and have some wisdom to share. Cheers From der.rudi at planet-dot-nl.no-spam.invalid Wed Jun 29 10:59:32 2005 From: der.rudi at planet-dot-nl.no-spam.invalid (DeRRudi) Date: Wed, 29 Jun 2005 14:59:32 +0000 (UTC) Subject: Open running processes References: Message-ID: Well it doesnt work yet, but its gonna! ;) i've tested it with a little app. There is my main app (called it server) wich contains a thread. This thread listens to a mm (memory mapping) when an other program sets a flag (finished_producing_event.set() ) it just calls self.iconize(false) I'm not sure what pieces of code i have to post here.. posting all of it makes it too large i believe :) >From server: ID_MESSAGECH = wxNewId() def EVT_RESULT(win, func): win.Connect(-1, -1, ID_MESSAGECH, func) class ResultEvent(wxPyEvent): def __init__(self): wxPyEvent.__init__(self) self.SetEventType(ID_MESSAGECH) class listener(Thread): def __init__(self, frame): Thread.__init__(self) self.frame = frame self.setDaemon(1) self.stopped = False #shared_memory = mmap.mmap (0, common.SHARED_MEMORY_SIZE, common.SHARED_MEMORY_NAME) #ready_to_consume_event = events.Win32Event (common.READY_TO_CONSUME) #finished_producing_event = events.Win32Event (common.FINISHED_PRODUCING) def run(self): while not self.stopped: try: finished_producing_event.wait() wxPostEvent(self.frame,ResultEvent(None)) except Exception,e: print "Error: " , e def stop(self): self.stopped = True within the frame: [code:1:080343f1b1] listen = listener(self) listen.start() EVT_RESULT(self, self.OnChange) def OnChange(self, event): shared_memory.seek(0) tekstding = shared_memory.readline() if(tekstding.strip() == "maximize"): self.Iconize(False) self.Show(False) elif(tekstding.strip() == "minimize"): self.Iconize(True) self.Show(True) self.panel.tekst.SetValue(tekstding) [/code:1:080343f1b1] Hope you can see now how it works! Greetz From flamesrock at gmail.com Tue Jun 7 04:56:29 2005 From: flamesrock at gmail.com (flamesrock) Date: 7 Jun 2005 01:56:29 -0700 Subject: reg php.ini equivalent file in python In-Reply-To: References: Message-ID: <1118134589.495032.98750@z14g2000cwz.googlegroups.com> I think it depends on your os variables From bry at itnisk.com Sun Jun 12 09:22:21 2005 From: bry at itnisk.com (Bryan Rasmussen) Date: Sun, 12 Jun 2005 15:22:21 +0200 Subject: checking for when a file or folder exists, typing problems? Message-ID: <1118582541.42ac370d14d5a@horde.scannet.dk> Hi I have a little program that is importing from os.path import exists, join, isdir, normpath, isfile at one point in my program I check if a file exists using if exists("c:\projects"): and that works fine. If I change it to be if exists(thepath): where thepath is a commandline argument it does not work fine. Note that the commandline is c:\projects and when I print thepath to check what is going on it prints c:\projects The only thing I can assume is that there is some sort of typing problem going on here, but then it should go ahead and give an error then if it's getting something unexpected obviously. Any help on what this error is? Thanks -- Bryan Rasmussen From tiang_ono at yahoo.com Mon Jun 6 05:57:38 2005 From: tiang_ono at yahoo.com (Hallo) Date: Mon, 06 Jun 2005 09:57:38 -0000 Subject: how to show simulation at web Message-ID: hi all, I have tried making a simulation with python. I want it to be shown at a web. It is ok when I run it. so, I decided using cgi. but, when I try it using a web browser it doesn't work. Is it problem in the header or something else ? If there are any suggestions about this problem, I will be very happy. thanks From mwm at mired.org Mon Jun 6 18:21:19 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 06 Jun 2005 17:21:19 -0500 Subject: Destructive Windows Script References: <868y1n8b1d.fsf@guru.mired.org> Message-ID: <86mzq36s9s.fsf@guru.mired.org> rbt writes: > Mike Meyer wrote: >> "Terry Reedy" writes: >> >>> On *nix, one could open '/dev/rawdisk' (actual name depends on the >>> *nix build) and write a tracks worth of garbage for as many tracks >>> as there are. I don't how to programmaticly get the track size and >>> number (if there is a standard way at all). >> Modern Unix systems assume drives don't care much about geometry, >> what >> with sector forwarding and variable track lengths and the like. >> Just open the raw disk device (assuming your Unix has such), and >> start >> writing data to it. Keep going until the write fails at the end of the >> media. >> > Wouldn't /dev/urandom or /dev/random on Linux systems work better? Well, that would certainly make a good source for the data you write. > It's the kernel's built in random number generator. It'd fill the > drive with random bits of data. You could loop it too... in fact, I > think many of the pre-packaged *wipe* programs are mini Linux distros > that do just this. > > dd if=/dev/random of=/dev/your_hard_drive That works. You may want to set a block size for performance reasons. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tom at dtsam.com Wed Jun 1 17:25:00 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 1 Jun 2005 16:25:00 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xzmu94wrf.fsf at ruckus.brouhaha.com... > "Thomas Bartkus" writes: > > > Given that for the most part nobody in the Python community has a > > > handle on any other Python person's paycheck, it's unlikely that > > > enough of the community can be convinced that a VB-like > > > development environment would be a "killer app" for Python and > > > thus motivated to go produce one. > > > > Judging by the message traffic alluded to by the original poster, I'm hardly > > the only one with this particular itch. AND there is clearly a substantial > > development effort in this direction. Apparently, a few in the community are > > convinced of the worth. > > Are we talking about a drag-and-drop GUI builder? I am! > What about Glade? Dying to try that. Ask me again in a week. > Or do you mean a fancy IDE? That too! > There's a Python plug-in for Eclipse, but I haven't tried it yet. Fact is, there are all kinds of interesting things in the air. I happen to be one - and I *know* I'm not alone - who thinks that building user interfaces is way too difficult and way too important. It is particularly frustrating in that we do seem to be moving backwards in this department. Am I the only one who notices that we are in the dark ages when it comes to producing (new) software that people can use. Was MS Office 2000 the be all and end all of software development. Why has it all come to a halt? My explanation is a: Microsoft entering senility a programming community unable to recognize a developing vacuum The great html plague And - Lack of interest in GUI/IDE programming environments. Thomas Bartkus From mfranklin1 at gatwick.westerngeco.slb.com Wed Jun 15 05:43:57 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Wed, 15 Jun 2005 10:43:57 +0100 Subject: Tkinter question In-Reply-To: References: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> Message-ID: I realise I was a bit short on advice earlier... Martin Franklin wrote: > Nicholas.Vaidyanathan at aps.com wrote: > >>I'm sure there must be a way to do this, but I can't figure it out for >>the life of me? I'm writing a program where I would like to use a >>button's text field as part of an if statement. I set up my button like >>this: >> >> i = [ "7", "8","9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", >>".", "=", "+"] you can write this as i = "789/456*123-0.=+" as strings are sequences and can be sliced [] just like lists >> t = 0 #iterator through the sequence >> >>for x in range(4): >> for y in range(4): >> self.buttonx = Button(self, text = "%s" %i[t] , >>width=10, command = self.pressed) just a note about Tkinter Button command option. You may not know but the callback self.pressed will not get any arguments, other tool kits would send the instance of the button or perhaps an event, not Tkinter there are several ways around this, my prefered is with a callback class instance: class Command: def __init__(self, text): self.text = text def __call__(self): ## user just pressed my button ## do somthing with self.text and the creation of the button would look like: self.buttonx = Button(self, text="%s" %i[t], width=10, command=Command(i[t])) >> self.buttonx.grid( row=x+1, column = y, sticky = W+E+S) >> t+=1 >> >>What I would like to do is is check which buttons' text values are >>digits, and if the text is, I would like to append the number to a >>label. But: >> >>if(self.buttonx.title.isdigit): >> > > > To get the text of a button: > > self.buttonx["text"] > and to test if it is a digit: if self.buttonx["text"] in "0123456789": # yay I'm a number Martin From benji at benjiyork.com Thu Jun 30 08:29:47 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 30 Jun 2005 08:29:47 -0400 Subject: Favorite non-python language trick? In-Reply-To: <200506300346.12614.hancock@anansispaceworks.com> References: <1120103487.450255.18800@g44g2000cwa.googlegroups.com> <200506300346.12614.hancock@anansispaceworks.com> Message-ID: <42C3E5BB.4030408@benjiyork.com> Terry Hancock wrote: > http://www.logilab.org/projects/python-logic/ > This is something pretty new to me, so I can't comment on how well > it would meet your expectations, but I see now that the site does mention > OZ/Mozart as comparables. I've used both, the logilab stuff is cool, but no where near the maturity (or speed) of OZ/Mozart. OTOH, I can actually get things done with the logilab code. But that might say more about me than Mozart. :) -- Benji York From cal_2pac at yahoo.com Sat Jun 11 22:44:43 2005 From: cal_2pac at yahoo.com (cal_2pac at yahoo.com) Date: 11 Jun 2005 19:44:43 -0700 Subject: How to receive events (eg. user mouse clicks) from IE In-Reply-To: <42915ad9$1_1@spool9-west.superfeed.net> References: <1116476411.853695.235670@g14g2000cwa.googlegroups.com> <428c3cbe$1_1@spool9-west.superfeed.net> <1116529345.146032.91880@f14g2000cwb.googlegroups.com> <428cf5a9$1_1@spool9-west.superfeed.net> <1116537405.495521.252570@f14g2000cwb.googlegroups.com> <428f5882$1_2@spool9-west.superfeed.net> <428f8660$1_1@spool9-west.superfeed.net> <1116792093.323847.312700@g49g2000cwa.googlegroups.com> <42915ad9$1_1@spool9-west.superfeed.net> Message-ID: <1118544283.178003.277370@g47g2000cwa.googlegroups.com> Resurrecting an old thread.. It seems that this solution does not return events on objects within frames in webpages eg . if you go to www.andersondirect.com - the page is composed of three frames called as topFrame main and address. Now when I click on say 'Select a Vehicle' which is within main - I do not get any Onclick event. I also do not get an OnMousemove event if I move the mouse. However, I do get on Mousemove event on a tag called as frameset (which is part of the top page). How does one get events from the frames then? As always thanks a lot. Roger Upole wrote: > wrote in message > news:1116792093.323847.312700 at g49g2000cwa.googlegroups.com... > ... > > The problem is that msdn documentation says that in order to identify > > the element that was clicked - one has to query on IHTMLWindow2::event > > property on iHTMLWindow2 interface to get IEventOBj interface and then > > from there - use query interfce to get to the id of the element. > > > > How do I do this in python? ie. I have this code > > class Doc_Events(doc_mod.HTMLDocumentEvents): > > def Ononclick(self): > > print 'onClick fired ' > > and I see onClick being trapped. > > Now I need to go and get a reference to the iHTMLWindow2 interface. For > > this I need to get a reference to doc_mod (as far as I can see). How do > > I get that in the OnonClick method above. > > To get the IHTMLWindow2, you can just use self.parentWindow > inside the event hander, and then get the event from it. And then > the event's srcElement should be what you need. > > class Doc_Events(doc_mod.HTMLDocumentEvents): > def Ononclick(self): > print 'onclick' > ev=self.parentWindow.event > src=ev.srcElement > print 'tagName:',src.tagName,'name:',src.getAttribute('name') > > For clicking on google's input field, this yields > tagName: INPUT name: q > > > > > b) You had mentioned PumpWaitingMessages in the previous posting. I > > first encountered this on newsgroup postings. None of the standard > > books (python on win32 / python developer) seem to explain this in > > detail although this seems to be commonly used. Though I understand > > this now - my problem is that there seems to be a lack of cohesive > > explanation on how python ties up with COM (despite a good chapter 12 > > PumpWaitingMessages is just a way to ensure that normal message processing > (window messages, events, dde, etc) happens while python code is running. > Normally you don't need it, but every once in a while you hit a situation > where > blocking occurs. > > For how exactly python interacts with COM, the source is your best bet. > > Roger > > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From projecktzero at yahoo.com Mon Jun 27 10:05:59 2005 From: projecktzero at yahoo.com (projecktzero) Date: 27 Jun 2005 07:05:59 -0700 Subject: Getting binary data out of a postgre database References: <1119636233.488038.170240@z14g2000cwz.googlegroups.com> <3i320qFjktsjU2@uni-berlin.de> Message-ID: <1119878398.854244.132830@z14g2000cwz.googlegroups.com> Sorry for the late reply. I didn't check the group/list over the weekend. Anyway, I added a print rec[0] just after the fetchone. Then I ran it from the command line, and it spewed a bunch of binary gibberish nearly locking up Putty. To me, it seems like it's coming out in the right format, but I'm not sure what I'm doing wrong. If you have any ideas, I'd really appreciate it. Thanks, Mike From Florian.Lindner at xgm.de Wed Jun 22 17:01:11 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Wed, 22 Jun 2005 23:01:11 +0200 Subject: Optimize a cache Message-ID: Hello, I am building a object cache in python, The cache has a maximum size and the items have expiration dates. At the moment I'm doing like that: cache = {} # create dictionary cache[ID] = (object, timestamp) # Save a tuple with the object itself and a timestamp (from datetime.datetime.now()) under a unique object ID. This make looking up a certain item a cheap operation (AFAIK). After looking up my program checks if the expiration date and returns cache[ID][1] or retrieve a new object and overwrite the one saved in the cache. My problem now: When len(cache) > cacheSize I need to remove the oldest objects (the ones with the smalest timestamp). For that I need to iterate through all items and get the oldest one: (pseudo code) oldest = datetime.datetime.now() for i in cache: if i[1] < a: id = i n = i[0] del cache[id] What possible you see to optimize this lookup? Or anything else you see to make it better? Thanks, Florian From usenet at bolli.homeip.net Tue Jun 21 08:41:07 2005 From: usenet at bolli.homeip.net (Beat Bolli) Date: Tue, 21 Jun 2005 14:41:07 +0200 Subject: after transfer of data from MS-outlook(mail ids) to application, mail ids are consisting of strange characters In-Reply-To: <1119331449.803907.285750@z14g2000cwz.googlegroups.com> References: <1119331449.803907.285750@z14g2000cwz.googlegroups.com> Message-ID: <42b80af1_3@news.bluewin.ch> > [?@ [?. [?,??@ ??. ?? etc. This looks like UTF-8 encoding Beat -- mail: echo '' | tr -d '[A-S]' pgp: 0x506A903A; 49D5 794A EA77 F907 764F D89E 304B 93CF 506A 903A gsm: 4.7.7.6.0.7.7.9.7.1.4.e164.arpa icbm: 47.0452 N, 7.2715 E "It takes love over gold, and mind over matter" -- Dire Straits From rkern at ucsd.edu Sat Jun 11 16:12:03 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 11 Jun 2005 13:12:03 -0700 Subject: What is different with Python ? In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > I apologize in advance for launching this post but I might get enlightment > somehow (PS: I am _very_ agnostic ;-). > > - 1) I do not consider my intelligence/education above average > - 2) I am very pragmatic > - 3) I usually move forward when I get the gut feeling I am correct > - 4) Most likely because of 1), I usually do not manage to fully explain 3) > when it comes true. > - 5) I have developed for many years (>18) in many different environments, > languages, and O/S's (including realtime kernels) . > > Yet for the first time I get (most) of my questions answered by a language I > did not know 1 year ago. I cannot understand this sentence. What questions? Which language? Do you mean that, currently, when you need to solve a problem, you usually use Python even though you are relatively new to it? And that before learning Python you usually used a variety of languages, none dominating the others? > As I do try to understand concepts when I'm able to, I wish to try and find > out why Python seems different. Python is my language of choice because it doesn't get in the way. I don't have to contort my problem into strict class heirarchies or recursive functions. I don't have to construct the whole system to test just a part of it. The interactive prompt has become vital to my workflow. By and large, I just Get It Done. The "one and preferably only one obvious way to do it" principle and Python's emphasis on readability means that I gain knowledge and capability as I write code. When I need to do a similar task six months later, I don't have to spend an inordinate amount of time figuring out what the hell I was thinking back then. In the same vein, I can also read and learn from others' code much more than I could from, say, Perl. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rhall at thiess.com.au Thu Jun 2 04:50:09 2005 From: rhall at thiess.com.au (Bloke) Date: 2 Jun 2005 01:50:09 -0700 Subject: dictionaries and threads In-Reply-To: References: <20050601231009.396072.becbe514@goombah.com> Message-ID: <1117702209.058492.187520@f14g2000cwb.googlegroups.com> I've been trying to find a Python tutorial on threading - does anyone have a reference? Rob From ptmcg at austin.rr.com Thu Jun 16 09:44:48 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Jun 2005 06:44:48 -0700 Subject: Regex for repeated character? References: <5J9se.136$Q75.39412@newshog.newsread.com> <1118929259.330317.52610@g14g2000cwa.googlegroups.com> Message-ID: <1118929488.826438.227340@z14g2000cwz.googlegroups.com> One more bit, add this on to the code in the previous post: print "collapse repeated characters" repeats.setParseAction(lambda s,l,toks: toks[0][0]) print test,"->",repeats.transformString(test) Gives: collapse repeated characters foo ooobaaazZZ -> fo obazZ From mwm at mired.org Sat Jun 11 15:49:26 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 11 Jun 2005 14:49:26 -0500 Subject: Is pyton for me? References: <867jh16d3s.fsf@guru.mired.org> <87is0lpl5h.fsf@debian.kirkjobsluder.is-a-geek.net> <3aidnaJMIv08ezffRVn-iA@powergate.ca> Message-ID: <86fyvo4qt5.fsf@guru.mired.org> Peter Hansen writes: > Kirk Job Sluder wrote: >> I agree with this approach. For me, there has to be a certain level of >> complexity before I reach for python as a tool. > > For me as well. In my case, the key question is "is this bash script > going to be longer than two lines?". If it would be, the Python > approach will be done faster and will be more maintainable, since I > often don't look at those scripts again for months and would tend to > forget any bash syntax that I've learned in the meantime. I tend to switch from sh to python when I start writing a loop. A long list of repeated commands - even with conditionals - isn't to bad. But when you start forking processes in a loop, it's time to use a more powerful tool. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From max at alcyone.com Mon Jun 6 18:42:50 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 06 Jun 2005 15:42:50 -0700 Subject: Creating file of size x In-Reply-To: <42a4cea6$1@griseus.its.uu.se> References: <42a4cea6$1@griseus.its.uu.se> Message-ID: <56qdnYcDS9f3TDnfRVn-tw@speakeasy.net> Jan Danielsson wrote: > Is there any way to create a file with a specified size? What do you want to put in the file? Once you've answered that question, the solution should present itself. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis All the people in my neighborhood turn around and get mad and sing -- Public Enemy From prabapython at yahoo.co.in Tue Jun 14 00:38:44 2005 From: prabapython at yahoo.co.in (praba kar) Date: Tue, 14 Jun 2005 05:38:44 +0100 (BST) Subject: Regarding Content-type headers In-Reply-To: <200506132340.51600.hancock@anansispaceworks.com> Message-ID: <20050614043844.98654.qmail@web8401.mail.in.yahoo.com> Dear All, I have doubt regarding headers in cgi programming. If I gives "Content-Type:text/plain" then I try to print html contents. Is right or wrong after giving content-type: text/plain? regards Prabahar __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From elprodigio at gmail.com Mon Jun 20 02:12:05 2005 From: elprodigio at gmail.com (Didier C) Date: 19 Jun 2005 23:12:05 -0700 Subject: Can we pass some arguments to system("cmdline")? Message-ID: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> Hi! I was wondering if we can pass some arguments to system("cmdline")? E.g in Perl, we can do something like: $dir="/home/cypher"; system("ls $dir"); which would instruct Perl to do an "ls /home/cypher" But in python, doing something like dir="/home/cypher" system("ls dir") would cause python to execute "ls dir" where "dir" might not exist at all! Is there a way to reproduce the same thing in Python? Thanks for any insights. cheers, Didier. From kveretennicov at gmail.com Tue Jun 21 07:34:55 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 14:34:55 +0300 Subject: Howto access a enumeration in a COM TypeLib In-Reply-To: References: Message-ID: <4660fe30050621043460d24442@mail.gmail.com> On 6/21/05, Alexander Eisenhuth wrote: > Hello alltogether, > > I hope somebody can help me in that case. I bet I have overseen s.th.. > > I have a VC++ IDispatch Com-Server (ATL) and include for error handling > issues a enumeration in the IDL-File. > > [...] > enum PROG_ERROR { > P_OK = 0, > P_ERR_01 = 1, > P_ERR_02 = 2, > ... > } > typedef enum PROG_ERROR PROG_ERROR_T; > > [...] > > I can acess the COM object using : > > obj = win32com.client.Dispatch("...") > > and can Load the TypeLib: > > lib = pythonwin.LoadTypeLib("...") > > and see the enumeration in the OLE-Browser of Windows, but don't know > how to access the enum in Python. > > Any help and hints are very welcome. > > Regards > Alexander > > PS.: I use the actual version of ActivePython 2.4. Use site-packages/win32com/client/makepy.py to produce myserver.py from your typelib file, then >>> import myserver >>> print myserver.constants. P_OK 0 Maybe you can access constants without makepy, I don't know. - kv From sbassi at gmail.com Tue Jun 21 08:35:00 2005 From: sbassi at gmail.com (Sebastian Bassi) Date: Tue, 21 Jun 2005 09:35:00 -0300 Subject: Question about HTMLgen In-Reply-To: <4660fe300506201645e17c2c9@mail.gmail.com> References: <4660fe300506201645e17c2c9@mail.gmail.com> Message-ID: Thanks, you are right! On 6/20/05, Konstantin Veretennicov wrote: > > > type="image/svg+xml" name="wmap" wmode="transparent"> > > Works for me... -- La web sin popups ni spyware: Usa Firefox en lugar de Internet Explorer From codedivine at gmail.com Wed Jun 29 16:23:12 2005 From: codedivine at gmail.com (Rahul) Date: 29 Jun 2005 13:23:12 -0700 Subject: strange __call__ In-Reply-To: References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> <1120062469.370984.130670@f14g2000cwb.googlegroups.com> Message-ID: <1120076592.828106.301340@z14g2000cwz.googlegroups.com> If you do C = wrap(C) C no longer remains a class..it becomes a function. Steven Bethard wrote: > Rahul wrote: > > def wrapper(obj): > > g = obj.__call__ > > def f(*args,**kwargs): > > for arg in args:print arg > > return g(*args,**kwargs) > > obj.__call__=f > > but it seems this will not work for functions :( > > def wrap(obj): > def f(*args, **kwargs): > for arg in args: > print arg > return obj(*args, **kwargs) > return f > > @wrap > def func(a, b, c): > ... > > class C(object): > ... > C = wrap(C) > > STeVe From sjmachin at lexicon.net Sat Jun 18 19:45:51 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 19 Jun 2005 09:45:51 +1000 Subject: oddness in super() In-Reply-To: References: Message-ID: <42B4B22F.1090204@lexicon.net> Michael P. Soulier wrote: > Ok, this works in Python on Windows, but here on Linux, with Python 2.4.1, I'm > getting an error. > > The docs say: > > A typical use for calling a cooperative superclass method is: > > class C(B): > def meth(self, arg): > super(C, self).meth(arg) > > However, when I try this, which works on windows, with ActiveState > ActivePython 2.4.0... > > class RemGuiFrame(RemGlade.RemFrame): > """This class is the top-level frame for the application.""" > > def __init__(self, *args, **kwds): > "Class constructor." > # Constructor chaining > super(RemGuiFrame, self).__init__(*args, **kwds) > > ...on linux I get this... > > [msoulier at piglet pysrc]$ ./RemGui.py > Traceback (most recent call last): > File "./RemGui.py", line 206, in ? > frame_1 = RemGuiFrame(None, -1, "") > File "./RemGui.py", line 30, in __init__ > super(RemGuiFrame, self).__init__(*args, **kwds) > TypeError: super() argument 1 must be type, not classobj > > Why the difference? You are in the best position to answer that; you have access to the source code of the place where the problem occurs (RemGui.py), in both a "working" instance and a non-"working" instance, so you can (a) read it (b) debug it with a debugger, or insert print statements e.g. print repr(RemGuiFrame), repr(RemGlade.RemFrame) You have already noted two variables, OS Windows/Linux, and Python 2.4.[01]). Are there any others? Perhaps RemGlade.RemFrame comes from a 3rd party library and there's a version difference. > Is Python portability overrated? No. Please stop baying at the moon, and dig out some evidence. > Is this a bug? Is *what* a bug? Is "it" a bug in what? Windows? Linux? Python 2.4.0? Python 2.4.1? 3rd party code? your code? ===== I've never used "super" before, I'm only vaguely aware what it could be useful for, and what a "cooperative superclass method" might be, and I don't have access to your source code, nor to Linux ... but let's just see what can be accomplished if you drag yourself away from that moonlit rock and start digging: First (1) Ooooh what a helpful error message! What is a "classobj"? Let's RTFM: Hmmm don't tell X** L** but there's no entry for "classobj" in the index. But wait, maybe that's geekspeak for "class object" ... two or three bounces of the pogo-stick later we find this: """ Class Types Class types, or ``new-style classes,'' are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override __new__(). The arguments of the call are passed to __new__() and, in the typical case, to __init__() to initialize the new instance. Classic Classes Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class's __init__() method if it has one. Any arguments are passed on to the __init__() method. If there is no __init__() method, the class must be called without arguments. """ (2) Well fancy that... "type" kinda sorta means "new", "classobj" kinda sorta means "old"! Now let's re-read the bit about super in TFM: """ super() only works for new-style classes """ (3) So let's check out our tentative hypothesis: """ class Bold: def __init__(self): print "Bold" class Bnew(object): def __init__(self): print "Bnew" class Cold(Bold): def __init__(self): print "Cold", repr(Cold), "derives from", repr(Bold) super(Cold, self).__init__() print "Cold OK" class Cnew(Bnew): def __init__(self): print "Cnew", repr(Cnew), "derives from", repr(Bnew) super(Cnew, self).__init__() print "Cnew OK" cnew = Cnew() cold = Cold() """ which when run on Python 2.4.1 on a Windows box produces this result: """ Cnew derives from Bnew Cnew OK Cold derives from Traceback (most recent call last): File "C:\junk\soulier.py", line 22, in ? cold = Cold() File "C:\junk\soulier.py", line 12, in __init__ super(Cold, self).__init__() TypeError: super() argument 1 must be type, not classobj """ Funny that, the class repr()s are different; not in a meaningful way, but the mere difference indicates the classes are products of different manufacturers. (4) Ooooh! How old is the Linux copy of that 3rd party library? (5) Looks like the bug is in RemGui.py -- it is calling super() with an invalid argument. No apparent Python portability problems. > > I'm confused. Confession is good for the soul. However true confession is even better for the soul. Please come up with a better description. :-) === I hope these self-help hints are useful with your next "confusion". Cheers, John From timr at probo.com Thu Jun 9 00:38:27 2005 From: timr at probo.com (Tim Roberts) Date: Wed, 08 Jun 2005 21:38:27 -0700 Subject: Destructive Windows Script References: Message-ID: Magnus Lycka wrote: >rbt wrote: >> data = ['0', 'a', '1', 'b', '2', 'c',\ >> '3', 'd', '4', 'e', '5', 'f',\ >> '6', 'g', '7', 'h', '8', 'i',\ >> '9', 'j', '~', '!', '@', '#',\ >> '$', '%', '^', '&', '*', ';'] >> > >Note that the backslashes are redundant between pairs >of [ ], ( ) or { }. Just write: > > data = ['0', 'a', '1', 'b', '2', 'c', > '3', 'd', '4', 'e', '5', 'f', > '6', 'g', '7', 'h', '8', 'i', > '9', 'j', '~', '!', '@', '#', > '$', '%', '^', '&', '*', ';'] > > >(Not that it solves your disk wiping issue.) This is a lot easier to type: data = list("0a1b2c3d4e5f6g7h8i9j~!@#$%^&*;") -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From caseyhHAMMER_TIME at istar.ca Wed Jun 1 23:34:18 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Thu, 02 Jun 2005 03:34:18 GMT Subject: Information about Python Codyng Projects Ideas References: <1117645221.920027.224880@g14g2000cwa.googlegroups.com> Message-ID: <9dvs91l4aec10tnaqbjs8bh9s4oqh6b7eb@4ax.com> The slightly slower startup time makes no difference for apps running 24 hours a day, except when reloading changed source modules! I imagine reloading modules is also slower -- but I could be mis t ak en! -- Regards, Casey From farcepest at gmail.com Wed Jun 29 08:51:27 2005 From: farcepest at gmail.com (Andy Dustman) Date: 29 Jun 2005 05:51:27 -0700 Subject: How to connect python and Mysql? In-Reply-To: References: Message-ID: <1120049487.865890.295460@z14g2000cwz.googlegroups.com> Post your question here: http://sourceforge.net/forum/forum.php?forum_id=70461 From programmer.py at gmail.com Tue Jun 28 13:58:39 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 28 Jun 2005 12:58:39 -0500 Subject: regulars expressions ? In-Reply-To: References: <42c18cc9$0$6342$636a15ce@news.free.fr> Message-ID: Doh - please note that csv.reader takes more than one argument - the FIRST one is an iterable object. jw On 6/28/05, Jaime Wyant wrote: > Maybe, you need the csv module: > > import csv > mystring = "\"test1, test2\", test, 42" > > # The one argument to csv.reader is an iterable object > # You could use a file here... > csv_reader = csv.reader([mystring]) > > for line in csv_reader: > print line > > ['test1, test2', ' test', ' 42'] > > hth, > jw > > On 6/28/05, scott wrote: > > hi people ! > > > > > > i got some trouble with regular expressions > > i need to split a string like this on the ',' character : > > > > mystring = ""\test1, test2\", test, 42" > > > > i wanna get something (a list) like this (3 elements) : > > "test1, test2" > > test > > 42 > > > > but the only thing i get is a list like this (4 elements) : > > "test1" > > "test2" > > test > > 42 > > > > each element is separated by ',' but 1st element which is delimited by > > '"' may contain ',' character inside. > > > > so the regular expression i need is something like : > > split each element using ',' delimiter but if ',' delimiter is included > > between '"' please do not split > > > > > > 1st question is : does someone has understood the question ? > > 2nd question is : does someone has an answer ? > > > > thanks people > > > > scott > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From peter at engcorp.com Thu Jun 9 14:25:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 14:25:07 -0400 Subject: Any way to not create .pyc files? In-Reply-To: References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Lonnie Princehouse wrote: >> If these .pyc files exist, they appear to cause problems when other >> users' Python interpreters use them instead of the .py files. (I know, >> they *should* work, but they don't). This may have something to do >> with the fact that all of these users (on Windows) have the network >> drive mapped to arbitrary drive letters. I don't know. That won't be the reason. > You might also expect problems if one user was using python 2.2 and > another was using 2.4, since each version requires its own format for > the .pyc file, and they might conflict. Ulitmately it sounds like a > permissions problem. > It would be *much* more sensible to find the underlying cause of the > problems and actually fix them :-) I agree with Steve, and want to add to what he's given you. The only reason a .pyc file gets written is if the magic number inside doesn't match the one expected by your version of python, or if the timestamp that is stored inside doesn't match the timestamp of the .py file from which it was created. As far as I know, if both these things are true (and if the file is actually readable) then the .pyc file is loaded and the .py is ignored, and no new .pyc file is written. I suggest you pick two users who have the same version of python and test whether your .pyc files are written again and again. If they are not, then start looking for the "bad" user who probably has an older version of python. If they are written over and over, then Steve is probably correct about a permissions issue. HTH -Peter From tjreedy at udel.edu Fri Jun 24 16:21:32 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Jun 2005 16:21:32 -0400 Subject: Two questions on lambda: References: Message-ID: "Xavier D?coret" wrote in message news:d9gvl9$lo2$1 at trompette.imag.fr... > Hi, > > I cannot find the way to do generic lambda functions using the lambda > syntax in python. I am probably missing a point. Thinking of lambda args: expression as more or less abbreviating def (args): return expression should fill you in. Two differences: 1. the first is an expression and can be used as such within other expressions; the second a statement that stands alone. 2. the first will compile (with proper substitutions for 'args' and 'expression'); the second will not, because '' is not a legal name. However, in CPython, '' *is* the .func_name attribute of lambda-defined functions (so they are not quite anonymous;-). Terry J. Reedy From drewdious at gmail.com Mon Jun 6 10:53:32 2005 From: drewdious at gmail.com (d) Date: 6 Jun 2005 07:53:32 -0700 Subject: Using IDLE for checking versions Message-ID: <1118069612.942511.228720@g44g2000cwa.googlegroups.com> Okay, so I need to find out what version of wxPython is being used on a companies computer. I figured I can do this through IDLE, but I cant find the proper commands. Any help would be appriciated. From powderkeg at snow.email.ne.jp Fri Jun 3 02:15:11 2005 From: powderkeg at snow.email.ne.jp (Mark Sargent) Date: Fri, 03 Jun 2005 15:15:11 +0900 Subject: Moving Places, Subtracting from slices/lists In-Reply-To: References: <429EACCE.8050101@snow.email.ne.jp> Message-ID: <429FF56F.5010402@snow.email.ne.jp> Dennis Lee Bieber wrote: >On Thu, 02 Jun 2005 16:12:44 +0900, Mark Sargent > declaimed the following in >comp.lang.python: > > > >>How do I get that x to be an integer b4 it is entered into the indice.? >>Cheers. >> >> >> > If you really want the index, ask for the index... > > > >>>>hc >>>> >>>> >['Cat', 'roof', 'on', 'a', 'hot', 'tin'] > > >>>>try: >>>> >>>> >... i = hc.index("roof") >... new_hc = hc[:i] + hc[i+1:] + [hc[i]] >... except ValueError: >... pass >... > > >>>>new_hc >>>> >>>> >['Cat', 'on', 'a', 'hot', 'tin', 'roof'] > > > Hi All, ok, got the following for that. >>> hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin'] >>> i = hotcat.index("roof") >>> hotcat = hotcat[:1] + hotcat[i+1:] + [hotcat[1]] >>> except ValueError: File "", line 1 except ValueError: ^ SyntaxError: invalid syntax Cheers. P.S. If it's not too much, could you explain this line.? hotcat[:1] + hotcat[i+1:] + [hotcat[1]] hotcat[:1] = Cat? hotcat[i+1:] = all after roof? what does [hotcat[1]] do.? Mark Sargent. From lbates at syscononline.com Thu Jun 30 08:57:05 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 30 Jun 2005 07:57:05 -0500 Subject: Store multiple dictionaries in a file In-Reply-To: References: Message-ID: <42C3EC21.6040906@syscononline.com> You might want to take a look at the shelve module. -Larry Philipp H. Mohr wrote: > Hello, > > I would like to store multiple dictionaries in a file, if possible one per > line. My code currently produces a new dictionary every iteration and > passes it on to another peace of code. In order to be able to re-run some > experiments at a later date I would like to store every dictionary in the > same file. > I looked at pickel, but that seems to require a whole file for each > dictionary. > > It would be great if some one could tell me how to do that. > > Thank you, > Phil > From gsakkis at rutgers.edu Sun Jun 5 13:49:53 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 5 Jun 2005 10:49:53 -0700 Subject: Iterate through a list calling functions References: Message-ID: <1117993793.371018.200280@g47g2000cwa.googlegroups.com> David Pratt wrote: > Hi. I am creating methods for form validation. Each validator has its > own method and there quite a number of these. For each field, I want > to evaluate errors using one or more validators so I want to execute > the appropriate validator methods from those available. I am iterating > over each validator using validateField method to gather my results. It > works but it ugly and inefficient. Can someone advise whether there is > a better way of doing this. I realize that the validator variable in > my iteration is only a string so question is how can I make the > validator string reference a function so I may be able to shorten > validateField to something similar to this (instead of my long list of > ifs which I am not very happy with): > > for validator in validators_list: > result = validator(name, value) > if type (result) in StringTypes: > results[name] = result > > Many thanks > David > > My current situation below: > > # A large list of validators > def isDecimal(name, value): > """ Test whether numeric value is a decimal """ > result = validateRegex(name, > value, > r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', > errmsg='is not a decimal number.', > ignore=None) > return result > > def isZipCode(name, value): > """ Tests if field value is a US Zip Code """ > result = validateRegex(name, > value, > r'^(\d{5}|\d{9})$', > errmsg='is not a valid zip code.', > ignore=None) > return result > > ... more validators > > # Iterating over validators to gather field errors > def validateField(name, value, validators_list, range=None, > valid_values=None): > """ Validates field input """ > results={} > for validator in validators_list: > if validator == 'isContainedIn': > result = isContainedIn(name, value) > if type (result) in StringTypes: > more... > if validator == 'isDate': > result = isDate(name, value) > if type (result) in StringTypes: > more... > if validator == 'isDecimal': > result = isDecimal(name, value) > if type (result) in StringTypes: > more... > > more validators ... That's a typical case for using an OO approach; just make a class for each validator and have a single polymorphic validate method (I would make validators __call__able instead of naming the method 'validate'): # Abstract Validator class; not strictly necessary but good for documentation class Validator(object): def __call__(self,field,value): '''Validate a value for this field. Return a string representation of value on success, or None on failure. ''' raise NotImplementedError("Abstract method") class DecimalValidator(Validator): def __call__(self,name,value): '''Test whether numeric value is a decimal.''' class ZipCodeValidator(Validator): def __call__(self,name,value): '''Test if value is a US Zip Code.''' def validateField(name, value, validators): """ Validates field input """ results = {} for validate in validators: result = validate(name,value) if result is not None: results[name] = result # XXX: if more than one validators succeed, # all but the last result will be overwritten return results # test validators = [DecimalValidator(), ZipCodeValidator()] print validateField("home ZIP", "94303", validators) Regards, George From robert at reeves.net Wed Jun 29 03:59:33 2005 From: robert at reeves.net (rjreeves) Date: 29 Jun 2005 00:59:33 -0700 Subject: Newbie: Explain My Problem In-Reply-To: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> References: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> Message-ID: <1120031972.898176.191280@g49g2000cwa.googlegroups.com> Hi Chuck 1. Missing an int(.. on one of the guess= print "You have", counter, " chances left to guess the number." guess = int(raw_input("Your guess is ")) Thus ensuring guess is consistent with it content type 2. Need a break when the guess=num if guess == num: print "You guessed the number, ", num, " in ", counter-6, " guesses!" break To stop from looping in the while when counter is NOT zero but the number has been found. From ivanlan at pauahtun.org Thu Jun 23 23:08:53 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 23 Jun 2005 21:08:53 -0600 Subject: A World Beyond Capitalism 2005, References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> <3cacc254a9d2010cbf5298fc3bd955b0@localhost.talkaboutprogramming.com> Message-ID: <42BB7945.1BDF8ACF@pauahtun.org> Hi All-- Jenta wrote: > > Interesting. > > To anyone who didn't want to know about the conference, my apologies. > > To everyone who was supportive, thanks. It is appreciated, because like > many activists, many python activists have skills which are able to > network people worldwide. > So, uh, what skills do "python activists" have? Why are their skills able to network people when the people who have the skills can't? And what defines a "python activist" anyway? Blowing up Perl installations worldwide? That takes skill? I thought they could handle that themselves. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.pauahtun.org/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From andre.roberge at gmail.com Wed Jun 1 21:19:15 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Wed, 01 Jun 2005 22:19:15 -0300 Subject: BUG-FIX: RUR-PLE 0.9.0.1 Message-ID: RUR is a Python Learning Environment, based after Pattis's Karel the robot. More details can be found at http://rur-ple.sourceforge.net Version 0.9.0.1 is a bug-fix. Version 0.9 relied on the presence of a unicode version of wxPython (version 2.6 preferred). Version 0.9.0.1 should work with both the unicode and the ansi version of wxPython. Andr? From sjmachin at lexicon.net Thu Jun 2 20:51:23 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 10:51:23 +1000 Subject: REQ: Small Perl to Python conversion needed In-Reply-To: <020620052018031433%user@unknown.invalid> References: <020620052018031433%user@unknown.invalid> Message-ID: <429fa98b$1@news.eftel.com> Koncept wrote: > Howdie Python folks! I am very new to Python ( 3rd day now ) and it has > already earned its place as my fav. language to work in. I hope to > continue, and I really would appreciate some good resources if anybody > would care to contribute. > > My current head-scratcher concerns something I can do in Perl which I > would like to have duplicated for Python. I have noticed that it is not > possible to increment an unset value in Python, so I would like to know > how to duplicate the following bit of code using Python dictionaries. > [expletives deleted] freq_dict = {} ... if thing in freq_dict: freq_dict[thing] += 1 else: freq_dict[thing] = 1 or, less plainly, freq_dict[thing] = freq_dict.get(thing, 0) + 1 From devlai at gmail.com Thu Jun 30 23:27:31 2005 From: devlai at gmail.com (Devan L) Date: 30 Jun 2005 20:27:31 -0700 Subject: Escaping commas within parens in CSV parsing? In-Reply-To: <1120187679.811723.242530@g47g2000cwa.googlegroups.com> References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> <1120187679.811723.242530@g47g2000cwa.googlegroups.com> Message-ID: <1120188451.250251.134750@g49g2000cwa.googlegroups.com> Oops, the above code doesn't quite work. Use this one instead. re.findall(r'(.+? (?:\(.+?\))?)(?:,|$)',yourtexthere) From ccurvey at gmail.com Mon Jun 20 11:11:04 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 20 Jun 2005 08:11:04 -0700 Subject: login website that using PHP In-Reply-To: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> References: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> Message-ID: <1119280264.576336.114610@g47g2000cwa.googlegroups.com> I'll add a plug for PAMIE (another set of Python classes that drive IE) http://pamie.sourceforge.net/ From philippe at philippecmartin.com Thu Jun 30 13:23:31 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 30 Jun 2005 17:23:31 GMT Subject: Seeking IDE References: Message-ID: Linux: Eric3 All: Eclipe: my choice (might be tough to get into) Nick Mountford wrote: > Hi, > > Complete newb to Python and programming, looking for an open source > IDE to download. Any suggestions? > > Thanks, > > Nick From chris.arndt at web.de Thu Jun 30 10:03:34 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Thu, 30 Jun 2005 15:03:34 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: <8c7f10c605063002083ccc1e88@mail.gmail.com> References: <3ian37Fkjle0U1@individual.net> <8c7f10c605063002083ccc1e88@mail.gmail.com> Message-ID: Simon Brunning schrieb: > On 6/29/05, Christopher Arndt wrote: > > > Adding sqllite to the standard library has been discussed before: > http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fd150297c201f814 Yeah, but they didn't seem to have come to a conclusion then. Also, pysqlite 2.x has had a final release now and is still fairly DB-API compatible (at least is seems so by looking at the docs). I might go to their mailing list and ask about the status. Chris From deets at web.de Wed Jun 22 16:29:18 2005 From: deets at web.de (Diez B. Roggisch) Date: Wed, 22 Jun 2005 22:29:18 +0200 Subject: Odd slicing behavior? In-Reply-To: References: <3htv6gFips59U1@uni-berlin.de> Message-ID: <3hu00uFifvnrU1@uni-berlin.de> Dave Opstad wrote: > In article <3htv6gFips59U1 at uni-berlin.de>, > "Diez B. Roggisch" wrote: > > >>So - the rationale seems to be: "When using slice-assignment, a form >>like l[a:b:c] imposes possibly a non-continous section in l, for which >>the semantics are unclear - so we forbid it" > > > But it isn't forbidden: > > >>>>v = range(10) >>>>v > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>>>v[0:10:3] = ['a', 'b', 'c', 'd'] >>>>v > > ['a', 1, 2, 'b', 4, 5, 'c', 7, 8, 'd'] > > The only time it's actively forbidden is when the length of the slice > and the length of the list being assigned to it don't match. Oh, cool. But then the semantics are clear: if using [a:b:c] syntax, the replaced slice has to be of same lenght. Makes sense - and in that case, I'd prefer c==1 not to be special cased - for the sake of a more clearly defined behaviour. Regards, Diez From rune.strand at gmail.com Mon Jun 20 21:06:10 2005 From: rune.strand at gmail.com (Rune Strand) Date: 20 Jun 2005 18:06:10 -0700 Subject: reading a list from a file In-Reply-To: <42B75818.3090901@lexicon.net> References: <223874235.UzX6FoQtyG@teancum> <1119305164.006906.133590@z14g2000cwz.googlegroups.com> <1119306766.673306.220350@z14g2000cwz.googlegroups.com> <1119307879.606696.238410@g49g2000cwa.googlegroups.com> <42B75818.3090901@lexicon.net> Message-ID: <1119312295.268986.304210@z14g2000cwz.googlegroups.com> :-/ You're right! From rkern at ucsd.edu Mon Jun 13 14:52:52 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 13 Jun 2005 11:52:52 -0700 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: References: Message-ID: Robert Kern wrote: > I'm just tossing this out. I don't really have much experience with the > algorithm, but when searching for multiple targets, an Aho-Corasick > automaton might be appropriate. > > http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ More puttering around the web suggests that pytst may be a faster/more scalable implementation. http://www.lehuen.com/nicolas/index.php/Pytst Try them both. If you meet success with one of them, come back and tell us about it. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From gjego at free.fr Sat Jun 4 07:10:03 2005 From: gjego at free.fr (Georges JEGO) Date: Sat, 04 Jun 2005 13:10:03 +0200 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: <42a18c1d$0$24365$626a14ce@news.free.fr> Mac a ?crit : > # .... do some stuff > if debug: > emit_dbg_obj(DbgObjFoo(a,b,c)) Assuming your debug functions always return true, you could use: assert emit_dbg_obj(DbgObjFoo(a,b,c)) and have this code executed -or not- depending on the use of "-O" -- Georges From bob at passcal.nmt.edu Tue Jun 28 12:00:38 2005 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 28 Jun 2005 10:00:38 -0600 Subject: Text() tags and delete() References: Message-ID: <1oadnbFnIeqJ6VzfRVn-hQ@nmt.edu> "Christopher Subich" wrote in message news:La3we.24035$qm.18241 at bignews6.bellsouth.net... > Bob Greschke wrote: >> Does Text.delete(0.0, END) delete all of the tags too? Everything says >> it does not delete marks, but nothing about tags. > > Note to everyone else: this is a TKinter question. Oops. I meant to put that in the subject. > Tags are attached to text ranges, in the Text widget. If you delete all > of the text in the widget, all of the text ranges will go poof, so > therefore all of the tag attachments will likewise go poof. That's what I thought, and that was what it looked like was happening (but just because you can't find something doesn't mean it hasn't been taken to the garbage :) > This will not delete any tags that have been defined for the widget, > though, although why you'd want to do that is an open question. We have all kinds. :) Thanks, Christopher! From mrmaple at gmail.com Thu Jun 23 14:10:39 2005 From: mrmaple at gmail.com (James Carroll) Date: Thu, 23 Jun 2005 14:10:39 -0400 Subject: User interfaces in console (dialog like) In-Reply-To: References: <2fdabf19.0506230445.249d063f@posting.google.com> Message-ID: Wow, I was just reminiscing about my old TurboVision days... I second the recommendation. On 6/23/05, Jeremy Sanders wrote: > Negroup wrote: > > > Do you guys know an alternative that fits my needings without moving > > from Python? > > Turbo Vision in dos used to be really good. There's a python binding to the > free version here: > > http://tvision.sourceforge.net/ > > (I haven't tried it) > > -- > Jeremy Sanders > http://www.jeremysanders.net/ > -- > http://mail.python.org/mailman/listinfo/python-list > > From danb_83 at yahoo.com Fri Jun 10 12:05:53 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 10 Jun 2005 09:05:53 -0700 Subject: Annoying behaviour of the != operator References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: <1118419552.982312.228410@g43g2000cwa.googlegroups.com> Steven D'Aprano wrote: ... > If you were to ask, "which is bigger, 1+2j or 3+4j?" then you > are asking a question about mathematical size. There is no unique answer > (although taking the absolute value must surely come close) and the > expression 1+2j > 3+4j is undefined. > > But if you ask "which should come first in a list, 1+2j or 3+4j?" then you > are asking about a completely different thing. The usual way of sorting > arbitrary chunks of data within a list is by dictionary order, and in > dictionary order 1+2j comes before 3+4j because 1 comes before 3. > > This suggests that perhaps sort needs a keyword argument "style", one of > "dictionary", "numeric" or "datetime", which would modify how sorting > would compare keys. > > Perhaps in Python 3.0. What's wrong with the Python 2.4 approach of >>> clist = [7+8j, 3+4j, 1+2j, 5+6j] >>> clist.sort(key=lambda z: (z.real, z.imag)) >>> clist [(1+2j), (3+4j), (5+6j), (7+8j)] ? From miki.tebeka at zoran.com Sun Jun 19 03:29:53 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 19 Jun 2005 10:29:53 +0300 Subject: Embedding Python - How to create a class instance Message-ID: <20050619072953.GJ908@zoran.com> Hello All, I'm trying to embed Python in a C application. What I didn't find is how to create an instance once I have a class object. I'd like to do the equivalent of: from a import A obj = A() obj.foo(10) The following code omits error checking for clarity. --- a.py --- class A: def foo(self, x): print "A got %d" % x --- a.py --- --- a.c --- int main() { PyObject *module, *A, *dict, *a, *args; PyObject *obj; Py_Initialize(); PyRun_SimpleString("import sys; sys.path.append('.')"); module = PyImport_ImportModule("a"); dict = PyModule_GetDict(module); A = PyDict_GetItemString(dict, "A"); /* FIXME: Create obj as instance of A (a = A()) */ obj = ??? foo = PyObject_GetAttrString(obj, "foo"); args = Py_BuildValue("(O, i)", obj, 49); PyObject_CallObject(foo, args); Py_Finalize(); return 0; } --- a.c --- Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From davecook at nowhere.net Sun Jun 19 12:21:53 2005 From: davecook at nowhere.net (Dave Cook) Date: Sun, 19 Jun 2005 16:21:53 GMT Subject: Migrating from Windows to OS X References: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> <0001HW.BED99CB20042B4FEF0407550@news.individual.de> <1119107224.205327.127150@g49g2000cwa.googlegroups.com> Message-ID: On 2005-06-18, ladasky at my-deja.com wrote: > How are the development tools for the Mac? I'll use IDLE if it's > available, but I like Scintilla better. Idle is /System/Library/Frameworks/Python.framework/Versions/2.3/bin/idle First thing you want to do is install readline to make the interactive interpreter useable: http://pythonmac.org/packages/ Other things to try: Aquamacs with python-mode http://www.aquamacs.org http://sourceforge.net/projects/python-mode/ http://www.emacswiki.org/cgi-bin/wiki/CustomizeAquamacs (instructions) I prefer a less aggressively "aquafied" emacs like: http://www.emacswiki.org/cgi-bin/emacs-en/CarbonEmacsPackage but someone who has never used emacs before might not care. Eclipse + pydev: http://www.eclipse.org http://pydev.sourceforge.net/ SPE or Eric3: http://www.wordtech-software.com/python.html Dave Cook From roy at panix.com Sun Jun 5 13:52:09 2005 From: roy at panix.com (Roy Smith) Date: Sun, 05 Jun 2005 13:52:09 -0400 Subject: If - Or statements References: Message-ID: venkata subramanian wrote: > It just reminds me that the most important thing about learning a > language is also to learn its style and "paradigm" and not just its > syntax and semantics. Or one might end up wrenching in > "C-like-thinking" into a python program where it might not look > necessarily pretty. Exactly! One sure sign of somebody trying to write C in Python is when they loop over a list by doing for i in range (len (myList)): doSomethingWith (myList[i]) or when they laboriously check for every possible error condition before performing an operation instead of just doing it and catching the exception. From tojuso at hotmail.com Wed Jun 8 17:49:59 2005 From: tojuso at hotmail.com (Dan) Date: 8 Jun 2005 14:49:59 -0700 Subject: Controlling source IP address within urllib2 References: <1117839742.510669.245420@g14g2000cwa.googlegroups.com> <87slzxlppj.fsf@pobox.com> <1118094808.095632.134210@z14g2000cwz.googlegroups.com> <87u0k9db32.fsf@pobox.com> Message-ID: <1118267399.833567.90710@z14g2000cwz.googlegroups.com> John, Thanks again for your help! I think that the do_open function in AbstractHTTPHandler does not return the correct object type as required by the opener. When I include the code you recommended, the implementation comes back with the message, "urlopen error unknown url type: http". Strange, because I would think that overriding the "http_open" function in the handler would have signaled that this function is capable of handling http. If I call the HTTPHandler base class "http_open" function from within the derived class, all works okay, but of course, I don't get to use the source IP address I wanted to use. I'll keep trying and let you know what I find. -Dan From tchur at optushome.com.au Wed Jun 29 18:14:13 2005 From: tchur at optushome.com.au (Tim Churches) Date: Thu, 30 Jun 2005 08:14:13 +1000 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <42C31D35.8070201@optushome.com.au> muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. Many companies hire salespersons from Britain to > represent their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? > > Be blunt. We Americans need to know. Should we try to change the way we > speak? Are there certain words that sound particularly goofy? Please > help us with your advice on this awkward matter. To true Pythonistas, the only regional English accent which denotes sophistication and high intelligence is the Dutch-English accent. For those wishing to practice their faux-Dutch-English accent (absolutely necessary if you are to be taken seriously at any Python-related gathering, no matter where in the world it is held), some examples to emulate can be found here (needs Quicktime): http://classweb.gmu.edu/accent/dutch0.html and here: http://www.itconversations.com/shows/detail545.html http://www.itconversations.com/shows/detail559.html Tim C From ionel.mc at gmail.com Wed Jun 1 12:48:54 2005 From: ionel.mc at gmail.com (ionel) Date: Wed, 1 Jun 2005 18:48:54 +0200 Subject: How can i craft my own ip packets in python Message-ID: ermmmm.... pointers please? :) -- ionel. From bokr at oz.net Sun Jun 26 13:47:21 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 17:47:21 GMT Subject: MoinMoin WikiName and python regexes References: Message-ID: <42bed3db.261184473@news.oz.net> On Wed, 8 Jun 2005 09:49:51 -0600, "Ara.T.Howard" wrote: > >hi- > >i know nada about python so please forgive me if this is way off base. i'm >trying to fix a bug in MoinMoin whereby > > WordsWithTwoCapsInARowLike > ^^ > ^^ > ^^ > >do not become WikiNames. this is because the the wikiname pattern is >basically > > /([A-Z][a-z]+){2,}/ > >but should be (IMHO) > > /([A-Z]+[a-z]+){2,}/ That would take care of the example above, but does it change an official spec? > >however, the way the patterns are constructed like > > word_rule = ur'(?:(? 'u': config.chars_upper, > 'l': config.chars_lower, > 'subpages': config.allow_subpages and (wikiutil.CHILD_PREFIX + '?') or '', > 'parent': config.allow_subpages and (ur'(?:%s)?' % re.escape(PARENT_PREFIX)) or '', > } > > >and i'm not that familiar with python syntax. to me this looks like a map >used to bind variables into the regex - or is it binding into a string then >compiling that string into a regex - regexs don't seem to be literal objects >in pythong AFAIK... i'm thinking i need something like > > word_rule = ur'(?:(? ^ > ^ > ^ > 'u': config.chars_upper, > 'l': config.chars_lower, > 'subpages': config.allow_subpages and (wikiutil.CHILD_PREFIX + '?') or '', > 'parent': config.allow_subpages and (ur'(?:%s)?' % re.escape(PARENT_PREFIX)) or '', > } > >and this seems to work - but i'm wondering what the 's' in '%(u)s' implies? >obviously the u is the char range (unicode?)... but what's the 's'? 'u' doesn't stand for unicode here. It is the key to look up config.chars_upper from the dict. That could be unicode, and probably is. The 's' is the final part of a formatting spec which says how to convert the data looked up, and 's' is for string, which doesn't change string data (unless, and UIAM, a conversion to unicode is required). All of the above is making use of the % operator of strings, as in the expression fmt % data where fmt is a string containing ordinary characters and formatting specs in the form of substrings escaped by a leading character '%'. The formatting specs take two basic alternative forms: % or %(name). If any '%' is followed by a parenthesized name, as in '%(u)s' it means that the data to be formatted is retrieved from data['u'] for the latter example. If there is no parenthesized name, the data is retrieved from data[i] where data must be a tuple and i is the positional count of format specs in fmt. In some cases where there is no ambiguity, and there is only one datum, data[0] may be written as the non-tuple value expression, e.g., instead of (123,) that data could be written as (123,)[0] or plain 123. In the word_rule above, %(u)s uses 'u' as a key to get data from the dictionary { 'u': config.chars_upper, ...} to substitute in the [%(u)s] as a string (that's what the 's' specifies), so config.chars_upper will presumably have had a string value such as u'ABC..Z' and that will then be inserted in place of the %(u)s to get u'...[ABC..Z]...' (if fmt is unicode, the resulting string will be unicode, UIAM) > >i'm looking at > > http://docs.python.org/lib/re-syntax.html > http://www.amk.ca/python/howto/regex/ > See also http://www.python.org/doc/current/lib/typesseq-strings.html (which IMO should be easier to find, but if you click on the index square at the top right of any library reference page, you can see a "%formatting" link) >and coming up dry. sorry i don't have more time to rtfm - just want to >implement this simple fix and get on to fcgi configuration! ;-) > >cheers. > >-a >-- >=============================================================================== >| email :: ara [dot] t [dot] howard [at] noaa [dot] gov >| phone :: 303.497.6469 >| My religion is very simple. My religion is kindness. >| --Tenzin Gyatso >=============================================================================== > Regards, Bengt Richter From mandus at gmail.com Sat Jun 25 06:58:26 2005 From: mandus at gmail.com (Mandus) Date: Sat, 25 Jun 2005 10:58:26 +0000 (UTC) Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Fri, 24 Jun 2005 16:31:08 +0100 skrev Tom Anderson: > On Fri, 24 Jun 2005, Joseph Garvin wrote: > >> Claudio Grondi wrote: >> >> So far we've got lisp macros and a thousand response's to the lua trick. >> Anyone else have any actual non-python language tricks they like? > > Higher-order functions like map, filter and reduce. As of Python 3000, > they're non-python tricks. Sigh - i guess it's time for me to get to know > list comprehensions a bit better. > u-huu... I wasn't aware of that. It is really a consensus on this; that removing map, filter, reduce is a good thing? It will render a whole lot of my software unusable :( Sure, I guess I can port most of it to list comprehensions, but reduce/map are so much nicer. -- Mandus - the only mandus around. From pmaupin at gmail.com Fri Jun 24 16:53:43 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 24 Jun 2005 13:53:43 -0700 Subject: formatted xml output from ElementTree inconsistency References: Message-ID: <1119646423.324518.220710@o13g2000cwo.googlegroups.com> Jarek Zgoda wrote: > Why want you to read an XML document "by hand"? It's a "machine related" > data chunk. > I see this attitude all the time, and frankly I don't understand it. Please explain why XML is in ASCII/unicode instead of binary. Is it because it is easier for a machine to parse? No, I thought not. It's obviously so humans can read it. The next question is: why is arbitrary whitespace allowed? Is that to make it easier for machines to parse? Is it any easier for machines to generate arbitrary whitespace than it would have been for them to always insert, e.g., a single space? No, I thought not there as well. > Document formatting should be done by means of CSS and/or XSL stylesheet. He's not formatting the (rendered) document -- he's just formatting the raw data to make it more readable in an editor. You could use CSS/XSL, and then selectively add whitespace without actually affecting the rendering. Alternatively, as you point out, it is a "machine related" data chunk -- some XML documents are never even destined for human eyes, _except_ for debugging. For some of those documents, CSS and XSL are just a waste of CPU cycles. Regards, Pat From foo at bar.com Wed Jun 22 10:32:04 2005 From: foo at bar.com (Steve Menard) Date: Wed, 22 Jun 2005 10:32:04 -0400 Subject: JEP and JPype in a single process In-Reply-To: References: Message-ID: Steve Menard wrote: > skn wrote: > >> Hello, >> >> I have written a very simple java class file, which invokes a Python >> script >> using JEP. >> >> Code snippet:- >> ------------------- >> Jep jep = new Jep(false); >> jep.runScript("C:\\temp\\testscript.py"); >> jep.close(); >> >> Now inside this Python script I want to make Java calls using JPype. >> If I use startjvm() inside this Python script, a Runtime Error >> (exception) >> is thrown. >> Also tried attachThreadToJVM(), but doesn't work, again Runtime Error. >> >> Any clues as to how I could achieve my goal?? >> The interaction shown below should happen in a single process. >> >> JAVA ==> jep ==> PYTHON ==> jpype ==> JAVA >> >> Regards, >> skn >> >> > > You're trying to do something I hope to make possible somewhere down the > road ... > > As of today, I do not think it is possible. JPype does not provide a way > to initialize the JVM-bridge system except for startJvm .. which seems > to be prohibited when a JVM is already running. > > AttachThreadToJVM will only work once the JVM-bridge system has been > initialize. > > I will look into providing a sister method to startJVM to attach to the > currently running JVM instead of starting a new one. IF it does not > require major changes I will release it as 0.5.1. If you'd like you can > submit an enhancement request on the JPype sourceforge page, so this > doesn't get lost. > > > OK .. it now works. There are a few caveats that cannot be resolved until either JEP and JPype can somehow cooperate or I finish what I started and basically fold the JEP functionality in JPype. I will release the new functionality in as version 0.5.1. The "gotchas" are going to be in a readme-jep.txt file. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From jjl at pobox.com Wed Jun 1 18:27:44 2005 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2005 22:27:44 +0000 Subject: scripting browsers from Python References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> Message-ID: <87r7fl7lwf.fsf@pobox.com> Olivier Favre-Simon writes: > On Tue, 31 May 2005 00:52:33 -0700, Michele Simionato wrote: > > > I would like to know what is available for scripting browsers from > > Python. [...] > ClientForm http://wwwsearch.sourceforge.net/ClientForm/ > > I use it for automation of POSTs of entire image directories to > imagevenue.com/imagehigh.com/etc hosts. This doesn't actually address what the OP wanted: it's not a browser. > The only drawback I've found are: > - does not support nested forms (since forms are returned in a list) Nested forms?? Good grief. Can you point me at a real life example of such HTML? Can probably fix the parser to work around this. > - does not like ill-formed HTML (Uses HTMLParser as the underlying parser. > you may pass a parser class as parameter (say SGMLParser for greater > acceptance of stupid HTML code) but it's tricky because there is no well > defined parser interface) Titus Brown says he's trying to fix sgmllib (to some extent, at least). Also, you can always feed stuff through mxTidy. I'd like to have a reimplementation of ClientForm on top of something like BeautifulSoup... John From deets at web.de Wed Jun 1 15:00:07 2005 From: deets at web.de (Diez B. Roggisch) Date: Wed, 01 Jun 2005 21:00:07 +0200 Subject: unsigned long to unsigned char In-Reply-To: <1117647790.746043.211110@g43g2000cwa.googlegroups.com> References: <1117647790.746043.211110@g43g2000cwa.googlegroups.com> Message-ID: ashtonn at gmail.com wrote: > Hello, > > Is it possible to convert unsigned long( 4 bytes) to unsigned char(1 > byte), so that i could define a common array for both. > > import array > temp = array('B', '\0' * 512) > > for i in range( 2): > temp[0] = 0xFF > temp[1] = 0xFFFFFFFF use module struct. Diez From dalke at dalkescientific.com Sat Jun 4 15:23:52 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 04 Jun 2005 19:23:52 GMT Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Nicolas Fleury wrote: > I think it is simple and that the implementation is as much > straight-forward. Think about it, it just means that: Okay, I think I understand now. Consider the following server = open_server_connection() with abc(server) with server.lock() do_something(server) server.close() it would be translated to server = open_server_connection() with abc(server): with server.lock() do_something(server) server.close() when I meant for the first code example to be implemented like this server = open_server_connection() with abc(server): with server.lock() do_something(server) server.close() (It should probably use the with-block to handle the server open and close, but that's due to my lack of imagination in coming up with a decent example.) Because of the implicit indentation it isn't easy to see that the "server.close()" is in an inner block and not at the outer one that it appears to be in. To understand the true scoping a reader would need to scan the code for 'with' lines, rather than just looking at the layout. > Good point. As a C++ programmer, I use RAII a lot. And I've used it a few times in Python, before I found out it wasn't a guaranteed behavior by the language. > So I come to another conclusion: the indentation syntax will most of the > time result in a waste of space. Typically a programmer would want its > with-block to end at the end of the current block. A test for how often this is needed would be to look in existing code for the number of try/finally blocks. I have seen and written some gnarly deeply stacked blocks but not often - once a year? That's not to say it's a good indicator. A lot of existing code looks like this def get_first_line(filename): f = open(filename) return f.readline() depending on the gc to clean up the code. A more ... not correct, but at least finicky ... implementation could be def get_first_line(filename): f = open(filename) try: return f.readline() finally: f.close() Almost no one does that. With the PEP perhaps the idiomatic code would be def get_first_line(filename): with open(filename) as f: return f.readline() (Add __enter__/__exit__ semantics to the file object? Make a new 'opening' function? Don't know.) What I mean by all of this is that the new PEP may encourage more people to use indented blocks, in a way that can't be inferred by simply looking at existing code. In that case your proposal, or the one written with abc, defg(mutex) as D, server.lock() as L: .. may be needed. Andrew dalke at dalkescientific.com From jatinder at textualanalytics.com Sat Jun 4 04:52:01 2005 From: jatinder at textualanalytics.com (Jatinder Singh) Date: Sat, 4 Jun 2005 03:52:01 -0500 Subject: No subject Message-ID: <1117875121.42a16bb150ac2@mailbox.textualanalytics.com> Hi guys I am working in a complex directory structure. I want to use a file (not .py) which is in some other directory. I couldn't do it.but if I copy the file in the same directory then it is working fine. Can anybody guide me how and where to add the path of the file. I have tried it with sys.path but it is not for that. -- Regards, Jatinder Singh ? Everyone needs to be loved... especially when they do not deserve it.? From lambacck at gmail.com Wed Jun 8 13:49:51 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Wed, 8 Jun 2005 13:49:51 -0400 Subject: array problems.. OverflowError In-Reply-To: <1118252443.856435.8170@g44g2000cwa.googlegroups.com> References: <1118252443.856435.8170@g44g2000cwa.googlegroups.com> Message-ID: You probably want to look at using struct.pack. That will allow you to back heterogenious groups of data into a string that can be saved to disk or sent over the network. It also does a really good job of taking care of byte order for you(if you tell it to). -Chris On 8 Jun 2005 10:40:43 -0700, ashtonn at gmail.com wrote: > How do i fill 1 byte and 4 bytes in a single array? This array contains > packet information. > > Python code... > > from array import * > > size = 526 > pData = array("B", '\0'* 526) > # Destination MAC address > destAddress = FFFFFFFFFFFF > for i in range(0, len(destAddress), 2): > pData[i/2] = int(destAddress[i:i+2], 16) > > pattern = 0xAAAAAAAA > for i in range( 512): > pData[i+6] = long(pattern, 16) > print pData > > OverflowError: long int too large to covert to int > > def test(pData.buffer_info()[0]) > .... > .... > Any help appreciated. > -Ashton > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From lux at perpetua.org Fri Jun 24 03:18:12 2005 From: lux at perpetua.org (Enrico) Date: Fri, 24 Jun 2005 07:18:12 GMT Subject: Favorite non-python language trick? References: Message-ID: "Joseph Garvin" ha scritto nel messaggio news:mailman.837.1119596150.10512.python-list at python.org... > --This code won't run because it's in a comment block > --[[ > print(10) > --]] > > --This code will, because the first two dashes make the rest a comment, > breaking the block > ---[[ > print(10) > --]] > > So you can change whether or not code is commented out just by adding a > dash. This is much nicer than in C or Python having to get rid of """ or > /* and */. Of course, the IDE can compensate. But it's still neat :) python: """ print 10 """ and #""" print 10 #""" C++: /* print(10); */ and ///* print(10); //*/ ? Bye, Enrico From pink at odahoda.de Sat Jun 4 09:38:20 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Sat, 04 Jun 2005 15:38:20 +0200 Subject: Walking through a mysql db References: Message-ID: Jeff Elkins wrote: > I'm writing a small wxpython app to display and update a dataset. So far, > I get the first record for display: > > try: > cursor = conn.cursor () > cursor.execute ("SELECT * FROM dataset") > item = cursor.fetchone () > > Now, how do I step through the dataset one row at a time? My form has > 'next' and 'back' buttons, and I'd like them to step forward or back, > fetching the appropriate row in the table. I've tried setting > cursor.rownumber by incrementing it prior to the fetchone() w/o effect. You could either execute N-1 fetchone()s before you fetch the Nth dataset (with N starting at 1) or use the 'LIMIT' feature of MySQL: cursor.execute ("SELECT * FROM dataset LIMIT %s,1", n) where n is the index of the requested dataset (starting at 0) -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From cam.ac.uk at mh391.invalid Thu Jun 9 04:00:04 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 09 Jun 2005 09:00:04 +0100 Subject: Writing func_closure? In-Reply-To: References: Message-ID: Fernando Perez wrote: > Yes, I knew of the new.function() approach, but the problem is that I don't know > how to make a fresh closure for it. I can reuse the closure from a different > function, but the docs don't say how to make a valid closure tuple. >>> def makeclosure(x): ... def _f(): ... x ... return _f.func_closure ... >>> makeclosure(42) (,) OK, that's kind of limited. God only knows what happens when there is more than one variable, although you could add extra levels of hackery to do with that. > Many thanks though, I'll probably end up using a less dirty hack :) *Excellent* idea. -- Michael Hoffman From greg.lindstrom at novasyshealth.com Tue Jun 7 11:35:14 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Tue, 07 Jun 2005 10:35:14 -0500 Subject: School Administration Software Message-ID: <42A5BEB2.3040505@novasyshealth.com> Hello- I just picked up my daughters' report cards for the year (they did well, thank-you) and was approached by the school administrator about writing an Acess application to help track attendance for next year (excused/unexcused, after so many unexcused absences a letter will be generated, etc.). Since I have a feel for how large this request will become, I googled for school administration software on the Python site and was pleased to get 312 "hits". There's software out there but -- alas -- it's difficult to tell what is being used, what people think, what's being maintained, etc. So...do any of you have experience with any of this software? This is for a small (~400 students k-12), private school that is not swimming in taxpayer dollars and I would rather use Open Source because we will probably need to customize some reports, etc. Any advice you have would be welcome. Thanks, --greg -- Greg Lindstrom 501 975.4859 (office) Senior Programmer 501 219-4455 (fax) NovaSys Health greg.lindstrom at novasyshealth.com Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. From peter at engcorp.com Thu Jun 9 21:53:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 21:53:19 -0400 Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: Lucas Raab wrote: > Sorry, but Terry just seemed to come off a little too strong. I'm well > aware of the dangers of clicking on a link in an email and the whole > nine yards. I realize that Terry is right, but his attackdog respose was > offputting. "Attackdog" is about as far from an accurate description of Terry's restrained, helpful, and tolerant response as I can imagine. Stick with just "Terry is right" and let's leave it at that. -Peter From kveretennicov at gmail.com Tue Jun 21 09:56:27 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 16:56:27 +0300 Subject: Using code objects? In-Reply-To: <0001HW.BEDD05A1000D6CC7F00FF3B0@smtp.tds.net> References: <0001HW.BEDD05A1000D6CC7F00FF3B0@smtp.tds.net> Message-ID: <4660fe3005062106565aab8536@mail.gmail.com> On 6/21/05, Chinook wrote: > > When I create the code objects though, it seems a couple different ways work > and I'm wondering which is better and why (or is there a more correct > technique in this situation)? > > The two different ways are illustrated below: ... > >>> obj1 = compile(exp1, 'whatever', 'single') ... > >>> obj2 = compile(exp2, 'whatever', 'exec') Are you essentially asking about difference between compile(..., 'single') and compile(..., 'exec'), which is described in http://docs.python.org/lib/built-in-funcs.html ? - kv From Me at Privacy.NET Wed Jun 1 20:37:41 2005 From: Me at Privacy.NET (Jeff_Relf) Date: 2 Jun 2005 00:37:41 GMT Subject: Like a star, I burn bright, dissipating into the night. References: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> Message-ID: Hi eprint10108, Hiding like a rat, You asked me if I was saved ? : http://115639.aceboard.net/forum2.php?rub=158&cat=61&login=115639&page=0#id96 No, I am not, and neither are you. You can't handle reality, can't face your own mortality, so, instead of taking drugs to hallucinate, you get high on Christ. Better to let go of all your attachments, I say. Our world is always and forever ephemeral, everyone and everything goes away, in the long run. My mantra is: Through no fault of my own... I was born. Through no fault of my own... I die. Like a star, I burn bright, dissipating into the night. From grante at visi.com Wed Jun 29 20:14:08 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 30 Jun 2005 00:14:08 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> Message-ID: <11c6eagahug5o73@corp.supernews.com> On 2005-06-29, Luis M. Gonzalez wrote: > Grant Edwards wrote: >> That depends on the accent. I believe that's probably true for >> the educated south of England, BBC, received pronunciation. I >> don't think that's true for some of the other dialects from >> northern areas (e.g. Liverpool) or the "cockney" accent. > > What's exactly the "cockney" accent? http://www.ic.arizona.edu/~lsp/CockneyEnglish.html > Is it related to some place or it's just a kind of slang? I'm > not sure, but I think that I read somewhere that it is common > in some parts of London, and that it is a sign of a particular > social class, more than a regionalism. Is that true? I think it's both. -- Grant Edwards grante Yow! Uh-oh!! I forgot at to submit to COMPULSORY visi.com URINALYSIS! From mg.mailing-list at laposte.net Fri Jun 3 09:47:51 2005 From: mg.mailing-list at laposte.net (mg) Date: Fri, 03 Jun 2005 15:47:51 +0200 Subject: compile python in release... Message-ID: <42A05F87.4050302@laposte.net> Hi, I try to install two Python environments on my platform: one in release, the other in debug. I generate the RELEASE Python environment with the following instructions : > ./configure --prefix=/usr/local/python --enable-shared > make My problem is here : all the source files are compiled with the -g flag which might be the debug flag. (On the other hand, the option -DNDEBUG is defined : it's normal !) Then my question is : Is exist a flag/option to run the shell script named 'configure' allowing to remove the '-g' flag located in the generated makefile ? Thanks From tchur at optushome.com.au Tue Jun 14 14:54:58 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 15 Jun 2005 04:54:58 +1000 Subject: ANN: Version 0.9 of NetEpi Case Manager Message-ID: <42AF2802.1060204@optushome.com.au> Version 0.9 of NetEpi Case Manager is now available via http://www.netepi.org NetEpi Case Manager is a tool (built using Python, the Albatross Web application framework for Python, and PostgreSQL) for securely collecting structured information about cases and contacts of communicable (and other) diseases of public health importance, through Web browsers and the Internet. New data collection forms can be designed and deployed quickly by epidemiologists, using a Web browser 'point-and-click' interface, without the need for knowledge of or training in any programming language. Data can then be collected from authenticated users of the system, who can be located anywhere in the world, into a centralised database. All that is needed by users of the system is a relatively recent Web browser and an Internet connection (?NetEpi? is short for ?Network-enabled Epidemiology?). Development of NetEpi Case Manager has been motivated in large part by the challenge of collecting rapidly changing data from many sources in the event of an outbreak of an emerging communicable disease, such as SARS and HPAI (highly pathogenic avian influenza). However, we hope that it has utility in addressing other distributed, ad hoc data collection problems in the public health and health care domains. A list of prerequisites and installation notes are available at http://sourceforge.net/docman/display_doc.php?docid=28865&group_id=123700 Version 0.9 incorporates a large number of improvements over previous versions, including: * simplification of and cosmetic improvements to the user interface and workflow - sample screenshots available at http://sourceforge.net/project/screenshots.php?group_id=123700; * greater robustness and improved security; * improved validation of field inputs; * the ability to specify help pages (and images) for each question on a form; * the ability to roll-forward data collected with previous versions of a form to the latest version; * the ability to export contact as well as case information in a "flattened" format suitable for analysis and reporting; * comprehensive end-user and administrator guides (the latter over 100 pages long); * additional installation options to allow easier customisation; * much greater speed when deployed via FastCGI on the Web server; * an initial suite of functional tests using the excellent open source Selenium web application test environment, as well as some additional unit tests. We welcome feedback (and bug reports) on this new release, as well as contributions to future releases. Please contact us directly by email or use the NetEpi mailing list (see http://lists.sourceforge.net/lists/listinfo/netepi-discuss ). We have a long list of additional features and potential improvements which could be added to Case Manager, and we would be very happy to hear from experienced Python programmers wishing to contribute to this work. We would also be very happy to hear from anyone willing to do further work on the documentation (using OpenOffice2), and from anyone willing to write additional Selenium test scripts, either in the Selenese scripting language or in Python via the Selenium "driven" mode (or more Python unit tests, for that matter). Tim Churches and Andrew McNamara From peter at engcorp.com Sat Jun 11 09:36:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Jun 2005 09:36:05 -0400 Subject: Best Web dev language In-Reply-To: <11al0nhr4opfgaa@corp.supernews.com> References: <11al0nhr4opfgaa@corp.supernews.com> Message-ID: Jon Slaughter wrote: > I'm trying to get into web development for creating a professional web site > and I'm confused on which language I should use. I've read some comparisons > between the major languages and I was thinking that python might be the way > to go for the most powerful and general language but I am not sure. If you are really interested in the "most powerful and general", then Python is one of only perhaps several options. I wouldn't bother counting something like C++ in the mix, personally... I'd say doing web development with C++ would warrant a quick visit from those nice, young men in their clean, white coats. Perhaps the following pages will be of some assistance, not directly in comparing Python with something else, but with giving the flavour (and, unfortunate or not, diversity!) of Python approaches: http://www.fredshack.com/docs/pythonweb.html http://www.boddie.org.uk/python/web_frameworks.html Michelle Levesque has been comparing several of the most popular in a "bakeoff" at http://pyre.third-bit.com/pyweb/index.html . > Does > anyone know of any detailed and objective comparisons between the major > languages(perl, php, java, javascript, etc...) that might help me get a > clearer picture? No, sorry. I can say, however, that if you want "general purpose" you do not want PHP. In fact, if you're a real programmer you probably don't want PHP. Perl... well, enough has been written about the unreadability of Perl code and the number of ways its arbitrariness can get you into trouble that I'm not going to waste time adding to it. Javascript shouldn't be considered a serious contender for the server-side stuff, though you will quite likely _require_ it for the client side stuff, so keep it in mind but try to minimize your use of it and postpone it as long as you can. (It's not actually that bad a language in many ways, and even has a bit of the same flavour as Python from time to time, in its dynamic nature.) Java? Well, a large number of us here (me included) have spent a fair bit of time with Java and, well, we're here now. (Really, Java is likely a much better candidate than C++ for many reasons. If you are down to a choice of two to make, I suspect it will be between Java and Python, or perhaps Ruby thrown into the mix.) > Also, can anyone recommend any book or web page that gives an introduction > to the method in which one programs web sites? I am not clear on who one, > for instance, would use C++ as the language for a web site except by using > it to create html... I'm not sure if basicaly all languages goal is creating > html dynamically or if there is more to do. What I mean is that basicaly > one is using some other language to wrap the html code or possibly generate > it at run-time for dynamic results. (so all client based web interfaces are > really just html readers but all this "extra" stuff is used to make certain > things easier and dynamic(just as generating tables and forms and all that). That's not a particular bad description. You're really starting from scratch here, aren't you? My advice, since you have such a long way to travel, is to use an "agile" approach and start with some small subset of your overall requirements, the most critical/valuable part, and pick any of the favourite Python frameworks and see how far you can get. If you like the way it went, pick the next most valuable part and then do it. (Keep these down to only a day or two of programming or you'll get bogged down.) The "PyWebOff" page above is actually an excellent demonstration of the approach you should take, and it's already been done by someone else for three or four different frameworks! -Peter From mrmaple at gmail.com Thu Jun 23 07:51:42 2005 From: mrmaple at gmail.com (James Carroll) Date: Thu, 23 Jun 2005 07:51:42 -0400 Subject: Swig wrapping C++ Polymorphism Message-ID: Hi, I asked this on the SWIG mailing list, but it's pretty dead over there... I'm trying to get Python to pass a subclass of a C++ object to another C++ object... I have three C++ classes, TiledImageSource ZoomifyReaderWx which ISA TiledImageSource TiffWriter which has a method which takes a TiledImageSource reader = bright.ZoomifyReaderWx() writer = bright.TiledTiffWriter() writer.SetImageSource(reader) <- doesn't work, error below. TiffWriter has a SetImageSource method that takes a pointer to a TiledImageSource. When I try to pass an instance of ZoomifyReaderWx to TiffWriter, SWIG can't hook the two up. How can I fix this? I think I need a typemap, but I'm not sure of the syntax. Thanks! -Jim Test script ---------------------------- reader = bright.ZoomifyReaderWx() reader.Open("C:/Slides/test.pff") writer = bright.TiledTiffWriter() writer.SetImageSource(reader) writer.CreateFile("C:/Slides/test.tif") while not writer.IsFinished(): writer.ProcessABit() print ".", Exception ---------------------------- C:\jimc\prj\bright\scripts\vsEdit>python piplineTest.py Traceback (most recent call last): File "piplineTest.py", line 11, in ? writer.SetImageSource(reader) File "C:\jimc\prj\bright\scripts\vsEdit\bright.py", line 88, in SetImageSource def SetImageSource(*args): return _bright.TiledTiffWriter_SetImageSource(*ar gs) TypeError: argument number 2: a 'TiledImageSource *' is expected, 'PySwigObject( _p_ZoomifyReaderWx)' is received Interface files (exceprts) ---------------------------- class ZoomifyReaderWx: public TiledImageSource { public: bool Open(wxString filename); void Close(); ZoomifyReaderWx(); //%pragma(python) addtomethod = "__init__:self._setOORInfo(self)" // necessary for ZoomableImageReader virtual int GetWidth(int reduction = 0); virtual int GetHeight(int reduction = 0); ... class TiledTiffWriter { public: TiledTiffWriter(); //%pragma(python) addtomethod = "__init__:self._setOORInfo(self)" void SetImageSource(TiledImageSource *source); void SetJpegQuality(int quality) { m_iJpegQuality = quality; } void CreateFile(char *filename); ... class TiledImageSource { public: //%pragma(python) addtomethod = "__init__:self._setOORInfo(self)" virtual int GetWidth(int reduction = 0); virtual int GetHeight(int reduction = 0); From jello at comics.com Wed Jun 1 17:52:08 2005 From: jello at comics.com (rzed) Date: Wed, 01 Jun 2005 17:52:08 -0400 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> Message-ID: "Thomas Bartkus" wrote in news:5uGdnfiX3aSnRADfRVn-1Q at telcove.net: > "rzed" wrote in message > news:Xns9667883C1D343jreeder at 63.223.7.253... > >> So what do you think? What's wrong with the picture? Why isn't >> there a greater priority to work in this direction? > > > What's wrong with the picture? > > Just one teeny little item. > > The Python world lacks the phenomenally successful development > models enjoyed by the now ancient Turbo Pascal, Delphi and > Visual Basic. > AND > If the likes of Visual Basic can have it, then it becomes > really, *really* hard to convince the world that Python is a > serious, professional system. > > At some point, one has to break out of theory and produce! > Or challenge the theory with some hard questions. > I'm not thinking only of a Drag & Drop graphical development interface (and in fact there are several available now, all of which work with some degree of similarity to VB). It might be nice to have, but I've used a lot of systems that could crank out tolerable windows with a relatively small amount of text entry. Those who have used Cognos' Powerhouse, for instance, or Magic, or even dBase (maybe that's a stretch) can testify to that, I think. But there is a common need for production of systems where data- entry and data views are required. Typically, the back end is a database, though it need not be. It's not that hard to build such a system using any one of the packages, particularly once you acquire expertise with that package. But should you want to switch to another package, you find that a *lot* has to change in your applications, no matter how hard you've tried to separate the presentation from the logic, just because the requirements of the various systems differ so much. It might be that you have to reorder parameter lists, or subtract parameters, or insert some. Almost never can you simply use a different import statement alone to change the underlying windows handler. If you need to add new parameters, almost never can you simply append them to an existing parameter list and expect the thing to work. And if you do change to the new system, your code can no longer work using the old system. A lot of this is just because of the way interfaces are specified; for some call on system A you need, let's say: (a)a label, (b)a size (which must be a tuple, not a list), (c) a boolean value. Now you switch to system B, which does not name the equivalent call the same, nor does it pass in the same parameters, or not in the same sequence. Multiply this by all the api calls you have, and you may as well start over with each package as try to make it all work. It seems to me that Python (the language, not the package) is intended in part to make tasks like that easier. It would be better if the call for a given function were named the same (in your application code), and if you could simply append some new parameters to make the new system function (knowing that its interface would simply ignore the old parameters it did not understand), well, that's not too hard, and it doesn't break the old system. So you add what you need to (if you need to add anything), and now you have a system that runs on two packages. All you have to do is to import the one you have, or want to use. It means the package writer has to create an API bridge, one that maps the underlying package's api to the Python standard api. The application writer doesn't or shouldn't have to worry about that mapping. And it probably means that dictionaries (or something similar) are used to pass most parameters. This sounds chaotic, as though interfaces would suddenly be impossible to document, but it need not be so. If a package has a feature that cannot be mapped reasonably to the Python api, then add to the Python api, or (as part of the Python api) allow a system pass-through the package's api can interpret. If the package doesn't get the information it needs, it will complain, just as it does now. Its requirements will be documented just as they are now. It's not that all applications would run on all systems without change, but that essentially all *basic* applications would run on any system that supported the same basic operations without change. There are many widgets, and as windowing packages become slicker, there are more options; eventually, as the options become universal (or at least common) they would be added to the Python api. Whether or not a D&D GDI would make this better would still be up to the individual programmer, I'd think. It would be a heck of a lot easier to *write* a GUI if you weren't overly concerned with the underlying graphics package. -- rzed From benji at benjiyork.com Mon Jun 27 23:18:41 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 27 Jun 2005 23:18:41 -0400 Subject: Better console for Windows? In-Reply-To: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: <42C0C191.6050102@benjiyork.com> Brett Hoerner wrote: > Is there a different shell I can use (other than cmd.com) to run Python > in, where I can full-screen the window (if I pleased), etc? As it is, > things that would run far off the right have to be word wrapped after > very few characters. To make the console full screen hit Alt-Enter. The same thing makes it windowed again. To accommodate very long lines click the "C:\" icon in the upper left corner of the window, choose "Properties" and then change the "Screen Buffer Size" Width and Height to something more to your liking. While you're there I'd recommend turning on "QuickEdit Mode" on the "Options" tab. Then you can drag with your left mouse button to select an area of text, right click to copy, then right click again to paste. -- Benji York From nidoizo at yahoo.com Sun Jun 5 23:29:45 2005 From: nidoizo at yahoo.com (Nicolas Fleury) Date: Sun, 05 Jun 2005 23:29:45 -0400 Subject: For review: PEP 343: Anonymous Block Redux and GeneratorEnhancements In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE72128D@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE72128D@au3010avexu1.global.avaya.com> Message-ID: Delaney, Timothy C (Timothy) wrote: > Nicolas Fleury wrote: >>def getFirstLine(filename): >> with opening(filename) as file >> return file.readline() > > Your tastes definitely disagree with the majority of Python programmers > then, including Guido. Scoping is defined in Python by indentation. I'm very happy to met someone who can speak for the majority of Python programmers, I should have chat with you in the first place;) But you're right, that would make a precedent in Python, and that is probably what makes my proposal so bad. Someone could argue that this should be allowed too: with locking(lock) if condition with opening(filename) as file for line in file ... And that's horrible IMO (and a no-no to me). About the majority of Python programmers, a lot of newcomers come from languages where you don't have to make a new block for an acquire/release pattern. Also, the following syntax: decorate staticmethod: def foo(): ... have been rejected for decorators. All this to say that over-indentation can be an issue. > If you want the above sort of thing, you're going to have to write a new > PEP, and I'd be very surprised to see it accepted. But there's nothing > stopping you from doing so. > > >>def getFirstLine(filename): >> with opening(filename) as file: >> return file.readline() > > This is beautiful and explicit. What else could you want? Did you deliberately keep that example instead of the other one in the message? with locking(lock): if condition: with opening(filename) as file: for line in file: ... It is definately explicit, but beautiful? Add to that the indentation of the class, of the method, a few more with-statements and you end up with something that makes it difficult to respect PEP008 (4 spaces indentation and lines < than 80). Compare that with the += like operators. It is not beautiful, but very usable. The same can be said for @decorators. > The syntax: > > with EXPR1 as VAR1, EXPR2 as VAR2: > ... That syntax doesn't help in the previous example. > was discussed on python-dev. It wasn't explicitly rejected, but the > feeling seemed to be that it was an unnecessary complication as far as > PEP 343 is concerned. There's nothing stopping another PEP proposing > this as an extension to PEP 343, and there's nothing stopping that being > in Python 2.5 if it's accepted. I totally agree. I don't want to change PEP343, but keeping the door open for a no-indentation syntax is a good idea. > PEP 343 was originally PEP 340 (and several other things) and was quite > complicated at one point (it originally contained PEP 342 as well). The > PEP in its current state represents 2 months of discussion, complication > and (finally) simplification. Its semantics are clear and unambiguous. > And (as Guido states) it will obsolete 4(?) other PEPs. I know, and I followed these discussions even in vacation. I'm very happy with the result. I'm just pointing that it will result in over-indented code. In some situations indentation is necessary anyway, so the PEP syntax is fine. Will I write a PEP for that? Maybe. I think the first step is to just use with-statements in real-life code and see how it comes. But I will not be surprised if it is added someday. Regards, Nicolas From michael at stroeder.com Tue Jun 21 11:13:24 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 21 Jun 2005 17:13:24 +0200 Subject: ANN: python-ldap-2.0.8 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.8 2005-06-22 at Linuxtag 2005, Karlsruhe, Germany Changes since 2.0.7: * Preliminary support for receiving LDAP controls added. Contributor: - Andreas Ames Lib:/ - Added classes in module ldif to ldif.__all__ to fix from ldif import * - Removed BitString syntax from ldap.schema.models.NOT_HUMAN_READABLE_LDAP_SYNTAXES since the LDAP encoding is in fact human-readable - ldapurl.LDAPUrlExtension.unparse() outputs empty string if LDAPUrlExtension.exvalue is None - Added ldap.controls.SimplePagedResultsControl ---------------------------------------------------------------- Released 2.0.7 2005-04-29 Changes since 2.0.6: * Added preliminary support for sending LDAP controls with a request. Contributors: - Deepak Giridharagopal - Ingo Steuwer (Receiving controls in LDAP results still not supported.) Modules: * LDAPObject.c: removed l_ldap_manage_dsa_it() * LDAPObject.c: Added missing #ifdef around l_ldap_passwd() for compability with older OpenLDAP libs. Lib:/ * New algorithm in ldap.schema.tokenizer.split_tokens() contributed by Wido Depping which is more robust when parsing very broken schema elements (e.g. Oracle's OID). * Fixed argument list (position of timeout) when calling LDAPObject.search_ext_s() from search_st() and search_s(). * LDAPObject.search_ext_s() correctly calls search_ext_s() now. * Re-implemented LDAPObject.manage_dsa_it() without calling _ldap. From petr at tpc.cz Mon Jun 13 22:20:53 2005 From: petr at tpc.cz (McBooCzech) Date: 13 Jun 2005 19:20:53 -0700 Subject: just learning eric ide References: <28706111.YDTNr6pyWa@teancum> Message-ID: <1118715653.712787.160770@g47g2000cwa.googlegroups.com> Try this: http://www.pycs.net/lateral/stories/16.html HTH Petr From xah at xahlee.org Tue Jun 21 04:54:40 2005 From: xah at xahlee.org (Xah Lee) Date: 21 Jun 2005 01:54:40 -0700 Subject: tree functions daily exercise: Table In-Reply-To: <1119075715.004033.169450@g14g2000cwa.googlegroups.com> References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> Message-ID: <1119344080.480368.161850@o13g2000cwo.googlegroups.com> here's the Python spec for the Table function: '''Table(f,[iStart,iEnd,iStep]) returns a list of f applied to the range range(iStart,iEnd,iStep). Example: Table(f,[3,10,2]) returns [f(3),f(5),f(7),f(9)] Table(f,[iStart,iEnd,iStep], [jStart,jEnd,jStep], ...) returns a nested list of f(i,j,...) applied thru the iterators. Example: Table(f,[1,3,1],[2,6,2]) returns [f(3),f(5),f(7),f(9)]''' it is slightly shortcut from the full form in that it doesn't allow short cut conveniences. For example, one should be able to write Table(f,[i,4], [j,1,9,2]) for Table(f,[i,1,4,1], [j,1,9,2]) anyhow, for simplicity, let's start with this simpler spec. I started to code this problem but this is quite a large problem, so i figured it'd be fruitful to discuss it as we go. The first problem i noted is that in Python, one cannot assign elements in arrays where it doesn't exist yet. i.e. a[7]=2 is illegal. This is in contrast to Perl, where one can do: $a[3][7][2]=4 and automatically have a 3-dimentional nested array, where other members simply have undefined values. (This behavior of Perl is convenient when needed, but i recall in 2001 i spend the whole half a day trying to debug a program and it turned out is caused by this behavior.) With perl, a solution is to have Table simply generate the following text and eval it. -------------- my ($i,$j,$k,); my @resultArray; foreach $i (0 .. scalar(@{$ref_rangeSequence->[0]}) -1 ) { foreach $j (0 .. scalar(@{$ref_rangeSequence->[1]}) -1 ) { foreach $k (0 .. scalar(@{$ref_rangeSequence->[2]}) -1 ) { $resultArray[$i][$j][$k] = &{Function(\@parameterList,$exprString)} ($ref_rangeSequence->[0]->[$i],$ref_rangeSequence->[1]->[$j],$ref_rangeSequence->[2]->[$k],); };};}; return \@resultArray; ------------ (in the above code, note the line $resultArray[$i][$j][$k]=...) Another issue noted is that the so-called ?list comprehension? syntax construction in Python actually also contained a semantic irregularity. That is to say, when the loops are nested inside a list-comprehension, it still produced a flat list, instead of a nested list. This is quite a pain. I didn't realize this until i completed my code and realized the result is a flat list. Here's the "wrong" code as a result: def Table2(fun, *itrs): dim=len (itrs) dummies = ['i'+repr(i) for i in Range(0,dim-1)] ll = [ (dummies[i],itrs[i][0],itrs[i][1],itrs[i][2]) for i in Range(0,dim-1)] funString='f(' for i in dummies: funString += i + ',' funString = funString[0:len(funString)-1] funString += ')' loopStr= '[ ' + funString for i in range(0,dim): loopStr += ' for ' + dummies[i] + ' in Range(' + repr(itrs[i][0])+','+repr(itrs[i][1])+','+repr(itrs[i][2]) + ') ' loopStr += ' ]' print loopStr return eval(loopStr) I was happy thinking that i'm done until am really dismayed by a realization of this semantic irregulary. Both syntax irregularity and semantic irregularity are ubiquitous in imperative languages. So, now i have two choices: (1) add another code to make a structure out of a flat list. e.g. turn [1,2,3,4,5,6] to [[[1,2]],[[3,4]],[[5,6]]] (2) rewrite the Table function to not use list comprehension. Instead, use for loops. I started to do (1) by writing a separate Partition function... bun in the process i think perhaps (2) is better... ---------------- References: ? for a context of this message, see: http://xahlee.org/tree/tree.htm ? for a exposition of syntax aspects of irregularity of Python's ?list-comprehension?, see http://xahlee.org/perl-python/list_comprehension.html Xah xah at xahlee.org ? http://xahlee.org/ From fredrik at pythonware.com Mon Jun 13 06:48:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Jun 2005 12:48:07 +0200 Subject: About size of Unicode string References: <42A48B19.5030201@geochemsource.com> <20050606184435.840F03182FF@newton.cujae.edu.cu> Message-ID: Frank Abel Cancio Bello wrote: > Can I get how many bytes have a string object independently of its encoding? strings hold characters, not bytes. an encoding is used to convert a stream of characters to a stream of bytes. if you need to know the number of bytes needed to hold an encoded string, you need to know the encoding. (and in some cases, including UTF-8, you need to *do* the encoding before you can tell how many bytes you get) > Is the "len" function the right way of get it? len() on the encoded string, yes. > Laci look the following code: > > import urllib2 > request = urllib2.Request(url= 'http://localhost:6000') > data = 'data to send\n'.encode('utf_8') > request.add_data(data) > request.add_header('content-length', str(len(data))) > request.add_header('content-encoding', 'UTF-8') > file = urllib2.urlopen(request) > > Is always true that "the size of the entity-body" is "len(data)" > independently of the encoding of "data"? your data variable contains bytes, not characters, so the answer is "yes". on the other hand, that add_header line isn't really needed -- if you leave it out, urllib2 will add the content-length header all by itself. From rex.eastbourne at gmail.com Sun Jun 26 14:48:46 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 26 Jun 2005 11:48:46 -0700 Subject: Running Python interpreter in Emacs In-Reply-To: References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> Message-ID: <1119811726.576282.59500@g49g2000cwa.googlegroups.com> I went to My Computer | Properties | Advanced | Environment Variables and added c:\program files\python24 to both the PYTHONPATH and Path variables. Still no luck. I don't know whether the path I'm talking about is the same as the $PATH you referred to, or whether I'm supposed to put python.exe explicitly somewhere; could someone refer me to a place where I can read about these things? Thanks! Rex From http Wed Jun 22 18:52:45 2005 From: http (Paul Rubin) Date: 22 Jun 2005 15:52:45 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> Message-ID: <7xoe9y3sxu.fsf@ruckus.brouhaha.com> Scott David Daniels writes: > > Negative 0 isn't a NaN, it's just negative 0. > Right, but it is hard to construct in standard C. Huh? It's just a hex constant. From skip at pobox.com Fri Jun 3 17:01:17 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 3 Jun 2005 16:01:17 -0500 Subject: Python interest group software In-Reply-To: <20050603204724.GB8195@goliath.ag.com> References: <20050603204724.GB8195@goliath.ag.com> Message-ID: <17056.50461.644952.876939@montanaro.dyndns.org> David> Is there already any software out there to manage a Python David> Interest Group? Something that can register users, take RSVPs for David> meetings, etc. I suspect a fair number take advantage of meetup.com. Skip From cappy2112 at gmail.com Thu Jun 9 14:35:11 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 9 Jun 2005 11:35:11 -0700 Subject: Generating HTML from python In-Reply-To: References: Message-ID: <1118342111.655843.85940@o13g2000cwo.googlegroups.com> I looked at HTMLGen a while ago- I didn't see what the advantage was. I wrote soem code similar to the example above, to generate a page.. It worked out fine. However, I want to add HTML ouput to many of my other python programs, and I don't want to re-write this for each program. So some higher level of abastraction is needed, but I don't know how just yet. HTMLGen is no longer maintained, so I don't know what the best choice is. If you know the basics of HTMl, you can write a simple class to write the html, and just call a method from your program, so your app does not have any HTML in it. Philippe C. Martin wrote: > Thanks a bunch, > > I'm currently playing with HTMLGen (great but not in Python distrib ...) and > it look very good - Yet your code example looks simple enough for me to > look at that alternative. > > > > > Thomas Guettler wrote: > > > Am Thu, 09 Jun 2005 12:43:19 +0000 schrieb Philippe C. Martin: > > > >> Hi, > >> > >> I wish to use an easy way to generate reports from wxPython and feel > >> wxHtmlEasyPrinting could be a good solution. > >> > >> I now need to generate the HTML wxHtmlEasyPrinting can print > > > > I don't know wxPython, but generating HTML is very easy. > > > > Some people say mixing HTML and programming code is not good. > > > > But if you want to create dynamic pages with more logic than HTML > > this is the best solution. > > > > Example: Multiplication Table > > > > rows=[] > > heading=[] > > for i in range(1, 11): > > heading.append('%s' % i) > > cols=[] > > for j in range(1, 11): > > cols.append('%s' % (i*j)) > > row='%s%s' % (i, ''.join(cols)) > > rows.append(row) > > html=""" > > > > Multiplication Table > > > > > > > > %s > > > > %s > >
 
> > > > """ % (''.join(heading), ''.join(rows)) > > > > I guess this looks more ugly in most template languages. > > > > HTH, > > Thomas > > From ivanlan at pauahtun.org Sat Jun 18 08:47:59 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Sat, 18 Jun 2005 06:47:59 -0600 Subject: functions with unlimeted variable arguments... References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> <7xr7f0yv0c.fsf@ruckus.brouhaha.com> Message-ID: <42B417FF.A51177B5@pauahtun.org> Hi All-- Paul Rubin wrote: > > "Xah Lee" writes: > > but are there other solutions? > > > > Xah > > Geez man, haven't you been around long enough to read the manual? > > def f(*a): return a > He's been around long enough to rewrite the manual. Metta, -ly y'rs, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From Ara.T.Howard at noaa.gov Wed Jun 8 11:49:51 2005 From: Ara.T.Howard at noaa.gov (Ara.T.Howard) Date: Wed, 8 Jun 2005 09:49:51 -0600 Subject: MoinMoin WikiName and python regexes Message-ID: hi- i know nada about python so please forgive me if this is way off base. i'm trying to fix a bug in MoinMoin whereby WordsWithTwoCapsInARowLike ^^ ^^ ^^ do not become WikiNames. this is because the the wikiname pattern is basically /([A-Z][a-z]+){2,}/ but should be (IMHO) /([A-Z]+[a-z]+){2,}/ however, the way the patterns are constructed like word_rule = ur'(?:(? Message-ID: <87vf417lem.fsf@lucien.dreaming> Matt Hollingsworth writes: > What are some good options that people commonly use so that they can > easily and quickly identify variable with just a glance? Use an editor that has a Python syntax highlighting mode, for example Emacs with python-mode, Vim, or the IDLE IDE that comes with Python. -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From roccomoretti at hotpop.com Tue Jun 28 19:55:04 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 28 Jun 2005 18:55:04 -0500 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: Rocco Moretti wrote: > It's been quite some time since I've looked at Forth, and the reference > material that I used then was probably outdated anyway. Sorry, thought of one more thing Python has going for it vs. Forth - reference material. Check the catalog of your local library. I'd guess that there is more choice for Python programming books vs. Forth programming books. If your local library does have a Forth book, it's likely that it'll be discussing some 1970's interpreter that ran on a now-defunct timesharing system, if mine is any indication. If you can afford to buy books, the selection at a new or used bookseller is going to be *much* better with Python than with Forth. My local new bookseller has at least a shelf of Python books. I don't think I saw any Forth ones last time I was there - they might have had a single title that I missed. From pmaupin at gmail.com Fri Jun 24 03:07:03 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 24 Jun 2005 00:07:03 -0700 Subject: PEP 304 - is anyone really interested? References: <1119567362.026775.272080@g44g2000cwa.googlegroups.com> <11bn2j3s4a18586@news.supernews.com> Message-ID: <1119596823.822935.242590@o13g2000cwo.googlegroups.com> John Roth wrote: > I'd like to suggest a different mechanism, at least for packages > (top level scripts don't generate .pyc files anyway.) Put a system > variable in the __init__.py file. Something like __obj__ = path > would do nicely. Then when Python created the __init__.pyc file, > it would insert a back link __src__ entry. I like the kernel of that proposal. One down-side is that you might wind up compiling at least __init__.py on every execution which imports the package (to extract the object directory variable __obj__). If you had automatic .pyc directory creation and updating of __obj__ for sub-packages, you would only take the hit of recompiling the topmost __init__.py in a package tree. I'm not as sure about the use of the backlink -- it seems to introduce a little bit of a chicken/egg problem to be able to import from a .pyc directory which knows where its .py directory is -- how did the .pyc files get there in the first place? There must have been a separate compilation phase at some point, and while I can envision a use case for that, I don't have a pressing need for it. I'm also not sure about the extent of the changes required to the import/compile mechanism. It seems the importer would have to be able to defer writing out the .pyc file until after the execution of the body of the __init__.py module. Finally, I think you're dismissing one of the discussed use-cases out of hand :) Although it is true that a top-level script will not generate a .pyc file, a slightly more generic use of the term "script" could encompass a top-level module and one or more sub-modules in the same directory. If the script is run infrequently enough and the sub-modules are small enough, in some cases I would certainly love to be able to tell Python "Please don't litter this directory with .pyc files." Assuming the deferral of writing .pyc files until after module execution is is not a problem (for all I know it already works this way, but I wouldn't know why that would be), I think a slightly more fleshed out (but still very green) proposal might be: 1) When a module is first imported, the importing module's globals are searched for an __obj__ identifier. The importer will make a local copy of this variable during the import: objdir = passed_globals.get('__obj__', None) 2) If a .pyc/.pyo file is found in the same directory as the coresponding .py file: a) If the .pyc/.pyo is newer, it is loaded and executed and we are done; or b) objdir is set to None to indicate that we should regenerate .pyc/.pyo in situ. Step b) could be debated, but I think it would be very confusing to have an out-of-date .pyc file in a directory, with the "real" .pyc file elsewhere... 3) If this is a package import and objdir is a non-null string, objdir is updated to include the package name. Something like: if is_package and objdir: objdir = os.path.join(objdir, package_name) 4) If objdir is a non-null string and there is a newer readable .pyc/.pyo file at the directory indicated in objdir, that file is loaded and executed and we are done. 5) The source file is compiled into memory. 6) If objdir is not None the globals of the newly created module are updated such that __obj__= objdir. 7) The module body is executed, including performing any sub-imports. 8) The module's __obj__ is now examined to determine if and where to write the module's .pyc/.pyo file: if __obj__ does not exist -- write to same directory as .py (same as current behavior) if __obj__ exists and is a non-empty string and is equal to objdir (e.g. not modified during initial module body execution) -- write to the named directory. Create the leaf directory if necessary (e.g. for package imports). if __obj__ exists and is the empty string, do not create a .pyc file. This allows author suppression of writing .pyc files. if __obj__ exists but is not equal to objdir, create the leaf directory if it does not exist, but do not write the .pyc file. This is an optimization for the case where __init__.py specifies a new package subdirectory -- why write out a .pyc file if you won't know where it is until you re-compile/re-execute the source .py file? You'll never be able to make use of the .pyc file and maybe you don't even have write privileges in the directory. Even though this is true, we still want to create the directory, so that sub-package imports don't have to create multiple directory levels. I think this mechanism would allow for the following: - Control of package/subpackage .pyc file location with a single line of code in the topmost __init__ file, at the small cost of recompiling the __init__ file on every program execution. - Control of _all_ .pyc file location (unless overridden for a given package as described above) from a top-level script. In this case, regular .pyc files would wind up _inside_ the __obj__ directory of the package which first imported them, and package .pyc files would wind up in a subdirectory underneath the directory of the package which first imported them. This is not a major issue for scripts which follow consistent import execution flow, but could be surprising to a first-time user of the control mechanism, and could increase disk space usage a tiny bit. - Suppression of writing of .pyc files from a top-level script by setting __obj__= ''. Preexisting .pyc files would be used (and overwritten if the corresponding .py is newer), but .pyc files would not be generated if they did not already exist. In addition, it might be possible to implement this mechanism to enable generation of .pyc files for zip-imported packages (as with using this mechanism with regular packages, the __init__.pyc file would not be written out, but it could define where to look for the other .pyc files). This could potentially be a huge performance gain for some zip imports. > Actually, the PEP states that if the environment variable does > not specify a directory then it does not generate a .pyc file. > Any entry that is not a directory would do, such as some special > characters that are illegal in file and directory names. It is my understanding (the capabilities of bash and other shells notwithstanding) that the only truly "illegal" filename characters under Posix are the slash and the null character. So, for a full path (as opposed to a single name), the only illegal character would be the null character, which is probably pretty hard/ugly to inject into an environment variable from a shell under either Windows or Linux. I suppose you could try to usurp special combinations, such as "//", except I think Microsoft has already done that :) Even if you found a combination that Microsoft didn't claim, I would personally find it very unPythonic to document the required use of something like "badname//". In any case, if we are re-thinking the PEP, and we find a use-case for something like your __obj__ proposal, but don't find such a good use-case for the environment variable, I would recommend leaving the environment variable out of the PEP, since its presence would add a security concern for people who are running SUDO python scripts when they upgrade to a version of Python which honors the environment variable. Regards, Pat From dirk.dierickx at liamg.moc Sat Jun 11 08:01:51 2005 From: dirk.dierickx at liamg.moc (dirk dierickx) Date: Sat, 11 Jun 2005 14:01:51 +0200 Subject: Hiding X windows Message-ID: All, I'm looking for a way to hide opened windows in X, these windows can be using any widget-set so it will not target gtk, qt, motif, etc directly (I know how to do it in gtk for example, but this will only work for gtk apps ofcourse). Just an easy way to select a certain window and hide it, is anything like this possible? thanks, -- Don't let your mind wander -- it's too little to be let out alone. From hsuanyeh at yahoo.com Sat Jun 4 21:03:25 2005 From: hsuanyeh at yahoo.com (Hsuan-Yeh Chang) Date: Sun, 05 Jun 2005 01:03:25 GMT Subject: Why Eric3 does not have any documentation or FAQ? Message-ID: Dear All, Does anyone know why? HYC From steven.bethard at gmail.com Fri Jun 24 22:21:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 24 Jun 2005 20:21:06 -0600 Subject: formatted xml output from ElementTree inconsistency In-Reply-To: References: Message-ID: Matthew Thorley wrote: > from elementtree import ElementTree as et > > xmla = et.ElementTree('some_file.xml') > xmlb = et.Element('parent') > et.SubElement(xmlb, 'child1') > et.SubElement(xmlb, 'child2') > > root = et.Element('root') > root.append(xmla.getroot()) > root.append(xmlb) > > print et.tostring(root) [snip] > Is their a function to 'pretty print' an element? Depends on how pretty you want it. I've found that putting each element on its own line has been sufficient for many of my manual-inspection use cases. This isn't too hard with a cheap hack: py> import elementtree.ElementTree as et py> root = et.Element('root') py> parent = et.SubElement(root, 'parent') py> child = et.SubElement(parent, 'child') py> print et.tostring(root) py> print et.tostring(root).replace('><', '>\n<') Not ideal, but it may work well enough for you. STeVe From graham.fawcett at gmail.com Thu Jun 30 10:27:47 2005 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 30 Jun 2005 07:27:47 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <1120141667.753928.40750@f14g2000cwb.googlegroups.com> Steven D'Aprano wrote: > Speaking as an Australia, ... > [snip] > But don't worry, there is one thing we all agree on throughout the > English-speaking world: you Americans don't speak English. And lest you feel Steven's observation don't bear much weight, keep in mind that he is speaking as an entire continent. ;-) But, speaking as Antarctica, I must disagree. I don't think the Keepers of the Canon of the English Language(tm) would hold up either your Strine or our Canadian regional accents as examples of Real English Pronunciation(tm). But that's the kind of thing that canon-keepers obsess about, while the rest of us just get along and communicate with one another. (By "us", I mean "us people", not "us continents" -- I stopped speaking as Antarctica a few lines back.) keep-your-stick-on-the-ice'ly yours, Graham From kent37 at tds.net Sat Jun 4 05:55:18 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 05:55:18 -0400 Subject: how to get name of function from within function? In-Reply-To: References: Message-ID: <42a17a49$1_1@newspeer2.tds.net> Christopher J. Bottaro wrote: > Steven Bethard wrote: > [...snip...] > >>Yes, has's suggestion is probably the right way to go here. I'm still >>uncertain as to your exact setup here. Are the functions you need to >>wrap in a list you have? Are they imported from another module? A >>short clip of your current code and what you want it to do would help. > > > But I want to avoid having to write each wrapper myself. As it is now, when > I want to add a public method to my class named myFunc, I first write > myFunc which is a wrapper to the implementation: > > def myFunc(self): > try: self.myFuncIMPL() > except: # error handling code > > def myFuncIMPL(self): > # do the real stuff here, no need to worry about error handling stuff > # cuz its done in the wrapper > > I guess I'm just lazy, but I don't want to write the wrapper func for each > new func I want to add. I want it done automatically. You can do this almost automatically with a decorator: def in_try(func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: print "entered except" raise return wrapper class C(object): @in_try def func_a(self): print "func_a" @in_try def func_b(self): print "func_b" raise Exception You could probably create a metaclass to apply the wrappers automatically but I like having it explicit as above. Kent From deets at web.de Thu Jun 23 09:25:06 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 23 Jun 2005 15:25:06 +0200 Subject: Looking For Geodetic Python Software In-Reply-To: References: <447po2-iqt.ln1@eskimo.tundraware.com> Message-ID: <3hvrhjFj3qfmU1@uni-berlin.de> Tim Daneliuk wrote: > Casey Hawthorne wrote: >> >> Do your planes fly over the earth's surface or through the ground? > > > Why do you presume this has anything to do with airplanes? > That was supposed to be a funny remark regarding that your "straight-line-distance" makes no sense at all - because that would mean that you'd have to go underground. So it has no real-world-application - unless you actually have underground-planes ;) Diez From dlc at io.frii.com Fri Jun 17 15:27:31 2005 From: dlc at io.frii.com (Dennis Clark) Date: Fri, 17 Jun 2005 19:27:31 -0000 Subject: add new modules? References: <11b65f7bjjt7a51@corp.supernews.com> Message-ID: <11b6913k7jpjkb7@corp.supernews.com> Thanks all, My problem came when I set PYTHONHOME, apparently that is a bad thing (in this case). I know that I set it to the directory that python was in, but something about that was "bad". now everything works. DLC Robert Kern wrote: : Dennis Clark wrote: : > This is a total newb question, you have been warned... : > : > I've been all over the www.python.org site and googled, but I've not : > found just how to add new modules. I've tried setting PYTHONPATH, : > I've tried putting the new module directories into the site-packages : > directory, I've tried creating the .pth files, I've even done all : > three of these things at the same time and still my python script : > refuses to import. What is the cannonical way to add new modules : > to python? I am running on OS X 10.4 (Macintosh obviously) on basically : > freeBSD, os I'm doing UNIX type stuff at the console. : If you are using the Apple-supplied Python 2.3.5, put the modules in : /Library/Python/2.3/site-packages/ . If you are using Bob Ippolito's : Python 2.4.1, then it's : /Library/Frameworks/Python.framework/Versions/Current/lib/python2.4/site-packages : . : -- : Robert Kern : rkern at ucsd.edu : "In the fields of hell where the grass grows high : Are the graves of dreams allowed to die." : -- Richard Harter -- ============================================================================ * Dennis Clark dlc at frii.com www.techtoystoday.com * * "Programming and Customizing the OOPic Microcontroller" Mcgraw-Hill 2003 * ============================================================================ From jepler at unpythonic.net Sat Jun 4 19:35:43 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 4 Jun 2005 18:35:43 -0500 Subject: method = Klass.othermethod considered PITA In-Reply-To: <87oeallp44.fsf@pobox.com> References: <87oeallp44.fsf@pobox.com> Message-ID: <20050604233539.GA12122@unpythonic.net> On Sat, Jun 04, 2005 at 10:43:39PM +0000, John J. Lee wrote: > 1. In derived classes, inheritance doesn't work right: Did you expect it to print 'moo'? I'd have been surprised, and expected the behavior you got. > 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do > this. In all the versions of Python I've used, classes are pickled by name. This example you wrote doesn't pose any special problem when pickling. >>> pickle.dumps(A) 'c__main__\nA\np0\n.' >>> pickle.dumps(B) 'c__main__\nB\np0\n.' Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tjreedy at udel.edu Mon Jun 6 00:22:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 6 Jun 2005 00:22:12 -0400 Subject: default values of function parameters References: Message-ID: "David Isaac" wrote in message news:piPoe.8518$ld3.1868 at trnddc04... > But the default values of function parameters seem rather like a static > attributes of a class. > Is that a good way to think of them? If you think of a function as defining a subclass of execution instances, with __init__ inherited from the superclass, then that is a possible way to think of them. Goodness depends on your meaning of goodness ;-). Does it help you write and use Python functions acurately? > If so, are they somehow accessible? > How? Under what name? This is implementation specific. For CPython, the interactive interpreter is your friend. Learn to use it! >>> def f(): pass ... >>> dir(f) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__ge tattribute__', '__hash__', '__init__', '__name__', '__new__', '__reduce__', '__r epr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] Now give f some parameters with defaults and print f.func_defaults. Terry J. Reedy From meren at uludag.org.tr Thu Jun 23 16:43:30 2005 From: meren at uludag.org.tr (A. Murat Eren) Date: Thu, 23 Jun 2005 23:43:30 +0300 Subject: zipfile + symlink.. Message-ID: <200506232343.33577.meren@uludag.org.tr> Hi, I have a problem about zipfile. I'm trying to add files from local file system into a zip file via zipfile module of python.. I have a function in my class which recursively adds files or dirs into zip: -------8<-------------------8<--------------------8<------------------8<----- def add_file(self, fileName): """add file or directory to a zip file""" if os.path.isdir(fileName): self.zip.writestr(fileName + '/', '') for f in os.listdir(fileName): self.add_file(fileName + '/' + f) else: if os.path.islink(fileName): dest = os.readlink(fileName) self.zip.writestr(fileName, dest) #do something here to set 'fileName's attributes #to write it as a symlink into the zip else: self.zip.write(fileName, fileName, zipfile.ZIP_DEFLATED) ------->8------------------->8-------------------->8------------------>8----- But here is a problem raising for symlinks (at the commented section of the code passage).. If i don't perform any special process for symlinks in the function, function produces zip files without symlinks, naturally; symlinks become regular files with the 'dest' content.. I have to set the attribute of the symlinks in the zip to make them a real symlink for the 'dest', how can i do that? Any help or idea would be great.. Best regards, -- - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - A. Murat Eren meren at uludag.org.tr http://cekirdek.uludag.org.tr/~meren/ 0x527D7293, 7BCD A5A1 8101 0F6D 84A4 BD11 FE46 2B92 527D 7293 - -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - -- Alan Cox sounds as if he hasn't followed the development of programming languages and compilers for the last 10 years (exa). - -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kay.schluehr at gmx.net Sun Jun 5 10:36:43 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 5 Jun 2005 07:36:43 -0700 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: <1117982203.857569.101730@z14g2000cwz.googlegroups.com> Mac wrote: > Is there a way to mimic the behaviour of C/C++'s preprocessor for > macros? The problem: a lot of code like this: > > def foo(): > # .... do some stuff > if debug: > emit_dbg_obj(DbgObjFoo(a,b,c)) > > # .... do more stuff > if debug: > emit_dbg_obj(DbgObjBar(d,e)) > > # ... and so on ... > > Notes: > > * the two-lines of debug conditional tend to really break up the flow > of the surrounding code > > * in C you could wrap them with a macro so you could do > DEBUG_EMIT(DbgObjFoo(a,b,c)), etc, with the macro only instantiating > the object and processing it if the debug flag was set. The one-liner > is MUCH less disruptive visually when reading code Make emit_dbg_obj() a class to create one-liners: class Emit_dbg_obj: debug = True def __init__(self, algo): self.algo = algo def call_if_debug(self): if self.debug: return self.algo def foo2(): # .... do some stuff Emit_dbg_obj(DbgObjFoo(a,b,c)).call_if_debug() # .... do more stuff Emit_dbg_obj(DbgObjFoo(c,d)).call_if_debug() Ciao, Kay From sklass at pointcircle.com Fri Jun 17 13:10:52 2005 From: sklass at pointcircle.com (rh0dium) Date: 17 Jun 2005 10:10:52 -0700 Subject: pysqlite - Checking the existance of a table Message-ID: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> Hi all, I am starting to play with pysqlite, and would like to know if there is a function to determine if a table exists or not. Thanks From kasimov at i.com.ua Thu Jun 9 12:02:56 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Thu, 09 Jun 2005 19:02:56 +0300 Subject: different time tuple format In-Reply-To: <1118258175.128686.247400@g14g2000cwa.googlegroups.com> References: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> <1118239337.961657.242660@g49g2000cwa.googlegroups.com> <42A707AC.9000405@i.com.ua> <1118258175.128686.247400@g14g2000cwa.googlegroups.com> Message-ID: <42A86830.9070004@i.com.ua> maybe you are right, i've searched in google groups - such a question was posted to comp.lang.python many times and i has not found (yet) the answer on "how to tune up the output of time.strptime()?" wittempj at hotmail.com wrote: > It is probably the best to calculate back to UTC. > > Assume "2005-06-07 15:07:12" the local time, then convert it as > follows to UTC. Use the UTC time to store/manipulate/whatever you want > to do. > > import time > t = time.mktime(time.strptime("2005-06-07 15:07:12", "%Y-%m-%d > %H:%M:%S")) > > print time.ctime(t) > > offset = time.timezone > if time.daylight: > offset = time.altzone > t += offset > print time.ctime(t) > -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From bdesth.quelquechose at free.quelquepart.fr Thu Jun 30 18:39:01 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 01 Jul 2005 00:39:01 +0200 Subject: Lost in a sea of documentation...can you point me in the right direction? In-Reply-To: <1120167496.973373.163400@f14g2000cwb.googlegroups.com> References: <1120167496.973373.163400@f14g2000cwb.googlegroups.com> Message-ID: <42c46e43$0$31194$636a15ce@news.free.fr> MooMaster a ?crit : (snip) > I'd like to write a program that I can pass a path to > (say: My Pictures) and at a timer interval will pick a picture from it > and set my wallpaper to that" So I started reading about os, threads, > and the path for the special folders What's a "special folder" ??? > in the archives and in the Python > docs and I'm kind of lost because there aren't many concrete examples > in the documentation. Can anyone point me in the right direction as to > where I might find info that can help me write this? There are 2 problems to solve: 1/ change the 'wallpaper' 2/ run as a background task (a 'service' on Win32, a 'daemon' on unix-likes) The 2nd one is already solved by your os (use Windows' task scheduler or *n*x's cron). So the main thing you have to do is find out how to 'change the wallpaper' on *your* system. For this, you first have to search in your system's API. From erik.myllymaki at aviawest.com Thu Jun 23 21:16:49 2005 From: erik.myllymaki at aviawest.com (Erik Myllymaki) Date: Fri, 24 Jun 2005 01:16:49 GMT Subject: trouble with win32serviceutil Message-ID: <5aJue.1786098$6l.413556@pd7tw2no> I am trying to start and stop a service with python. This used to work on an NT box but not on this 2003 server machine. (note- using "net stop myService" and net start myService" from the command line works just fine). The event viewer does tell me that a "Start command was sent to myService" but the service never starts. ------------------------------------------------------------------------- import win32serviceutil def service_control(service,action,machine='192.168.1.9'): if action == 'stop': try: win32serviceutil.StopService(service, machine) return('%s stopped successfully' % service) except: return ("Error stopping %s" % (service)) elif action == 'start': try: win32serviceutil.StartService(service, machine) return('%s started successfully' % service) except: return ("Error starting %s" % (service)) elif action == 'restart': try: win32serviceutil.RestartService(service, machine) return('%s restarted successfully' % service) except: return ("Error restarting %s" % (service)) elif action == 'status': if win32serviceutil.QueryServiceStatus(service, machine)[1] == 4: return("%s is running normally" % service) else: return("%s is *not* running" % service) if __name__ == '__main__': machine = '192.168.1.9' service = 'myService' action = 'start' print service_control(service,action,machine) From chad.hughes at pnl.gov Wed Jun 15 19:50:45 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Wed, 15 Jun 2005 16:50:45 -0700 Subject: Finding Word and switch focus to it Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6184@pnlmse27.pnl.gov> The first part is easy. I will have to think about the second part. To find an opened copy of Word and switch focus to it do the following: from win32com.client import Dispatch word = Dispatch('Word.Application') wdWindowStateNormal = 0 if len(word.Documents): word.Activate() if word.WindowState != wdWindowStateNormal: word.WindowState = wdWindowStateNormal -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of John Henry Sent: Wednesday, June 15, 2005 3:21 PM To: python-list at python.org Subject: Finding Word and switch focus to it Does anybody know how to find an opened copy of Word and switch focus to it, wait until Word is closed, before continuing my Python script? I tried to search for the answer from Google and nothing stands out. Running under Windows XP. Thanks, -- John -- http://mail.python.org/mailman/listinfo/python-list From richardjones at optushome.com.au Sat Jun 11 21:53:04 2005 From: richardjones at optushome.com.au (richard) Date: Sun, 12 Jun 2005 11:53:04 +1000 Subject: SMTP Test Rig ( SMTPRIG.PY v1.0 ) References: Message-ID: <42ab9580$0$11691$afc38c87@news.optusnet.com.au> Tim Williams wrote: > After a few posts recently, I have put together an SMTP test rig that > will > receive emails and either store them to a file, write them to a console, > or both. > > Does anyone have any suggestions on where I can get it hosted as a > utility for general public use? http://www.python.org/pypi Richard From __peter__ at web.de Thu Jun 30 03:07:04 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Jun 2005 09:07:04 +0200 Subject: aligning text with space-normalized text References: Message-ID: Steven Bethard wrote: > I have a string with a bunch of whitespace in it, and a series of chunks > of that string whose indices I need to find.??However,?the?chunks?have > been whitespace-normalized, so that multiple spaces and newlines have > been converted to single spaces as if by ' '.join(chunk.split()).??Some If you are willing to get your hands dirty with regexps: import re _reLump = re.compile(r"\S+") def indices(text, chunks): lumps = _reLump.finditer(text) for chunk in chunks: lump = [lumps.next() for _ in chunk.split()] yield lump[0].start(), lump[-1].end() def main(): text = """\ aaa bb ccc dd eee. fff gggg hh i. jjj kk. """ chunks = ['aaa bb', 'ccc dd eee.', 'fff gggg hh i.', 'jjj', 'kk.'] assert list(indices(text, chunks)) == [(3, 10), (11, 22), (24, 40), (44, 47), (48, 51)] if __name__ == "__main__": main() Not tested beyond what you see. Peter From gene.tani at gmail.com Sun Jun 19 05:07:46 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jun 2005 02:07:46 -0700 Subject: Help implementing an idea In-Reply-To: References: Message-ID: <1119172066.895213.226210@g44g2000cwa.googlegroups.com> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/299271 or the nice recipe, page 403 of cookbook2, that i can't find in ASPN From ruach at chpc.utah.edu Thu Jun 23 15:26:46 2005 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Thu, 23 Jun 2005 13:26:46 -0600 Subject: formatted xml output from ElementTree inconsistency Message-ID: Greetings, perhaps someone can explain this. I get to different styles of formatting for xmla and xmlb when I do the following: from elementtree import ElementTree as et xmla = et.ElementTree('some_file.xml') xmlb = et.Element('parent') et.SubElement(xmlb, 'child1') et.SubElement(xmlb, 'child2') root = et.Element('root') root.append(xmla.getroot()) root.append(xmlb) print et.tostring(root) The output I get shows xmla as nicely formatted text, with elements on different lines and everything all tabbed and pretty. Inverly, xmlb is one long string on one line. Is that because the some_file.xml is already nicely formatted? I thought that the formatting was ignored when creating new elements. Is their a function to 'pretty print' an element? I looked in api ref and didn't see anything that would do it. It would be nice if their was a way to create 'standard' formatted output for all elements regardless of how they were created. Comments and suggestions are greatly appreciated. regards -Matthew From harold.fellermann at upf.edu Wed Jun 15 11:16:21 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 15 Jun 2005 17:16:21 +0200 Subject: extending Python base class in C In-Reply-To: <42af225e$1@nntp0.pdx.net> References: <42af225e$1@nntp0.pdx.net> Message-ID: <122bb88ff3a4217782ade5d801a6c648@upf.edu> Yahoooo! Finally, I got the thing to work. Here is how I did it. /* import the module that holds the base class */ PyObject *base_module = PyImport_ImportModule("module_name"); if (!base_module) return; /* get a pointer to the base class */ PyObject *base_class = PyMapping_GetItemString( PyModule_GetDict(base_module,"BaseClass") ); if (!base_class) return; /* assign it as base class */ cclassType.tp_bases = Py_BuildValue("(O)",BaseClass); I am doing all this before the call to PyType_Ready() -- as Scoot Daniels suggested. Using the python API's SetAttrString() did not work (I suppose for the same reason, why assigning cls.__bases__ does not work in pure python either). I also checked cclassType.tp_base = (PyTypeObject *) base_class; which also works and I am not aware of the difference of these two slots. Anyway, for my simple purposes it works just fine. - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." From DPhelps at linuxmail.org Mon Jun 13 14:48:24 2005 From: DPhelps at linuxmail.org (DPhelps at linuxmail.org) Date: 13 Jun 2005 11:48:24 -0700 Subject: Python/C API -- trouble creating objects Message-ID: <1118688504.602806.41210@g47g2000cwa.googlegroups.com> I have a multithreaded Python shell server (base on the sample code 'pysvr.py') that uses a C-based extension class. The trouble I'm having is that I cannot figure out a way to create a Python object from the C code. I'll detail the methods I've looked at and the troubles I'm having: Method 1) Ideally, I could get PyRun_String to work, however I cannot figure out how to properly get the locals and globals structures. In the examples I've seen, people are either creating brand new globals dictionaries and/or reusing globals as locals. The problem I have is that I potentially have multiple threads with different globals and locals (see pysvr.py code in Python 2.4.1 distribution). I need to reference the locals and globals for the interpreter shell for the current thread. PyRun_SimpleString works great, but I need to get a PyObject * back, so I need to use PyRun_String -- so another way to phrase my problem is: How do I get the locals and globals used in PyRun_SimpleString for use with PyRun_String (given that I'm in a multi-threaded, multi-interpreter environment similar to the one found using pysvr.py). Method 2) PyObject_New() seems like a good possibility -- except that I have no idea where to get a PyTypeObject* from! This is for a Python-implemented class, e.g.: Queue. Method 3) Dig inside the interpreter structs (PyFrameObject, PyThreadState, etc) and dig the locals out that way. Problem is, that's not supported, so I'd rather not do it. There has to be a simple way to do this simple task!! -Doug From sdhyok at gmail.com Tue Jun 7 14:27:27 2005 From: sdhyok at gmail.com (sdhyok) Date: 7 Jun 2005 11:27:27 -0700 Subject: How to call python functions from matlab? Message-ID: <1118168847.762297.306890@o13g2000cwo.googlegroups.com> PyMat enables to call matlab functions from python. But, what I want is to call python functions from matlab. Is there any library for it? Thanks. Daehyok Shin From tim.golden at viacom-outdoor.co.uk Wed Jun 29 07:35:56 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 12:35:56 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB94B@vogbs009.gb.vo.local> [Tim Golden] | [Greg Miller] | | | I didn't have this problem on the | | first release | | as we weren't interested in displaying the file version of the .dll. | | With this improved version of the product the request has | come down to | | have all software package versions displayed, so that is | why I am now | | attempting to extract the file version of the dll. Thanks again for | | everyone's assistance................. | | There was some talk a while back about including the win32 | calls to get file versions into the pywin32 packages. Might | be worth checking to see if it's happened. Or using ctypes, | of course. If WMI is this much trouble, and only for this one | piece of info, definitely worth looking elsewhere. | | TJG In fact, check out the win32api.GetFileVersionInfo function. import os, sys import win32api win32api.GetFileVersionInfo (os.path.join (sys.exec_prefix, "python24.dll"), "\\") You'll have to look in the demos directory for examples and in the docs, but maybe this will save you a bit of grief. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From rutt.4 at osu.edu Mon Jun 20 21:33:06 2005 From: rutt.4 at osu.edu (Benjamin Rutt) Date: Tue, 21 Jun 2005 01:33:06 GMT Subject: getting list of all available modules Message-ID: <87d5qgsddt.fsf@penguin.brutt.org> I note that the help() function of interactive python can determine all available modules: [rutt at akron ~]$ python Python 2.4 (#1, Mar 31 2005, 15:26:02) [GCC 3.2.3 (Debian)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help() [...] help> modules Please wait a moment while I gather a list of all available modules... BaseHTTPServer bisect linuxaudiodev shelve Bastion bsddb (package) locale shlex BicycleRepairMan_Idle cPickle logging (package) shutil CDROM cStringIO macpath signal CGIHTTPServer calendar macurl2path site Canvas cgi mailbox smtpd ConfigParser cgitb mailcap smtplib [...] I want to do the same (get all such modules in a python list); how can I do so? Or where is the code for the REPL for help() itself so I can find out myself? This is to build a code introspection tool BTW. Thanks, -- Benjamin Rutt From johan at pulp.se Sat Jun 25 17:35:24 2005 From: johan at pulp.se (Johan Lindberg) Date: 25 Jun 2005 14:35:24 -0700 Subject: Office COM automatisation - calling python from VBA In-Reply-To: References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <1119735324.335187.94020@g47g2000cwa.googlegroups.com> Hi. > > If you are new to Python and want to use it with COM, definitely get > > yourself a copy of _Python Programming on Win32_ by Mark Hammond and > > Andy Robinson. > > ...or at least read the chapter available online: > http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Also, check out the following tutorials: http://www.reportlab.com/ftp/talks/PythonWindowsTutorial.doc http://starship.python.net/crew/pirx/spam7/COMtut.PPT ...and if you're visiting EuroPython make sure to show up for Guy Dalbertos tutorial on Python+ Excel. If you're not, download his presentation and example code from: http://www.python-in-business.org/ep2005/talk.chtml?talk=2626&track=690 HTH Johan Lindberg johan at pulp.se From ahmadhosseinzadeh at yahoo.ca Tue Jun 7 10:43:30 2005 From: ahmadhosseinzadeh at yahoo.ca (Ahmad Hosseinzadeh) Date: Tue, 7 Jun 2005 10:43:30 -0400 (EDT) Subject: redirecting messgaef from sys.stdout Message-ID: <20050607144330.13561.qmail@web52203.mail.yahoo.com> Hello, I?m trying to run an external program in my application. Both are coded in python. I need to write an independent module that is used in the main application. Its responsibility is to run the external program and redirect its stdout and stderr to the main application. The application?s stdout and stderr are set to an object and they are not command prompt anymore. The output is selected by a flag; if true the stdout and stderr will be redirected to application?s stdout and stderr. If false, the stdout and stderr will be redirected o command prompt. I don?t know how to redirect the output. Can anyone help please? Regards, Ahmad Hosseinzadeh __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From paddy3118 at netscape.net Wed Jun 29 23:51:27 2005 From: paddy3118 at netscape.net (Paddy) Date: 29 Jun 2005 20:51:27 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <1120103487.450255.18800@g44g2000cwa.googlegroups.com> Joseph Garvin wrote: 'm curious -- what is everyone's favorite trick from a non-python language? And -- why isn't it in Python? I use constraints programming at work, Check out "System Verilog" or OZ/Mozart. It would be great if this style of programming could be added to Python. It is a declarative programming style (http://en.wikipedia.org/wiki/Declarative_programming), in which you can state what discrete values constrained values can take , say in a list. Give a set of functions that must be true for the variables then sit back and generate one or many sets of variable values that fit the constraints. The OZ homepage has an example for solving the eight queens problem: http://www.mozart-oz.org/documentation/fdt/node25.html#section.scripts.queens My use would be for testing. In the electronic design automation fields, there are several proprietary languages with this feature, here is an example written in Cadence's Specman 'e' language: http://www.asic-world.com/specman/specman_one_day2.html Cheers, Paddy. From rrr at ronadam.com Mon Jun 13 22:57:59 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 14 Jun 2005 02:57:59 GMT Subject: "also" to balance "else" ? In-Reply-To: <1118709113.769757.160250@g47g2000cwa.googlegroups.com> References: <1118709113.769757.160250@g47g2000cwa.googlegroups.com> Message-ID: Eloff wrote: > My first reaction was that this is terrible, else clauses on loops are > confusing enough. But if I think about it more, I'm warming up to the > idea. Also/Else for loops is clear, symmetrical, and would be useful. > > Reversing the meanign of else will break code, but it's not used that > frequently, and it was a confusing thing to begin with, nothing wrong > in breaking something (slowly!) if it was 'broken' to begin with. > > Alifs look evil, I couldn't deduce the control flow very easily, but > then they are a new idea. I'll keep an open mind on that one. Yes, it's probably because it's new. Alifs would be used where you want to test for multiple possible values, and need to respond differently depending on the values. They probably wouldn't be used as often as elifs. alifs is a way to string if's together as a group. The following would be equivalent to if-alif-also-else. didif = False if val == condition1: didif = True BLOCK1 if val == condition2: didif = True BLOCK2 if val == condition3: didif = True if didif: BLOCK3 else: BLOCK4 The if-alif-also-else version doesn't need the extra name to mark if any of the conditions were true. if val == condition1: BLOCK1 alif val == condition2: BLOCK2 alif val == condition3: BLOCK3 also: BLOCK4 else: BLOCK5 But I think we will need to find some real use case's to make it convincing. > I think the best thing would be to compare the also/else syntax to what > identical functionality looks like in python now [hint to someone with > more time than me right now ;)]. I'd vote for whichever is the more > concise and readable of the two. > > -Dan > In cases of if-also, the equivalent code needs an extra local variable and an additional if statement. iftest = False if : iftest = True BLOCK1 elif : iftest = True BLOCK2 if iftest: BLOCK3 This is the pattern that caused me to think of having an also. I was parsing and formatting doc strings at the time, and also would allow it to become. if : BLOCK1 elif : BLOCK2 also: BLOCK3 Which is much easier to read. Ron From exarkun at divmod.com Wed Jun 29 14:15:09 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 29 Jun 2005 14:15:09 -0400 Subject: importing packages from a zip file In-Reply-To: Message-ID: <20050629181509.26278.505427434.divmod.quotient.2672@ohm> On Wed, 29 Jun 2005 18:49:10 +0000, Peter Tillotson wrote: >cheers Scott > >should have been >from myZip.zip import base.branch1.myModule.py > >and no it didn't work, anyone know a reason why this syntax is not >preferred ?? > >sorry posted the soln again, it works but feels nasty Including paths in source files is a disaster. As soon as you do it, you need to account for alternate installation schemes by rewriting portions of your source files. Separating path names from module names lets you avoid most of this mess. Jp From jivadent at gmail.com Mon Jun 27 10:06:07 2005 From: jivadent at gmail.com (Gabriel Jiva) Date: 27 Jun 2005 07:06:07 -0700 Subject: pulling multiple instances of a module into memory Message-ID: <1119881167.255259.251880@f14g2000cwb.googlegroups.com> I have a Python app, spam.py, that uses a C shared library, eggs.so. This shared library is an interface that makes connections to another system (Ham), and among other things uses callback functions. Therefore, if I want to make multiple connections to Ham, I need eggs.so to be instantiated in memory multiple times so that everything works fine. Right now, in spam.py, let's say I want to make two connections to the Ham system. I call eggs.start('Connection1') eggs.start('Connection2') On the second one, I get a 'duplicate call' error. Because Python is optimized to only load a module into memory once, I can never make more than one connection from the same Python script. Any ideas to work around this would be great. Gabriel From aahz at pythoncraft.com Wed Jun 29 11:37:48 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jun 2005 08:37:48 -0700 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1120023753.231890.182890@g43g2000cwa.googlegroups.com> Message-ID: In article <1120023753.231890.182890 at g43g2000cwa.googlegroups.com>, BORT wrote: > >Gentle folk of comp.lang.python, I heartily thank you all for your >input. I think I'm taking the boys through the door marked "Logo." We >may be back this way, though. We will likely need MORE in the nebulous >future. I am impressed with the outpouring of support here! > >Thanks to all! You're welcome. I want to leave you with one parting comment: I first started programming when I was nine years old, in the mid-1970s. We used TTYs with a timeshared HP1000 and BASIC. Given modern computers and editors I think that any programming language that isn't excessively baroque will do fine for young people. They can always unlearn bad habits later. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From nothingcanfulfill at gmail.com Fri Jun 24 20:54:39 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 24 Jun 2005 17:54:39 -0700 Subject: Newbie question: how to keep a socket listening? In-Reply-To: <11bok3btkedg151@corp.supernews.com> References: <1119637288.536579.249340@z14g2000cwz.googlegroups.com> <11bok3btkedg151@corp.supernews.com> Message-ID: <1119660879.852664.167100@f14g2000cwb.googlegroups.com> Heh, like I said. I was not at all sure. :P Nevertheless, could this be the problem? =\ From gilles.lenfant at nospam.com Tue Jun 14 09:24:49 2005 From: gilles.lenfant at nospam.com (Gilles Lenfant) Date: Tue, 14 Jun 2005 15:24:49 +0200 Subject: [OT ?] (Pythonic) detection word protected files In-Reply-To: References: Message-ID: <42AEDAA1.6020205@nospam.com> Tim Golden a ?crit : > [Gilles Lenfant] > | I'm building an utility that makes a catalog of M$ word files > | in a giant > | directory tree. The password protected files must be marked, and I > | didn't find how to guess which files are password protected and which > | ones are not. > | > | I can't use the COM interface for this because the utility > | must run on a > | Linux Samba server. > | > | I didn't find anything satisfying in M$ related sites (like msdn) or > | forums or google. > > This page looks like it might be useful: > > http://wvware.sourceforge.net/wvInfo.html Wow ! What a great starter ! I got to much information now :o) Many thanks. -- Gilles From thomas.weholt at gmail.com Wed Jun 1 18:22:44 2005 From: thomas.weholt at gmail.com (Thomas W) Date: 1 Jun 2005 15:22:44 -0700 Subject: NSLU2 and python - a love story ? In-Reply-To: References: <1117629593.000908.294450@g43g2000cwa.googlegroups.com> Message-ID: <1117664564.859147.185660@g49g2000cwa.googlegroups.com> Well, AFAIK people are running web-sites using apache, php and mysql on it and with ok performance. I'm not saying this would replace a real server, but for normal home-use with not too much traffic it seems to do the job. It's a fact that Linksys uses a somewhat modified version of linux on the NSLU2, maybe they don't advertise it on their web-page, but who cares? They got similar products based on or running linux which also have replacement-firmware. The point is that alot of people have modified their NSLU2, which by the way don't remove any of the functionality of the original product as I understand it, and made it possible to do cool things with it; run a subversion server for their projects etc. and by adding up to two large ( 300GB + ) drives you have enought storage for most things. And FYI the root filesystem can be stored on one of the USB-devices. It doesn't have to be stored on the 8MB flash. My interest in it is due to the fact that my current two servers makes alot of noise, are big and uses alot of eletricity. If I could replace them with a NLSU2 running linux and python I could use all my allready developed software on a system costing 1/10th of my current server, with almost no noise and consume very little eletricity. I just think that's very interesting. The first project I have in mind is a web-interface to my digital image collection, in which I can organise the pictures in categories, add metadata, generate galleries and slideshows etc. From what I can see the NSLU2 would have little problems serving this specific purpose, in addition to serving the images thru samba as well so I can access them with my laptop, my KISS DP-558 PVR and my XBox. The "distro"/replacement-firmware for the NSLU2 allready have most of the modules I need ( CherryPy, pySQLite/SQLite ). The only thing missing is, as I said earlier, PIL. I think anything running linux and especially Python, is awsome, I'll admit that. Perhaps I'm just blinded by all that and cannot see the fact that 266Mhz isn't enough "juice". But I really do think the NSLU2 is suitable for running a project like I described above, based on the stuff I've read about other projects using the box. If I'm wrong a heads up would be great so I can save my money. Save money to buy a mini mac/mini intel/barebone, because that's the alternative for me right now, and really silent barebone systems tend to cost alot more, generate heat and use electricity like a normal computer ( and pack alot more punch of course ). I don't own a NSLU2 yet, but intend to buy one soon. If the python project is successful I'll post some info here. From diabolik at uku.co.uk Thu Jun 30 13:58:58 2005 From: diabolik at uku.co.uk (JudgeDread (nospam)) Date: Thu, 30 Jun 2005 17:58:58 +0000 (UTC) Subject: Scket connection to server Message-ID: hello python gurus I would like to establish a socket connection to a server running a service on port 29999. the host address is 10.214.109.50. how do i do this using python? many thanks From roy at panix.com Mon Jun 13 07:53:03 2005 From: roy at panix.com (Roy Smith) Date: Mon, 13 Jun 2005 07:53:03 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: Andrea Griffini wrote: > There's no way you will remember what is O(n), > what O(1) and what is O(log(n)) among containers > unless you roughly understand how it works. People were thinking about algorithmic complexity before there was random access memory. Back in the unit record equipment (i.e. punch card) days, people were working out the best ways to sort and merge decks of punch cards with the fewest trips through the sorting machine. Likewise for data stored on magnetic tape. I can certainly demonstrate algorithmic complexity without ever going deeper than the level of abstraction exposed by Python. You can learn enough Python in an afternoon to write a bubble sort and start learning about O(2) behavior without even knowing what a memory address is. Somebody mentioned that string addition in Python leads to O(2) behavior. Yes it does, but that's more an artifact of how Guido decided he wanted strings to work than anything fundamental about memory allocation. He could have taken a different design path and made Python strings more like STL vectors, in which case string addition would be O(n). Teaching that "string addition is O(2)" is not only needlessly confusing for somebody just starting out, it's also wrong (or at best, a specific case valid for one particular implementation). And, BTW, I started out programming on a big HP desktop calculator (http://www.hpmuseum.org/hp9810.htm). Next came BASIC. Then Fortan and assembler on a pdp-10. Then C, a couple of years later. After that, I've lost track. Some of the languages that taught me the most were ones that got very far away from the hardware. NewtonScript was my first introduction to OOPL, and PostScript showed me that stack languages aren't just for calculators. Lisp, of course, expanded my mind in ways that only Lisp can (the same could be said for many things I tried back in those days). Even quirky HyperCard showed me a different way to think about programming. I think it's probably just as important for a CS major to play with those mind-altering languages as it is to worry about bytes and pointers and memory locations. But you can't start everywhere, and if you've got to start someplace, Python let's you concentrate on the real universal fundamentals of data structures, algorithms, and control flow without getting bogged down in details. From guyon.moree at gmail.com Thu Jun 9 03:58:17 2005 From: guyon.moree at gmail.com (=?iso-8859-1?B?R3V5b24gTW9y6WU=?=) Date: 9 Jun 2005 00:58:17 -0700 Subject: Python Challenge web site In-Reply-To: <98OdnUvjYdn8LjrfRVn-qg@comcast.com> References: <98OdnUvjYdn8LjrfRVn-qg@comcast.com> Message-ID: <1118303897.416785.21750@o13g2000cwo.googlegroups.com> Wow, no I haven't reached 30 yet, I'm almost at number 16. I did write about my solutions uptil puzzle 10 on my blog: http://gumuz.looze.net/wordpress/index.php/archives/2005/05/09/python-challenge-solutions-part-1/ http://gumuz.looze.net/wordpress/index.php/archives/2005/05/20/python-challenge-solutions-part-2/ please share your solutions. cheers, Guyon Mor?e http://gumuz.looze.net/ From sjmachin at lexicon.net Thu Jun 23 20:29:37 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Jun 2005 10:29:37 +1000 Subject: trouble subclassing str In-Reply-To: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> Message-ID: <42BB53F1.30504@lexicon.net> Brent wrote: > I'd like to subclass the built-in str type. For example: You'd like to build this weird-looking semi-mutable object as a perceived solution to what problem? Perhaps an alternative is a class of objects which have a "key" (your current string value) and some data attributes? Maybe simply a dict ... adict["some text"] = 100? > class MyString(str): > > def __init__(self, txt, data): > super(MyString,self).__init__(txt) > self.data = data > > if __name__ == '__main__': > > s1 = MyString("some text", 100) > > > but I get the error: > > Traceback (most recent call last): > File "MyString.py", line 27, in ? > s1 = MyString("some text", 12) > TypeError: str() takes at most 1 argument (2 given) > > I am using Python 2.3 on OS X. Ideas? > __init__ is not what you want. If you had done some basic debugging before posting (like putting a print statement in your __init__), you would have found out that it is not even being called. Suggestions: 1. Read the manual section on __new__ 2. Read & run the following: class MyString(str): def __new__(cls, txt, data): print "MyString.__new__:" print "cls is", repr(cls) theboss = super(MyString, cls) print "theboss:", repr(theboss) new_instance = theboss.__new__(cls, txt) print "new_instance:", repr(new_instance) new_instance.data = data return new_instance if __name__ == '__main__': s1 = MyString("some text", 100) print "s1:", type(s1), repr(s1) print "s1.data:", s1.data 3. Note, *if* you provide an __init__ method, it will be called [seemingly redundantly???] after __new__ has returned. HTH, John From peter at engcorp.com Tue Jun 14 07:53:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 07:53:35 -0400 Subject: ANN: pyparsing-1.3.1 released In-Reply-To: References: <1118675563.206703.263700@g14g2000cwa.googlegroups.com> Message-ID: Christopher Subich wrote: > Is the pyparsing > tokenizer flexible enough to let me do this sort of thing easily? I can't say that for sure, but I can say that it is certainly easy enough to try it out (and well enough documented) that downloading it, installing it, and doing a quick proof-of-concept experiment would probably take less time than waiting for a reply to that question. ;-) -Peter From kent37 at tds.net Sun Jun 5 22:08:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Jun 2005 22:08:43 -0400 Subject: Iterate through a list calling functions In-Reply-To: References: Message-ID: <42a3afe6$1_1@newspeer2.tds.net> David Pratt wrote: > Hi Kent. Thank you for your reply. I gave this a go but get the > following traceback: > ... > result = validator(name, value) > TypeError: 'str' object is not callable > > Have put validators in list and iterate over it as in following: > > validator_list = > [isContainedIn,isDate,isDecimal,isEmail,isEmpty,isInteger... > more validators....] > results={} > for validator in validators_list: > result = validator(name, value) > if type (result) in StringTypes: > # do some stuff... > return results Are you sure you don't have quoted strings in your validator list? That is what the error message indicates. Can you post a small complete example of the code that fails? or put print repr(validator) before the line that calls validator so you can see exactly what you are trying to call. Kent From nothingcanfulfill at gmail.com Thu Jun 30 22:16:23 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 30 Jun 2005 19:16:23 -0700 Subject: Threading Question Message-ID: <1120184183.474557.22610@g49g2000cwa.googlegroups.com> I've used python for a while now, and am startting to dig into threads and sockets (using asyncore/asynchat). Through all this, I've been using the -v option on python to generate verbose output and try to pinpoint any potential problems...however, one warning is eluding me as to it's cause/resolution. > > > > > > PyThreadState_Clear: warning: thread still has a frame This warning seems to make little sense to me (even though it probably shouldn't). Can anyone guide me as to what it is and how I could try and make a resolution. Many thanks in adv. -Wes P.S.: If needed, I will gladly toss a shortened version of the code up for all to see. From spam.csubich+block at block.subich.spam.com Mon Jun 27 23:09:36 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Mon, 27 Jun 2005 23:09:36 -0400 Subject: Text() tags and delete() In-Reply-To: References: Message-ID: Bob Greschke wrote: > Does Text.delete(0.0, END) delete all of the tags too? Everything says it > does not delete marks, but nothing about tags. Note to everyone else: this is a TKinter question. Tags are attached to text ranges, in the Text widget. If you delete all of the text in the widget, all of the text ranges will go poof, so therefore all of the tag attachments will likewise go poof. This will not delete any tags that have been defined for the widget, though, although why you'd want to do that is an open question. From hancock at anansispaceworks.com Mon Jun 27 00:14:48 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 26 Jun 2005 23:14:48 -0500 Subject: what is your opinion of zope? In-Reply-To: References: Message-ID: <200506262314.48674.hancock@anansispaceworks.com> On Sunday 26 June 2005 06:34 pm, Avery Warren wrote: > I am investigating converting a wiki site to plone. I am having > a lot of difficulty finding good documentation programmatically > accessing the ZODB API. Well, it's really pretty straightforward to use, but you should be able to find sufficient documentation on the zope.org site. Try searching for "zodb" and "standalone zodb". However, I'm not sure why you want this information. If you are trying to import data into Zope, you are more likely going to be using Zope, not accessing ZODB directly. > A lot of the user feedback is centered on how difficult it is to > get good documentation on developing using these technologies. My > question to comp.lang.python is "what is your opinion of zope?" Well, I use it an awful lot. I manage all of my websites using (plain) Zope. The largest Python projects I've been working on are Zope applications. It seems to be a very useable framework. I've never tried Plone, so I won't respond to that part. It's biggest problem is that it is a *framework* (as opposed to a "toolkit"), so it requires you to "think in Zope" when developing for it. This is a criticism of Zope 2.x. This makes for a very steep learning curve. There's also a lot of the framework which doesn't work very well (e.g. Sessions? IIRC), and is largely unused. This creates red-herrings which are also a problem for new users. There are two competing template languages (DTML and ZPT), both of which were invented for Zope. OTOH, there are standalone ZPT implementations (not so for DTML), and ZPT seems to be taking the prefered new language. It appears from what little I've played with it that Zope 3 will go a long way towards rectifying this problem by moving to a "component" architecture. Zope 3 will still be a framework, but you will have much more control over which parts you use and it will be easier to use 3rd party (and stdlib) modules with it. That is to say, Zope 3 will have a lighter framework with more of the 2.x framework moved into "components" --- making it more like a toolkit. I think that's a terrific idea. I still have not really started testing Zope 3 in ernest, though, so I can't really report my experience with it. I have used the "interface" and "schema" modules from it, and I've been very happy with using those to establish interfaces in my own software. (This makes it much easier to delineate "plugins" or places in your code where 3rd party development can be done, without requiring the developer to understand your entire application in order to be able to contribute --- if you are hoping for contributions from user-developers on a free-software application, then this has to be a good idea). Without more specifics about what you are looking for, it would be hard to reply further than this. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From exarkun at divmod.com Wed Jun 15 12:04:35 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 15 Jun 2005 12:04:35 -0400 Subject: non OO behaviour of file In-Reply-To: <42B04B78.8000601@chamonix.reportlab.co.uk> Message-ID: <20050615160435.5047.559850221.divmod.quotient.3338@ohm> On Wed, 15 Jun 2005 16:38:32 +0100, Robin Becker wrote: >Michael Hoffman wrote: >..... >> >> Well, you could use python -u: >> > >unfortunately this is in a detached process and I am just reopening stdout >as an ordinary file so another process can do tail -F on it. I imagine ther >ought to be an os dependant way to set the file as unbuffered, but can't >remember/find out what it ought to be. > open(name, 'w', 0) For even more excitment, there's os.open() with the O_DIRECT and O_SYNC flags. You shouldn't need to go to this extreme, though. FWIW, I think the behavior of Python wrt file subclasses that override write() is silly, too. Jp From s_david_rose at hotmail.com Tue Jun 21 10:23:43 2005 From: s_david_rose at hotmail.com (GMane Python) Date: Tue, 21 Jun 2005 10:23:43 -0400 Subject: Python choice of database References: Message-ID: For my database, I have a table of user information with a unique identifier, and then I save to the filesystem my bitmap files, placing the unique identifier, date and time information into the filename. Why stick a photo into a database? For instance: User Table: uniqueID: 0001 lNane: Rose fName: Dave Then save the bitmap with filename: 0001_13:00:00_06-21-2005.bmp To make things faster, I also have a table of filenames saved, so I can know exactly which files I want to read in. -Dave From steve at REMOVETHIScyber.com.au Sat Jun 25 13:27:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 03:27:59 +1000 Subject: what list comprehension can't References: <1119638714.090433.130520@z14g2000cwz.googlegroups.com> <20050624210415.48f5dace.no.spam@box> Message-ID: On Fri, 24 Jun 2005 21:04:15 +0200, Christophe Delord wrote: > Hello, > > On 24 Jun 2005 11:45:14 -0700, ajikoe at gmail.com wrote: > >> Hello, >> >> Can we impose if then else into list comprehension ? >> Like we do in lambda-map form: >> >> This code change None into 0 >> L = [None, 12] >> R = map(lambda x: (x==None and [0] or x)[0], L) # [0,12] >> > > Do you mean: > [(x==None and [0] or [x])[0] for x in L] > or [{None:0}.get(x,x) for x in L] > or [x or 0 for x in L] > > Well, the third solution doesn't exactly fit the specification but may > be easier to read. Or, more generally, [0 for x in L if x is None] which doesn't solve the asked-for question, but is a useful feature. -- Steven. From whimsica at aol.com Wed Jun 22 04:33:46 2005 From: whimsica at aol.com (whimsica) Date: 22 Jun 2005 01:33:46 -0700 Subject: C++ ActiveX python javascript communication trouble. Message-ID: <1119429226.294057.272480@g43g2000cwa.googlegroups.com> I'm investingating a c++ api, Panda3d.com, that has a python binding. I want to convert this api into an ACtiveX control so it will run on the web. When I do so I want to use Microsoft Script Control to call api routines from Javascript in the browser. Let's say I write up a game in python with my own functions. Then I embed it in a web page and I want to call my functions from javascript? How can I do it. Script control allows you to bind api functions to javascript, but not the functions in my python file. Adobe Atmoshere a 3D application that ran in a web page, had a javascript binding. You could write code in a javascript file, and it would be interpreted during start-up. After that, I could send function calls in the form of a string from the browser to atmosphere. How did this work? Is the api aware of the python functions and variables after it is loaded up? Confused, Dan From ville at spammers.com Wed Jun 8 08:50:17 2005 From: ville at spammers.com (Ville Vainio) Date: 08 Jun 2005 15:50:17 +0300 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) References: Message-ID: >>>>> "Fred" == Fred Pacquier writes: Fred> Same here : thanks for letting us get away with being Fred> lazy(er) ! :-) Ditto. As someone who's done a couple of p-url's, I can say it's quite a bit of work to find the interesting tidbits from the depths of 500-post threads where people can't be bothered to change the subject line... -- Ville Vainio http://tinyurl.com/2prnb From jatinder at textualanalytics.com Thu Jun 9 06:15:05 2005 From: jatinder at textualanalytics.com (Jatinder Singh) Date: Thu, 9 Jun 2005 05:15:05 -0500 Subject: Premature script error Message-ID: <1118312105.42a816a91d672@mailbox.textualanalytics.com> I am running a CGI Programme. which is throwing Premature script error for some inputs. I have checked and couldn't fig out the problem. Even error log is empty. Can anybody help me out of this or can I use try except to catch the Error and how? plz get back soon .Its urgent -- Regards, Jatinder Singh ? Everyone needs to be loved... especially when they do not deserve it.? From philippe at philippecmartin.com Thu Jun 23 20:02:39 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 24 Jun 2005 00:02:39 GMT Subject: Running Python interpreter in Emacs References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> Message-ID: Hi, this is what I have: (autoload 'python-mode "python-mode" "Python mode." t) (setq auto-mode-alist (append '(("\\.\\(py\\)$" . python-mode)) auto-mode-alist)) Plus, you can always spawn a shell then call your script (if the point is to have access to the output). Regards, Philippe Rex Eastbourne wrote: > Hi, > > I'm interested in running a Python interpreter in Emacs. I have Python > extensions for Emacs, and my python menu lists "C-c !" as the command > to run the interpreter. Yet when I run it I get the message "Spawning > Child Process: invalid argument." What do I need to do/download to fix > this? > > I read in a post in this group from a while back where someone had the > following lines in his .emacs file: > > (setq interpreter-mode-alist > (cons '("python" . python-mode) > interpreter-mode-alist)) > > Does that have something to do with it? Do I have to set my load-path > to my python interpreter? > > Thanks, > > Rex From cam.ac.uk at mh391.invalid Thu Jun 23 12:36:35 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 23 Jun 2005 17:36:35 +0100 Subject: Loop until condition is true In-Reply-To: <86u0jpytg7.fsf@guru.mired.org> References: <86u0jpytg7.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Making None a constant broke existing code (and I just saw old code > that assigned to None). Are True and False that much more common as > variable names than None? Yes. In fact, I count at least 4 different modules in the Python 2.4 standard library that assign to True or False, mainly as a compatibility measure for the days before they were built-ins. If you try assigning None, CPython will refuse to compile the module, even if the code where None is assigned is unreachable. If there was ever a good reason to assign to None, I don't know it. -- Michael Hoffman From news at andrewcdonagh.f2s.com Sun Jun 26 19:56:13 2005 From: news at andrewcdonagh.f2s.com (Andrew McDonagh) Date: Mon, 27 Jun 2005 00:56:13 +0100 Subject: Acceptance test spike example In-Reply-To: References: Message-ID: Steve Jorgensen wrote: > I'm posting this message for 2 reasons. > > First, I'm still pretty new and shakey to the whole Acceptance Testing thing, > and I'm hoping for some feedback on whether I'm on the right track. Second, > although all the Agile literature talks about the importance of doing > Acceptance Testing, there's very little in any of the books or out on the Web > that helps with how to do it. If I am on the right track, this will be one > more helpful item folks can find on a Google search. > > The code below is basically a spike I wrote in a few hours last night to prove > to myself and my team that it would be feasible to quickly create a simple, > useful Acceptance Testing harness for our learning project. > > First, I wrote an example test script I would hope to be able to execute... > > =============== > ?recipeListCount:0 > !new > ?name:"New Recipe" > name:"PB&J" > ?name:"PB&J" > !save > !close > ?recipeListCount:1 > !goToListItem 1 > !openListItem > ?name:"PB&J" > =============== > Snipped. Its best to aim the Acceptance Test at your Customers level of expertise, not at the developers. As a Customer is the person best placed to tell us What they want. Yes Our team people (Devs or testers) can help write the actual tests, but the Customer should still be able to read them. After all, the tests are Executable Requirements. There's two flavors of Customer oriented styles I've come across. The first uses a Domain Specific Language...eg using your values above.. --------------------------------- IsTotalNumberOfRecipes 0 ClickNewRecipeButton RecipeNameToUse "PB&J" SaveNewRecipe CloseDialog IsTotalNumberOfRecipes 1 IsThereOneRecipeCalled "PB&J" --------------------------------- All commands are the first full word. No need for special tokens to decide what the command is supposed to do, as each Command is the name of a class to use. You can use reflection to dynamically create the Command instances or the name can be used by a factory as an id. The Commands themselves know what they are supposed to do, not the Script parsing engine. The second approach is using FIT/Fitnesse - google these for exact description. They take information in Table form. This allows the customer to use any software to create the test scripts, so long as it can create tables: Word processors, Spread Sheets, etc. Andrew From peter at engcorp.com Wed Jun 22 22:51:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Jun 2005 22:51:08 -0400 Subject: Database recommendations for Windows app In-Reply-To: <42b9d01e$0$2588$da0feed9@news.zen.co.uk> References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <42b9d01e$0$2588$da0feed9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Thanks for the replies. I think I'm going to go with sqllite for now. Your list didn't mention a few things that might be critical. Referential integrity? Type checking? SQLite currently supports neither. Just make sure you check the list of supported features to see that it really does what you need. -Peter From rupole at hotmail.com Thu Jun 2 18:19:23 2005 From: rupole at hotmail.com (Roger Upole) Date: Thu, 2 Jun 2005 18:19:23 -0400 Subject: how to retrieve info about print jobs References: <3EAne.108100$xW2.6437935@phobos.telenet-ops.be> Message-ID: <429f86d1$1_1@spool9-west.superfeed.net> There are functions for managing printers and print jobs in the win32print module from the Pywin32 package. Roger "Guy Lateur" wrote in message news:3EAne.108100$xW2.6437935 at phobos.telenet-ops.be... > Hi all, > > We have several printers in our company network. I would like to know if it > is possible to check the current print jobs/queues for each of them. That > way, if a user wants to print something (big), I could give her a hint as to > which printer would get the job done first. We're using win2k and xp, btw. > > Any ideas? I'm pretty new to python, I'm afraid.. > > TIA, > g > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From oren.tirosh at gmail.com Sat Jun 4 07:36:43 2005 From: oren.tirosh at gmail.com (oren.tirosh at gmail.com) Date: 4 Jun 2005 04:36:43 -0700 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: <1117885003.321247.261130@g47g2000cwa.googlegroups.com> Ilpo Nyyss?nen wrote: > Nicolas Fleury writes: > > def foo(): > > with locking(someMutex) > > with opening(readFilename) as input > > with opening(writeFilename) as output > > ... > > How about this instead: > > with locking(mutex), opening(readfile) as input: > ... +1, and add PEP-328-like parentheses for multiline. Oren From smitty_one_each at bigfoot.com Sat Jun 11 17:17:41 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Sat, 11 Jun 2005 16:17:41 -0500 Subject: using python from c/c++ References: Message-ID: <87y89gbnka.fsf@bigfoot.com> >>>>> "alexandr" == alexandr writes: alexandr> Is it possible to create a library from my python module alexandr> that can be used from c/c++ application? http://boost.org/libs/python/doc/index.html From sakesun at boonthavorn.com Thu Jun 9 23:57:45 2005 From: sakesun at boonthavorn.com (Sakesun Roykiattisak) Date: Fri, 10 Jun 2005 10:57:45 +0700 Subject: Python Developers Handbook In-Reply-To: <1118372596.003161.290690@g49g2000cwa.googlegroups.com> References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> Message-ID: <42A90FB9.30609@boonthavorn.com> wooks wrote: >I thought that posting a link that contained the word ebay and a >subject title of Python Developers Handbook conveyed all the relevant >information and didn't want to patronise the NG. > >I have had 110 hits on the item but seem to have upset 3 people. > > >I am sorry. I don't have any other Python books to sell so it won't >happen again. > > > Don't blame yourself. People get upset by their own mind. Incidents were taken as false accused. From finite.automaton at gmail.com Thu Jun 9 14:43:47 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 9 Jun 2005 11:43:47 -0700 Subject: Any way to not create .pyc files? References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <1118342627.806463.178430@g14g2000cwa.googlegroups.com> >> PEP 304 would have helped, but it appears to be deceased. > Not sure it's deceased (a dead parrot?) - it's on the standards track, > it hasn't been rejected, and Skip has actually provided a patch to > implement the solution. It is possible that PEP 304 is really just pining for the fjords, but I don't know. Digging through the newsgroup, it looks like Skip's patch is for UNIX and progress has stalled in trying to get a Windows patch. Really, it's moot, since I'm not going to recompile Python and try to convince everyone to reinstall it. (the latter would be a herculean labor) :P I guess I sort of assumed that Python would ignore the .pyc files if it didn't have read access, but it could be some sort of permissions issue. Only a handful of users have write access. Maybe the issue happens when Python tries to /replace/ .pyc files with newer versions, but doesn't have permission to overwrite the old files? It doesn't help that I'm one step removed from the users and administrators, so I don't really have any diagnostic information besides people calling me up to say "it's broken". Feh. Python versioning could definitely cause a problem, but in this case everyone is using 2.3.5 (I should have mentioned that). > It would be *much* more sensible to find the underlying cause of the > problems and actually fix them :-) Amen! From bugbear at trim_papermule.co.uk_trim Thu Jun 23 10:05:44 2005 From: bugbear at trim_papermule.co.uk_trim (bugbear) Date: Thu, 23 Jun 2005 15:05:44 +0100 Subject: newbie - modules for jython (under grinder 3) ? Message-ID: <42bac1b8$0$2021$ed2e19e4@ptn-nntp-reader04.plus.net> I'm just trying to use Grinder 3 to beat up my http-app. Grinder 3 comes with its own jython.jar. Some of the sample scripts: http://grinder.sourceforge.net/g3/script-gallery.html use import statements that don't work for me. Reading around, these are reference to modules. Do I need a "proper" jython instead of the one that grinder ships with? Or... Do I need to get and install some modules? If the latter, where from and how? I note that not all Python modules can be used as Jython modules. My most urgent need is for the threading module, although I've faked my way round that by using Doug Lea's concurrent library in java, which I can call from Jython. http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/concurrent/intro.html But I'd like to know how to do it "right" BugBear From deets at web.de Sat Jun 18 09:24:18 2005 From: deets at web.de (Diez B. Roggisch) Date: Sat, 18 Jun 2005 15:24:18 +0200 Subject: Threading and serial port access In-Reply-To: <1119100180.442972.244100@g14g2000cwa.googlegroups.com> References: <1119100180.442972.244100@g14g2000cwa.googlegroups.com> Message-ID: <3hilk5FhbnplU1@uni-berlin.de> willie at macleod-group.com wrote: > Hi, > > I'm writing a program which requires the use of three serial ports and > one parallel port. My application has a scanning devices on each port, > which I can access fine with pyserial. However, I'm unsure of how > exactly I should be designing the program, I thought I could use > threading to start class: > > class scanner(Thread): > def __init__(self,port): > Thread.__init__(self) > self.port = port > def scan(self): > ser = serial.Serial(port) > print ser.portstr > id = ser.read(12) > ser.close > > But this doesn't work as I thought when I call it like: > > for port in range(0,totalserialports): # loop through all serial ports > print "starting thread for port %d" %(port) > NewThread = scanner(port) > NewThread.scan() > NewThread.start() > > I get: > > starting thread for port 0 > /dev/ttyS0 > > Now, I know that I haven't specified any port timeouts, but I don't > want it to timeout, I want to open each port and keep it open > indefinately. Threading seems to block waiting for the read from the > serial port. How can I open every serial port at the same time, read > from it, do an action and then go back to it? Anyone got any good > documentation sources for threading that explain things clearly and > gives examples? (I'm running python 2.3.4) The problem is not your code (as far as I can see that w/o running it), but that you didn't understand the threading API. You have to overload the run-method of a Thread object and then start your thread - which will result in executing the run method in a separate thread. Like this: class Poll(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.setDaemon(True) self.running = True def run(self): while self.running: .... # do whatever you want here for t in [Poll() for i in xrange(3)]: t.start() Apart from that the approach you use is wasting resources - if you are concerned about that (or better style...) use e.g. twisted with the serial and parallel support and its so-called select reactor. The idea behind that concept is that the OS is responsible for scannig IO-Ports. It notifies an application about newly arrived data by the system function select - which means that your program sits and waits not cosuming any resources until actual data arrives. See the module select for an overview, and google for "python twisted serial". regards, Diez From has.temp2 at virgin.net Fri Jun 3 19:13:09 2005 From: has.temp2 at virgin.net (has) Date: 3 Jun 2005 16:13:09 -0700 Subject: how to get name of function from within function? In-Reply-To: References: Message-ID: <1117840389.678357.293780@g14g2000cwa.googlegroups.com> Christopher J. Bottaro wrote: > Basically I want to wrap every function in try/except automatically. Simplest way to do that would be something like: def wrapFunction(func): def wrapper(*args, **kargs): try: return func(*args, **kargs) except Exception, e: raise # your error handling code here return wrapper HTH From richie at entrian.com Wed Jun 29 10:28:27 2005 From: richie at entrian.com (Richie Hindle) Date: Wed, 29 Jun 2005 15:28:27 +0100 Subject: MS Compiler to build Python 2.3 extension In-Reply-To: <1120054137.471983.240320@o13g2000cwo.googlegroups.com> References: <1120054137.471983.240320@o13g2000cwo.googlegroups.com> Message-ID: [Gary] > I recenly built a C API Python extension for Python 2.3 > on OS X, and now I need to build it for Windows. Will > [MS Visual Studio Pro 6.0] do the trick? Yes. That's exactly the compiler that Python 2.3 itself, and most 2.3 extensions, were built with. -- Richie Hindle richie at entrian.com From renato.ramonda at gmail.com Sat Jun 18 10:39:39 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Sat, 18 Jun 2005 16:39:39 +0200 Subject: extreme newbie In-Reply-To: <11b884bj3bp164@corp.supernews.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <11b884bj3bp164@corp.supernews.com> Message-ID: Grant Edwards ha scritto: > Python is required and Java is optional and not installed by > default in the Linux distros I'm familiar with. > > I don't know how many Windows systems have Java installed. > I don't think any of mine do. It's pretty much the other way round: java CANNOT be included by default in any (free) linux distro for license reasons, and it CANNOT be included by default in Windows as a consequence of court ruling: Microsoft is actually _not allowed_ to include Java. The only system (apart from solaris, I guess) that has a JVM by default is OSX, and it's _NOT_ sun's one, but the internally developed one. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From kbk at shore.net Thu Jun 2 00:40:11 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 2 Jun 2005 00:40:11 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200506020440.j524eB3m025074@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 344 open ( +2) / 2845 closed ( +6) / 3189 total ( +8) Bugs : 916 open (-20) / 5014 closed (+40) / 5930 total (+20) RFE : 191 open ( +2) / 163 closed ( +4) / 354 total ( +6) New / Reopened Patches ______________________ Optimization for textwrap (2005-05-26) http://python.org/sf/1209527 opened by Connelly Build Python2.4.1 on AIX5 using xlc v6 (2005-05-27) http://python.org/sf/1209781 opened by Gangadhar NPK Split email headers near a space (2005-05-29) http://python.org/sf/1210680 opened by Noam Raphael Add st_flags support to (l)stat function (2005-05-31) http://python.org/sf/1212117 opened by Diego Petten? mode argument for fileinput class (2005-05-31) http://python.org/sf/1212287 opened by Reinhold Birkenfeld Improved profiler (2005-06-01) http://python.org/sf/1212837 opened by Brett Rosen option to allow reload to affect existing instances (2005-06-01) http://python.org/sf/1212921 opened by Brett Rosen new patch for fixing skipitem() in getargs.c (2005-06-01) http://python.org/sf/1212928 opened by Reinhold Birkenfeld note that os.chown can have -1 as an argument (2005-06-01) http://python.org/sf/1213031 opened by Reinhold Birkenfeld Patches Closed ______________ updates for the compiler package (2005-05-21) http://python.org/sf/1206077 closed by sxanth make float packing copy bytes when they can (2005-04-12) http://python.org/sf/1181301 closed by mwh webbrowser.Netscape.open bug fix (2005-02-20) http://python.org/sf/1144816 closed by birkenfeld cgitb: make more usable for 'binary-only' software (2003-06-10) http://python.org/sf/751943 closed by birkenfeld bug skipping optional keyword arguments of type "w#" (2004-07-06) http://python.org/sf/985713 closed by birkenfeld Optional keyword unicode args not handled correctly (2003-12-04) http://python.org/sf/853890 closed by birkenfeld New / Reopened Bugs ___________________ urllib2's urlopen() method causes a memory leak (2005-05-25) http://python.org/sf/1208304 opened by Petr Toman no CoreGraphics library under Python 2.4 (2005-05-25) CLOSED http://python.org/sf/1208468 opened by Jurjen N.E. Bos longs should be pickled in hexadecimal (2005-05-26) CLOSED http://python.org/sf/1209324 opened by Fredrik Johansson divmod documentation shd reference // not / (2005-05-26) CLOSED http://python.org/sf/1209411 opened by Alan os.path.join() fails if 2nd arg is a UNC path (2005-05-26) http://python.org/sf/1209447 opened by John Ehresman spurious blank page in dist.pdf (2005-05-27) http://python.org/sf/1209560 opened by paul rubin dict.popitem documentation should mention empty dict case (2005-05-27) CLOSED http://python.org/sf/1209671 opened by William Chang doc bug in Lock.acquire (2005-05-27) http://python.org/sf/1209880 opened by Chris Perkins Typo in "Differences from mimelib" (2005-05-27) http://python.org/sf/1210001 opened by Zumi comma separated cookie values (2005-05-28) http://python.org/sf/1210326 opened by tvogt Cursors not correctly closed after exception. (2005-05-28) http://python.org/sf/1210377 opened by Ragnar Ouchterlony An error in Python Tutorial (2005-05-29) CLOSED http://python.org/sf/1210832 opened by Gene mmap's resize method resizes the file in win32 but not unix (2003-04-27) CLOSED http://python.org/sf/728515 reopened by facundobatista parser tells invalid syntax with correct code (2005-05-31) CLOSED http://python.org/sf/1211639 opened by ntrunk itertools.groupby ungraceful, un-Pythonic (2005-05-31) CLOSED http://python.org/sf/1212077 opened by Mike Coleman str.lower() to have an IMPORTANT NOTE or it's for magicians (2005-05-31) http://python.org/sf/1212195 opened by Nikos Kouremenos anydbm and 'n' flag (2005-05-31) CLOSED http://python.org/sf/1212223 opened by Jack Moffitt Incorrect result for regular expression - "|(hello)|(world)" (2005-06-01) http://python.org/sf/1212411 opened by Vijay Kumar Python 2.5 CVS broken for HP-UX platform? (2005-06-01) http://python.org/sf/1212703 opened by Vincent Jamart Python segfaults on OpenBSD (tested 3.4 and 3.5) (2005-06-01) http://python.org/sf/1212900 opened by Fabien Devaux Bugs Closed ___________ bug in unichr() documentation (2005-02-11) http://python.org/sf/1120777 closed by fdrake Line ending documentation is misleading (2005-03-21) http://python.org/sf/1167922 closed by fdrake no CoreGraphics library under Python 2.4 (2005-05-25) http://python.org/sf/1208468 closed by mwh Issue in grammar (2005-05-24) http://python.org/sf/1207501 closed by mwh Problem with abs function (2005-05-16) http://python.org/sf/1202946 closed by rhettinger longs should be pickled in hexadecimal (2005-05-26) http://python.org/sf/1209324 closed by rhettinger divmod documentation shd reference // not / (2005-05-26) http://python.org/sf/1209411 closed by rhettinger dict.popitem documentation should mention empty dict case (2005-05-27) http://python.org/sf/1209671 closed by rhettinger An error in Python Tutorial (2005-05-29) http://python.org/sf/1210832 closed by birkenfeld Windows os.path.isdir bad if drive only (2002-02-11) http://python.org/sf/516232 closed by facundobatista test_signal hangs -- signal broken on OpenBSD? (2002-04-26) http://python.org/sf/549081 closed by facundobatista popen4 doesn't close filedescriptors when in Threads (2003-07-09) http://python.org/sf/768649 closed by facundobatista Sudden death with SIGSEGV in RtlEnterCriticalSection (2003-06-30) http://python.org/sf/763190 closed by facundobatista can't CNTRL-C when running os.system in a thread (2003-06-18) http://python.org/sf/756940 closed by facundobatista socketmodule.c: inet_pton() expects 4-byte packed_addr (2003-04-30) http://python.org/sf/730222 closed by facundobatista mmap's resize method resizes the file in win32 but not unix (2003-04-27) http://python.org/sf/728515 closed by facundobatista Core Dumps : Python2.2.2 (2003-04-24) http://python.org/sf/727241 closed by facundobatista "build_ext" "libraries" subcommand not s (2003-04-07) http://python.org/sf/716634 closed by facundobatista Thread running (os.system or popen#) (2003-03-11) http://python.org/sf/701836 closed by facundobatista Canvas origin is off-canvas in create_<item>(). Worka (2003-03-10) http://python.org/sf/700650 closed by facundobatista Canvas Widget origin is off-screen (2003-03-08) http://python.org/sf/699816 closed by facundobatista Profilier hooked into SystemExit (2003-02-15) http://python.org/sf/687297 closed by facundobatista String formatting operation Unicode problem. (2003-01-28) http://python.org/sf/676346 closed by facundobatista os.popen+() can take string list and bypass shell. (2003-01-12) http://python.org/sf/666700 closed by facundobatista doctest and exception messages (2002-12-16) http://python.org/sf/654783 closed by facundobatista Misuse of /usr/local/in setup.py (2002-11-19) http://python.org/sf/640553 closed by facundobatista parser tells invalid syntax with correct code (2005-05-31) http://python.org/sf/1211639 closed by doerwalter urllib has spurious print statement (2005-05-20) http://python.org/sf/1205544 closed by birkenfeld Description of string.lstrip() needs improvement (2005-05-15) http://python.org/sf/1202395 closed by rhettinger FutureWarning: %u/%o/%x/%X of negative int will return a sig (2003-06-19) http://python.org/sf/757365 closed by birkenfeld digraphs on komment lines / xlib (2003-07-16) http://python.org/sf/772176 closed by birkenfeld itertools.groupby ungraceful, un-Pythonic (2005-05-31) http://python.org/sf/1212077 closed by rhettinger anydbm and 'n' flag (2005-05-31) http://python.org/sf/1212223 closed by jafo memory leak in pickle/cPickle [2.2.3] (2003-07-14) http://python.org/sf/770997 closed by birkenfeld file.read returns reaches EOF when it shouldn't (2004-01-11) http://python.org/sf/875157 closed by birkenfeld Minor bug in urllib docs (2005-05-03) http://python.org/sf/1194249 closed by akuchling asyncore.loop() documentation (2005-04-12) http://python.org/sf/1181939 closed by akuchling Typo in Curses-Function doc (2005-02-15) http://python.org/sf/1123268 closed by akuchling SMTPHandler argument misdescribed (2005-02-13) http://python.org/sf/1121875 closed by akuchling incorrect constant names in curses window objects page (2005-01-19) http://python.org/sf/1105706 closed by akuchling curses.textpad raises error (2005-02-27) http://python.org/sf/1152762 closed by akuchling New / Reopened RFE __________________ expat binding for XML_ParserReset (2005-05-25) http://python.org/sf/1208730 opened by John Eikenberry add single html files (2005-05-27) http://python.org/sf/1209562 opened by paul rubin calling it revert is fine with me (2005-05-27) CLOSED http://python.org/sf/1209664 opened by paul rubin "break" and "continue"-ing out of nested 'for' loops (2005-05-29) CLOSED http://python.org/sf/1210975 opened by Geraint Luff sets needs an 'arbitrary element' method (2005-05-31) http://python.org/sf/1212091 opened by Mike Coleman Prepending Text (2005-05-31) http://python.org/sf/1212169 opened by Aaron Elbaz RFE Closed __________ Clipboard Cleared on Close (2005-05-24) http://python.org/sf/1207592 closed by kbk Bottom Scroll Bar (2005-05-24) http://python.org/sf/1207613 closed by kbk calling it revert is fine with me (2005-05-27) http://python.org/sf/1209664 closed by rhettinger "break" and "continue"-ing out of nested 'for' loops (2005-05-29) http://python.org/sf/1210975 closed by rhettinger From prabapython at yahoo.co.in Tue Jun 14 02:00:09 2005 From: prabapython at yahoo.co.in (praba kar) Date: Tue, 14 Jun 2005 07:00:09 +0100 (BST) Subject: regarding cgi In-Reply-To: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: <20050614060009.83183.qmail@web8409.mail.in.yahoo.com> Dear All, I have doubt regarding headers in cgi programming. If I gives "Content-Type:text/plain" then I try to print html contents. Is right or wrong after giving content-type: text/plain? regards Prabahar _______________________________________________________ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com From benji at benjiyork.com Fri Jun 24 00:08:34 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 24 Jun 2005 00:08:34 -0400 Subject: A World Beyond Capitalism 2005, In-Reply-To: <42BB7945.1BDF8ACF@pauahtun.org> References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> <3cacc254a9d2010cbf5298fc3bd955b0@localhost.talkaboutprogramming.com> <42BB7945.1BDF8ACF@pauahtun.org> Message-ID: <42BB8742.10509@benjiyork.com> Ivan Van Laningham wrote: > And what defines a "python activist" anyway? Blowing up Perl > installations worldwide? +1 QOTW -- Benji York From dalke at dalkescientific.com Wed Jun 8 17:23:02 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 08 Jun 2005 21:23:02 GMT Subject: Fast text display? References: Message-ID: Christopher Subich wrote: > You're off by a decimal, though, an 80-column line > at 20ms is 4kbytes/sec. D'oh! Yeah, I did hundredths of a second instead of thousands. > My guess is that any faster throughput than > 10kbytes/sec is getting amusing for a mud, which in theory intends for > most of this text to be read anyway. Which is why I don't think you'll have a problem with any of the standard GUI libraries. > That looks quite good, except that Trolltech doesn't yet have a GPL-qt > for Win32. Cost and license weren't listed as requirements. :) You *did* say "hobby" though in post-hoc justification, I've known people with some pretty expensive hobbies. > See the scrolling problem in the original post, as to why I can't use it > as a temporary user interface. :) Indeed, but MUDs 15 years ago could run in a terminal and display colored text via ANSI terminal controls, letting the terminal itself manage history and scrolling. I had some sort of TSR for the latter, under DOS. Andrew dalke at dalkescientific.com From richard.a.patterson at lmco.com Thu Jun 30 17:31:37 2005 From: richard.a.patterson at lmco.com (Richard Patterson) Date: Thu, 30 Jun 2005 17:31:37 -0400 Subject: building 2.4.1 on HPUX References: Message-ID: In case someone else reads these for information about a simliar problem.... It turns out, that I did not need to edit the setup.py script, I could just ignore the compile time INFO statements regarding Tk/Tcl libs and includes.. I did need to modify the Modules/Setup file however... But the final run-time trick was to define two environment variables... TK_LIBRARY=/opt/tk/lib/tk8.4, and TCL_LIBRARY=/opt/tcl/lib/tcl8.4 Now "make test", "./python Lib/test/test_tcl.py", and all my python 1.6 scripts seem to work. I don't know if this is the best solution, but it seems to work. "Richard Patterson" wrote in message news:d9sisp$mfq$1 at knight.vf.lmco.com... > I'm trying to compile python 2.4.1, on HPUX10.20, with support for tk and > tcl 8.4 (installed in /opt/tk and /opt/tcl). I assume this means I need to > compile the tkinter module too.. > > I was getting make errors, saying it couldn't find tcl/tk libs or headers... > so I changed the setup.py script, hard coding library and include paths for > tcl/tk, but it still didn't build the _tkinter module. So next I modified > the Modules/Setup file, uncommenting, and changing compiler arguments to > point to the correct lib and include paths. At least it built this time... > so I ran make test, and got the following error for test_tcl: > > TclError: Can't find a usable tk.tcl in the following directories: > /opt/tcl8.4.4/lib/tk8.4 home directory> > > On my system, /opt/tk is a link to /opt/tk8.4.4, therefore, the tk.tcl file > is really in /opt/tk/lib/tk8.4/tk.tcl, but why didn't it look there? > > I'm stumped. Did I really have to hack the setup.py and Setup files? Where > is it getting its paths from? Is my environment wrong, or do I need to > change some configure parameters? I'm hoping someone out there knows what > I'm doing wrong, or perhaps can point me in the right direction. Thanks > again > > Rich > > > > From jstroud at mbi.ucla.edu Fri Jun 24 18:47:45 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 24 Jun 2005 15:47:45 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <200506241547.45894.jstroud@mbi.ucla.edu> On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote: > with colour do begin > red := 0; blue := 255; green := 0; > end; > > instead of: > > colour.red := 0; colour.blue := 255; colour.green := 0; > > Okay, so maybe it is more of a feature than a trick, but I miss it and it > would be nice to have in Python. class color: # americanized red = 0 blue = 255 green = 0 Less typing than pascal. Also avoids those stupid little colons. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From agriff at tin.it Tue Jun 7 17:02:36 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 07 Jun 2005 21:02:36 GMT Subject: time consuming loops over lists References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> Message-ID: <292ca1h01uhj0jfsehvs50i0t6vcaaun01@4ax.com> On Tue, 07 Jun 2005 18:13:01 +0200, "Diez B. Roggisch" wrote: >Another optimization im too lazy now would be to do sort of a "tree >search" of data[i] in rngs - as the ranges are ordered, you could find >the proper one in log_2(len(rngs)) instead of len(rngs)/2. I don't see a "break" so why the "/2" ? also IIUC the ranges are more than just ordered... they're all equal and computed by for i in xrange(no_of_bins+1): rngs[i] = dmin + (rng*i) so my guess is that instead of searching with for j in xrange(len(rngs)-1): if rngs[j] <= data[i] < rngs[j+1]: one could just do j = int((data[i] - dmin)/rng) The code with this change gets roughly about twice faster. Andrea From steve at REMOVETHIScyber.com.au Sun Jun 26 06:41:44 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 20:41:44 +1000 Subject: noob question References: Message-ID: On Sat, 25 Jun 2005 22:06:08 -0700, Matt Hollingsworth wrote: > Hello, > > Very new to python, so a noob question. When I've written stuff in > JavaScript or MEL in the past, I've always adopted the variable naming > convention of using a $ as the first character (no, I don't use perl, > never have). Not possible in python. What are some good options that > people commonly use so that they can easily and quickly identify > variable with just a glance? Learn the language rather than relying on magic symbols. I don't understand why you would need to have a special naming convention to identify variables. Magic symbols just get in the way, especially in a language like Python where everything is an object. (Except keywords and operators, I suppose.) Eg, when you do something like this: myInstance = MyClass(something) print myInstance.method(somethingelse) everything except "print" is an object. Or rather, a name that references an object. Python doesn't really have variables as such. It has names and objects. Most of the time, you can think of names as being like variables. Can anyone think of some good, easy to understand examples of where Python's name/object model differs from the variable/value model? -- Steven. From kveretennicov at gmail.com Wed Jun 22 21:01:27 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 23 Jun 2005 03:01:27 +0200 Subject: Detect windows shutdown In-Reply-To: References: Message-ID: <4660fe300506221801765dc76f@mail.gmail.com> On 6/22/05, Austin wrote: > My program is running on windows and it is wrritten by Python and wxPython, ... > Is there any way to dectect windows shutdown or reboot? Will wx.EVT_END_SESSION or wx.EVT_QUERY_END_SESSION help? - kv From fuzzyman at gmail.com Mon Jun 20 06:38:37 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Jun 2005 03:38:37 -0700 Subject: login website that using PHP In-Reply-To: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> References: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> Message-ID: <1119263917.054114.213120@g14g2000cwa.googlegroups.com> The behaviour with the browser is what is known as a 'session cookie' -the site sets it when you login and the browser keeps it until you end the session by closing the browser. You handle the cookie using ClientCookie (Python 2.3) or cookielib (Python 2.4). You need to create a cookiejar instance and an opener that uses HTTPCookieProcessor (and your cookiejar). When you've done that - calls to your opener will fetch pages and handle the cookie *compeltely automatically*. There is an example of doing that at http://www.voidspace.org.uk/python/articles.shtml#http The authentication is via an html form. You can handle this using ClientForm - or you can look at the HTML source of the page and just have your opener (as above) send the right values to the URL. If you have problems - post the details here and people will help. It is *possible* that the javascript does 'magic' on the form submission (client side encryption is one possibility). That is very hard to automatically duplicate from Python because you would need to parse the python and mimic the page DOM to duplicate the effect. It might be easier to use PAMIE to automate the form submission in the browser. I've never tried this myself - but seen the announcements here. Best Regards, Fuzzy http://www.voidspace.org.uk/python unfortunately voidspace is temporarily down :-( From steven.bethard at gmail.com Thu Jun 2 21:10:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 02 Jun 2005 19:10:45 -0600 Subject: REQ: Small Perl to Python conversion needed In-Reply-To: <429fa98b$1@news.eftel.com> References: <020620052018031433%user@unknown.invalid> <429fa98b$1@news.eftel.com> Message-ID: John Machin wrote: > freq_dict = {} > ... > if thing in freq_dict: > freq_dict[thing] += 1 > else: > freq_dict[thing] = 1 > > or, less plainly, > > freq_dict[thing] = freq_dict.get(thing, 0) + 1 or try: freq_dict[thing] += 1 except KeyError: freq_dict[thing] = 1 STeVe From ptmcg at austin.rr.com Wed Jun 15 11:33:44 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Jun 2005 08:33:44 -0700 Subject: how to use pyparsing for identifiers that start with a constant string References: <1118784164.619007.74150@g14g2000cwa.googlegroups.com> <42af57c0$1_2@newspeer2.tds.net> Message-ID: <1118849624.117660.165240@o13g2000cwo.googlegroups.com> Be careful, Kent. You may get tagged as "the new pyparsing guy." :) -- Paul From mwm at mired.org Sat Jun 11 16:08:54 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 11 Jun 2005 15:08:54 -0500 Subject: Best Web dev language References: <11al0nhr4opfgaa@corp.supernews.com> Message-ID: <86br6c4pwp.fsf@guru.mired.org> "Jon Slaughter" writes: > Also, can anyone recommend any book or web page that gives an introduction > to the method in which one programs web sites? I am not clear on who one, > for instance, would use C++ as the language for a web site except by using > it to create html... I'm not sure if basicaly all languages goal is creating > html dynamically or if there is more to do. What I mean is that basicaly > one is using some other language to wrap the html code or possibly generate > it at run-time for dynamic results. (so all client based web interfaces are > really just html readers but all this "extra" stuff is used to make certain > things easier and dynamic(just as generating tables and forms and all that). That's one way to look at it. Personally, I prefer to think of HTML as the "UI toolkit" for web development. It's more like CLI code that GUI code, in that you have three distinct phases of "process, display, await response" rather than waiting for UI events which trigger data processing and a display update. As such, you can use pretty much any language that can connect to the toolkit. CGI is pretty low-level, and pretty much anything can be used. C++ and Java both certainly get used. Others have mentioned LISP variants. I've used the shell and Rexx. These days, I prefer Python, but that's what you'd expect from somene reading c.l.python. Anything you're comfortable with should work. In particular, since the user is going to spend time waiting on network delays, any performance issues the language implementation may have will be negligible for a single user. Someone mentioned that you might "require JavaScript on the client side". I recommend against that - people and organizations disable JavaScript for security reasons, and browsers on portable devices may not have JavaScript at all. Why limit your audience? If you understand HTML, it's possible to write a web page that uses JavaScript (or any other such technology) for flashy effects, but still functions properly if the user has disabled JavaScript, or doesn't have it available. But that's a long discussion - see for more information. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From rkern at ucsd.edu Wed Jun 29 08:48:59 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 29 Jun 2005 05:48:59 -0700 Subject: Newbie: Explain My Problem In-Reply-To: <42C26CF5.1010107@lexicon.net> References: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> <42C26CF5.1010107@lexicon.net> Message-ID: John Machin wrote: > ChuckDubya at gmail.com wrote: > [snip] > >>while counter != 0: >> if guess == num: > > [snip] > > Others have told you already what was wrong with your program. Here's a > clue on how you could possibly help yourself: > > 1. Each time around your loop, print the values of the interesting > objects, in this case counter and guess. > E.g. before the "if" statement above, put something like this: > print "guess = %r, counter = %r" % (guess, counter) > That would have shown "guess" containing a string e.g. > guess = '42', counter = 4 > instead of an integer e.g. > guess = 42, counter = 4 > > 2. Examine the logic carefully. The answer to your second problem was > just staring you in the face -- you hadn't pulled the ripcord after the > counter became zero. 3. Sign up for the Python-tutor list. (Okay, that's not quite "helping yourself," but it's still good advice, I think). http://mail.python.org/mailman/listinfo/tutor -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From saint.infidel at gmail.com Wed Jun 1 13:45:55 2005 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2005 10:45:55 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> Message-ID: <1117647955.132014.309210@g49g2000cwa.googlegroups.com> "God made me an atheist, who are you to question His wisdom?" -- Saint Infidel the Skeptic From JOHNWUN at aol.com Mon Jun 6 14:27:52 2005 From: JOHNWUN at aol.com (Grooooops) Date: 6 Jun 2005 11:27:52 -0700 Subject: the python way? Message-ID: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> Hi All, I've been lurking the list for a month and this is my first post. I am hoping this post is appropriate here, otherwise, my apologies. I'm somewhat new to Python, (I'm reading all the tutorials I can find, and have read through Andre Lessa's Developers Handbook.) I am trying to learn the Python way of thinking as well as the syntax. I popped this bit of code together for fun, based on a previous post regarding randomizing a word. This shuffles a word, then splits out the vowels and then reassembles it with the vowels interpolated between consonants. (To create plausible sounding gibberish) The code just seems kind of bulky to me. I am wondering, is this an efficient way to do things, or am I making things harder than necessary? #--------------------------begin code------------------ """scrambles a word, but creates plausable gibberish""" import random def shuffled(s): """ scrambles word""" l = list(s) random.shuffle(l) return ''.join(l) def contains(alist,b): """...is letter b in list a...""" ret = [] for all in alist: #print all if all==b: return 1 return 0 def newZip(a1,a2): """ reassemble """ l1=len(a1) l2=len(a2) longest = [a1,a2][l10: ret = ret + longest.pop() if len(shortest)>0: ret = ret + shortest.pop() return ret def reinterpolate(word): """ main function """ wlist = shuffled(list(word)) vlist = list('aeiouy') # ok, y isn't really a vowel, but... vees = filter(lambda x: contains(vlist,x),wlist) cons = filter(lambda x: not(contains(vlist,x)),wlist) a=list(vees) b=list(cons) return newZip(a,b) word = "encyclopedia" print reinterpolate(word) #-------------------------------end code--------------------------- BTW: I'm just curious, is there an easier way to copy-paste code snippets from the interpreter so that it removes the '... ' and the '>>> ' from the examples? I'm using search and replace now which works, but if there is a better way, I'd like to know. thanks in advance, -J From newsgroups at jhrothjr.com Thu Jun 16 14:06:50 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 16 Jun 2005 12:06:50 -0600 Subject: utf8 and ftplib References: Message-ID: <11b3ftrea0k2e29@news.supernews.com> "Richard Lewis" wrote in message news:mailman.540.1118935910.10512.python-list at python.org... > Hi there, > > I'm having a problem with unicode files and ftplib (using Python 2.3.5). > > I've got this code: > > xml_source = codecs.open("foo.xml", 'w+b', "utf8") > #xml_source = file("foo.xml", 'w+b') > > ftp.retrbinary("RETR foo.xml", xml_source.write) > #ftp.retrlines("RETR foo.xml", xml_source.write) > > It opens a new local file using utf8 encoding and then reads from a file > on an FTP server (also utf8 encoded) into that local file. It comes up > with an error, however, on calling the xml_source.write callback (I > think) saying that: > > "File "myscript.py", line 75, in get_content > ftp.retrbinary("RETR foo.xml", xml_source.write) > File "/usr/lib/python2.3/ftplib.py", line 384, in retrbinary > callback(data) > File "/usr/lib/python2.3/codecs.py", line 400, in write > return self.writer.write(data) > File "/usr/lib/python2.3/codecs.py", line 178, in write > data, consumed = self.encode(object, self.errors) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 76: > ordinal not in range(128)" > > I've tried using both the commented lines of code in the above example > (i.e. using file() instead of codecs.open() and retlines() instead of > retbinary()). retlines() makes no difference, but if I use file() > instead of codecs.open() I can open the file, but the extended > characters from the source file (e.g. foreign characters, copyright > symbol, etc.) all appear with an extra character in front of them > (because of the two char width in utf8?). > > Is the xml_source.write callback causing the problem here? Or is it > something else? Is there any way that I can correctly retrieve a utf8 > encoded file from an FTP server? It looks like there are at least two problems here. The major one is that you seem to have a misconception about utf-8 encoding. The _disk_ version of the file is what is encoded in utf-8, and it has to be decoded to unicode on being read later. In other words, what you got is what you should have put on disk without any conversion. As you noted, when you did that, the FTP part of the process worked. Whatever program you are using to read it has to then decode it from utf-8 into unicode. Failure to do this is what is causing the extra characters on output. The object returned by codecs.open raised an exception because it expected a unicode string on input; it got a character string already encoded in utf-8 format. The internal mechanism is first going to try to decode that into unicode before then encoding it into utf-8. Unfortunately, the default for encoding or decoding (outside of special contexts) is ASCII-7. So everything outside of the ASCII range is invalid. Amusingly, this would have worked: xml_source = codecs.EncodedFile("foo.xml", "utf-8", "utf-8") It is, of course, an expensive way of doing nothing, but it at least has the virtue of being good documentation. HTH John Roth > > Cheers, > Richard From python at rcn.com Sat Jun 18 11:54:04 2005 From: python at rcn.com (Raymond Hettinger) Date: 18 Jun 2005 08:54:04 -0700 Subject: Set of Dictionary References: Message-ID: <1119110044.397538.225320@g14g2000cwa.googlegroups.com> [Vibha] > I know sets have been implemented using dictionary but > I absolutely need to have a set of dictionaries...any > ideas how to do that? Yes. Create a dictionary subclass that is hashable. Be sure not to mutate it after using it in a set. >>> class FrozenDict(dict): def __hash__(self): try: return self._hash except AttributeError: self._hash = hash(tuple(sorted(self.iteritems()))) return self._hash >>> d1 = FrozenDict(a=1, b=2, c=3) >>> d2 = FrozenDict(d=4, e=5, f=6) >>> d3 = FrozenDict(b=2, c=3, a=1) >>> s = set([d1, d2, d3]) >>> s set([{'e': 5, 'd': 4, 'f': 6}, {'a': 1, 'c': 3, 'b': 2}]) >>> d2 in s True Raymond Hettinger From grante at visi.com Mon Jun 6 19:57:09 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 06 Jun 2005 23:57:09 -0000 Subject: Creating file of size x References: <42a4cea6$1@griseus.its.uu.se> <56qdnYcDS9f3TDnfRVn-tw@speakeasy.net> <42a4d256$1@griseus.its.uu.se> <11a9mlh4t7oif3c@corp.supernews.com> <42a4db07$1@griseus.its.uu.se> Message-ID: <11a9oml9hn8k8a8@corp.supernews.com> On 2005-06-06, Jan Danielsson wrote: >>>The problem is that the design I'm working on won't guarantee >>>what order the blocks will be returned in -- so I need to be >>>able to seek to block n's location and write the ckeck block. >> >> Exactly. And precisely how did that fail? > > It didn't -- but that's on my platform; What sort of programmer are you? If it works on your computer, it's done, ship it! ;) > I have no idea how it'll work on another platform; which is > why I wanted to be able to first create the file of the > specified size, and then start writing to it. > >>>Next block could be m, where m < n. So, they aren't continous. >> >> If you do a seek before each write, it doesn't matter. > > According to Python, posix, Linux, Windows, ANSI-C? Good question. The Python documentation for the file object's seek method is mute on the the topic of seeking past EOF. I believe the observed behavior is required by POSIX, SVr4, and BSD for lseek() (which, I presume, is what Python calls on those platforms). That should have you covered for all of the Linux and Linux-like OSes (included Mac OS X). Under Win32, I don't know if there's an lseek() or what it does. I would guess that whoever wrote the file object's seek() method went to some effort to make sure it works the same on all platforms. As somebody else pointed out, the following should work: f = file('name','wb') f.write('\x00' * requiredFileLength) Then just do f.seek()/f.write() as the blocks come in. -- Grant Edwards grante Yow! Sometime in 1993 at NANCY SINATRA will lead a visi.com BLOODLESS COUP on GUAM!! From JOHNWUN at aol.com Mon Jun 27 18:11:11 2005 From: JOHNWUN at aol.com (Grooooops) Date: 27 Jun 2005 15:11:11 -0700 Subject: FlashMX and Py2exe doesn't fly... Message-ID: <1119910271.719937.101370@g43g2000cwa.googlegroups.com> Flash and Python could be a VERY powerful pair of tools for building quick apps, Yet I don't see much on the web about it. I was excited to see that it is possible to make them play together here: http://www.klaustrofobik.org/blog/archives/000235.html Unfortunately, these folks seem to have gotten stuck on compiling the py files to exe, and since I don't see reference to it anywhere else, I was wondering if anyone here knew why it didn't work, or if anyone had ideas about how to make it work. Normally I would put some test code here, but I'm way out of my league. Just insanely curious... Any thoughts??? Thanks, -J From spam.csubich+block at block.subich.spam.com Tue Jun 14 00:13:44 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Tue, 14 Jun 2005 00:13:44 -0400 Subject: ANN: pyparsing-1.3.1 released In-Reply-To: <1118675563.206703.263700@g14g2000cwa.googlegroups.com> References: <1118675563.206703.263700@g14g2000cwa.googlegroups.com> Message-ID: Paul McGuire wrote: > (sorry if this is a double-post - I tried posting this last night but I > think GoogleGroups ate it) > > Pyparsing is a pure-Python class library for quickly and easily > constructing recursive-descent parsers. Pyparsing takes a > "building-block" approach to parser construction, as opposed to code > generation methods (such as lex/yacc) or pattern definition strings > (such as regular expressions). Funnily enough, I've been thinking about something exactly like this. I've realized that my desired scripting language for the mud client I'm writing is very much a CFG, so simple regexes aren't going to cut it. The biggest issue for me is command syntax -- commands can have one of a number of parameter formats (number and type of parameters can vary). With a special command-marker at the beginning of the expression, I know unambiguously what is a command and what is not, but I'd need to look up in a dictionary (indexed by command name) the types. Is the pyparsing tokenizer flexible enough to let me do this sort of thing easily? From dalke at dalkescientific.com Tue Jun 7 16:41:54 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 07 Jun 2005 20:41:54 GMT Subject: split up a list by condition? References: <3gjpk0FcrnknU1@individual.net> <3gmabbFd6jmpU2@individual.net> Message-ID: Reinhold Birkenfeld wrote: >>> So I think: Have I overlooked a function which splits up a sequence >>> into two, based on a condition? Such as >>> >>> vees, cons = split(wlist[::-1], lambda c: c in vocals) > This is clear. I actually wanted to know if there is a function which I > overlooked which does that, which wouldn't be a maintenance nightmare at > all. Not that I know of, but if there is one it should be named "bifilter", or "difilter" if you prefer Greek roots. :) def bifilter(test, seq): passes = [] fails = [] for term in seq: if test(term): passes.append(term) else: fails.append(term) return passes, fails >>> bifilter("aeiou".__contains__, "This is a test") (['i', 'i', 'a', 'e'], ['T', 'h', 's', ' ', 's', ' ', ' ', 't', 's', 't']) >>> Another implementation, though in this case I cheat because I do the test twice, is >>> from itertools import ifilter, ifilterfalse, tee >>> def bifilter(test, seq): ... seq1, seq2 = tee(seq) ... return ifilter(test, seq1), ifilterfalse(test, seq2) ... >>> bifilter("aeiou".__contains__, "This is another test") (, ) >>> map(list, _) [['i', 'i', 'a', 'o', 'e', 'e'], ['T', 'h', 's', ' ', 's', ' ', 'n', 't', 'h', 'r', ' ', 't', 's', 't']] >>> Andrew dalke at dalkescientific.com From fredrin at ifi.uio.no Thu Jun 30 04:57:16 2005 From: fredrin at ifi.uio.no (Fredrik Normann) Date: Thu, 30 Jun 2005 10:57:16 +0200 Subject: Reading files in /var/spool/rwho/whod.* In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Mon, 27 Jun 2005 13:26:12 +0200, Fredrik Normann > declaimed the following in comp.lang.python: > > >>Hello, >> >>I'm trying to read the binary files under /var/spool/rwho/ so I'm wondering if >>anyone has done that before or could give me some clues on how to read those >>files. I've tried to use the binascii module without any luck. >> > > Have you looked at the struct module? > Thanks for the tip. A friend of mine helped me with making this small script: #!/usr/bin/env python """whod file parser. Made by: Igor V. Rafienko This tiny script tries to grock whod files. """ from struct import calcsize, unpack, pack from socket import ntohl import time outmp_format = '8s8s4s' whoent_format = '%ds4s' % calcsize(outmp_format) almost_whod = 'cc2s4s4s32s12s4s' def make_string(s): """Stupid C. Chop the string off at the first '\0'.""" index = s.find('\0') if index != -1: return s[:index] # fi # end make_string def make_time(seconds): """Convert from seconds since Epoch to ISO8601.""" return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(seconds)) # end make_time def make_int(binary): """Convert binary from network representation to host int.""" assert len(binary) == 4, "ints are 4 bytes long here" if calcsize("i") == 4: return ntohl(unpack("i", binary)[0]) elif calcsize("l") == 4: return ntohl(unpack("l", binary)[0]) else: raise "Dammit! no suitable integral type" # fi # end make_int def parse_one_outmp(binary_data): """Parse an outmp struct.""" out_line, out_name, out_time = unpack(outmp_format, binary_data) out_time = make_int(out_time) return out_line, out_name, out_time # end parse_one_outmp def parse_one_whoent(binary_data): """Parse a whoent struct.""" outmp_part, we_idle = unpack(whoent_format, binary_data) we_idle = make_int(we_idle) out_line, out_name, out_time = parse_one_outmp(outmp_part) return out_line, out_name, out_time, we_idle # end parse_one_whoent def parse_one_file(binary_data): """Parse the entire thing.""" # First we parse everything, except for the whoent-array prefix = unpack(almost_whod, binary_data[:calcsize(almost_whod)]) print "prefix has %d elemenets" % len(prefix) print "wd_vers:", ord(prefix[0]) print "wd_type:", ord(prefix[1]) print "wd_fill:", make_string(prefix[2]) print "wd_sendtime:", make_time(make_int(prefix[3])) print "wd_recvtime:", make_time(make_int(prefix[4])) print "wd_host: ", make_string(prefix[5]) load = prefix[6] print "wd_load avg: %d, %d, %d" % tuple([make_int(x) for x in (load[:4], load[4:8], load[8:])]) print "wd_boottime", make_time(make_int(prefix[7])) sz = calcsize(whoent_format) array_data = binary_data[calcsize(almost_whod):] assert len(array_data) % sz == 0, "Aiee! corrupt chunk?" whoent_chunks = [ array_data[sz*x:sz*(x+1)] for x in range(len(array_data) / sz) ] print "%d whoent chunks" % len(whoent_chunks) for out_line, out_name, out_time, we_idle in [parse_one_whoent(x) for x in whoent_chunks]: print "\tout_line:", make_string(out_line) print "\tout_name:", make_string(out_name) print "\tout_time:", make_time(out_time) print "\twe_idle:", we_idle # od # end parse_one_file From xeys_00 at yahoo.com Thu Jun 30 16:53:54 2005 From: xeys_00 at yahoo.com (xeys_00 at yahoo.com) Date: 30 Jun 2005 13:53:54 -0700 Subject: Python for everything? Message-ID: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> I posted a article earlier pertaining programming for my boss. Now I am gonna ask a question about programming for myself. I just finished my first C++ Class. Next semester is a class on encryption(and it's probably gonna be a math class too). And finally back in programming in the fall with C++ and Java 1. The C++ will cover pointers, and linked lists, sorting algorithms, etc... I run linux and OS X. I have read in the old days that C was used for everything. It was a systems programming language, and also did a lot of the same stuff Bash scripts and perl do now. So, in that era, C did it all, from short to tall. My question is, can Python "do it all"? I am wondering what to learn as my scripting language. I have read that perl is good up to about 250 lines, and after that it gets kind of hairy. However, from what little I have heard about Python, it's very well suited for readability due to the whitespace requirements of the language, and very good for large projects due to it's large amount of modules and it's object oriented structure. I would like opinions as to the suitability of Python as a general purpose language for programming unix, everything from short scripts to muds. Thanks for your patience, opinions, and comments. Xeys From exarkun at divmod.com Fri Jun 10 10:52:29 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 10 Jun 2005 10:52:29 -0400 Subject: IMAP Proxy In-Reply-To: <42A99B1C.7020507@nuxeo.com> Message-ID: <20050610145229.5047.1191920149.divmod.quotient.441@ohm> On Fri, 10 Jun 2005 15:52:28 +0200, Tarek Ziad? wrote: >Hi, > >I want to write a small TCP Server in Python to make an IMAP Proxy for >post-processing client requests. > >It is not long either complicated but needs to be very robust so... >maybe someone here has already done such a thing I can use or know where >i can get it ? I recommend using Twisted's IMAP4 support for this. There's a simple proxy in the Twisted issue tracker that might be useful to start from: http://twistedmatrix.com/bugs/issue215 Jp From tjreedy at udel.edu Wed Jun 1 14:36:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 14:36:31 -0400 Subject: Unhappy with numarray docs References: <429dc954$1@nntp0.pdx.net> <1dlr911ln6omm7nov1amaqtbikdvp51p7n@4ax.com> Message-ID: "Matt Feinstein" wrote in message news:1dlr911ln6omm7nov1amaqtbikdvp51p7n at 4ax.com... > On Wed, 01 Jun 2005 08:11:36 -0700, Scott David Daniels > wrote: > >>Propose some fixes to the documents that will make this easier for >>the next one in line. You don't even need to get it exactly right; >>the person after you can fix the mistakes you make. This is the >>process we use for this. See this as an opportunity to contribute, >>not simply a frustration about how much you overpaid for the product. > > Which is why I was specific about what I didn't like about the > documentation and why I didn't like it. Seriously, what more should I > do? If your suggestion is 'small', you can write a suggested sentence or two and post in on the appropriate forum. Something like 'In section xx.y, 2nd para, I wish there had been a sentence saying something like 'connect the frog to the jib and the jib to the boom'. With something like that to go on, an expert can verify and possibly insert/replace. I have done this for the Python docs. > It's plainly inappropriate for me to write documentation for a > module that I'm still struggling to learn. You know better than any expert where you got lost and what you wish had been said ;-) Terry J. Reedy From jepler at unpythonic.net Mon Jun 6 08:02:16 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 6 Jun 2005 07:02:16 -0500 Subject: Socket Speed In-Reply-To: References: <1117979261.996245.143810@g14g2000cwa.googlegroups.com> <20050605135944.GA18270@unpythonic.net> Message-ID: <20050606120213.GA2165@unpythonic.net> The machines with the 100mbps ethernet link are slightly different---Pentium 4, 2.8GHz, Python 2.2, RedHat 9. File size: 87490278 Best of 4 runs: 7.50 MB/s reported by "wget". There was other network activity and system load at the time. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rkern at ucsd.edu Sun Jun 26 07:11:18 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 26 Jun 2005 04:11:18 -0700 Subject: Favorite non-python language trick? In-Reply-To: <200506260559.18488.hancock@anansispaceworks.com> References: <87r7eptn9w.fsf@wilson.rwth-aachen.de> <200506260559.18488.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote: > >>Hall?chen! >>However, then you must forbid a=b=1 for assigning to two variables >>at the same time. > > Why? It's already handled as an exception in the syntax. > > In C, what you say makes sense, because "b=1" is an expression as > well as an assignment. But I don't think Python reads it that way -- it > just has code to recognize multiple assignment as a statement. I think > I remember reading that in the Language Reference or something. You need to differentiate a = b = 1 from a = b == 1 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dalke at dalkescientific.com Tue Jun 14 00:18:06 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 14 Jun 2005 04:18:06 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: Andrea Griffini wrote: > This is investigating. Programming is more similar to building > instead (with a very few exceptions). CS is not like physics or > chemistry or biology where you're given a result (the world) > and you're looking for the unknown laws. In programming *we* > are building the world. This is a huge fundamental difference! Philosophically I disagree. Biology and physics depends on models of how the world works. The success of a model depends on how well it describes and predicts what's observed. Programming too has its model of how things work; you've mentioned algorithmic complexity and there are models of how humans interact with computers. The success depends in part on how well it fits with those models. In biology there's an extremely well developed body of evidence to show the general validity of evolution. That doesn't mean that a biological theory of predator-prey cycles must be based in an evolutionary model. Physics too has its share of useful models which aren't based on QCD or gravity; weather modeling is one and the general term is "phenomenology." In programming you're often given a result ("an inventory management system") and you're looking for a solution which combines models of how people, computers, and the given domain work. Science also has its purely observational domains. A biologist friend of mine talked about one of his conferences where the conversations range from the highly theoretical to the "look at this sucker we caught!" My feeling is that most scientists do not develop new fundamental theories. They instead explore and explain things within existing theory. I think programming is similar. Both fields may build new worlds, but success is measured by its impact in this world. Andrew dalke at dalkescientific.com From Scott.Daniels at Acm.Org Thu Jun 23 14:21:10 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 23 Jun 2005 11:21:10 -0700 Subject: Reraise exception with modified stack In-Reply-To: References: <20zue.74584$Kk4.909739@news20.bellglobal.com> <42badec0$1@nntp0.pdx.net> Message-ID: <42baf628$1@nntp0.pdx.net> Nicolas Fleury wrote: > Scott David Daniels wrote: > >> How about dropping reraise and changing: >> reraise(...) >> to: >> addinfo(...) >> raise > > > It doesn't work, or at least it doesn't do what I want. I want to keep > the same exception stack to be able to identify the original error. I > would like to avoid also writing in the caller something like > sys.exc_info()[-1]. > > Regards, > Nicolas Have you tried it? Looked to do what you described to me when I run a sample. Note that is an unadorned raise with no args. The idea is to simply modify the exception object and then use raise to carry the whole original exception along as if not intercepted. --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVETHIScyber.com.au Thu Jun 23 19:28:51 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 24 Jun 2005 09:28:51 +1000 Subject: trouble subclassing str References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> Message-ID: On Thu, 23 Jun 2005 12:25:58 -0700, Paul McGuire wrote: > But if you are subclassing str just so that you can easily print your > objects, look at implementing the __str__ instance method on your > class. Reserve inheritance for true "is-a" relationships. Often, > inheritance is misapplied when the designer really means "has-a" or > "is-implemented-using-a", and in these cases, the supposed superclass > is better referenced using a member variable, and delegating to it. Since we've just be talking about buzzwords in another thread, and the difficulty self-taught folks have in knowing what they are, I don't suppose somebody would like to give a simple, practical example of what Paul means? I'm going to take a punt here and guess. Instead of creating a sub-class of str, Paul suggests you simply create a class: class MyClass: def __init__(self, value): # value is expected to be a string self.value = self.mangle(value) def mangle(self, s): # do work on s to make sure it looks the way you want it to look return "*** " + s + " ***" def __str__(self): return self.value (only with error checking etc for production code). Then you use it like this: py> myprintablestr = MyClass("Lovely Spam!") py> print myprintablestr *** Lovely Spam!!! *** Am I close? -- Steven From ccurvey at gmail.com Mon Jun 6 20:05:55 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 6 Jun 2005 17:05:55 -0700 Subject: separate IE instances? Message-ID: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> I need to create a set of IE instances that have different sets of session cookies. I thought that using the win32com.DispatchEx function would do this, but it doesn't seem to. In other words ie1 = win32com.DispatchEx("InternetExplorer.Application") ie2 = win32com.DispatchEx("InternetExplorer.Application") gives me two IE windows, but only one IEXPLORE process in Task Manager. And if I login to a site that uses session cookies to track sessions using ie1, when I move ie2 to the same site, ie2 is already logged in. Any help appreciated. -Chris From qwweeeit at yahoo.it Sun Jun 26 06:28:48 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 26 Jun 2005 03:28:48 -0700 Subject: noob question In-Reply-To: References: Message-ID: <1119781728.934326.99600@g14g2000cwa.googlegroups.com> Hi Matt, I also am almost a newbie (in Python) and my approach to variable naming follows more or less the Hungarian Type Notation Defined. To better explain, I use one char or two (in small case) as a prefix of the name of the variable (starting in capital letters). The prefix identifies the "type" of variable. My choice of such prefixes is (a short example): s string (sStringVariable) l list (lFileLines) n numeric (nNumericVariable) and so on... Bye. From felciano at gmail.com Thu Jun 30 22:22:25 2005 From: felciano at gmail.com (felciano at gmail.com) Date: 30 Jun 2005 19:22:25 -0700 Subject: Escaping commas within parens in CSV parsing? Message-ID: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> Hi -- I am trying to use the csv module to parse a column of values containing comma-delimited values with unusual escaping: AAA, BBB, CCC (some text, right here), DDD I want this to come back as: ["AAA", "BBB", "CCC (some text, right here)", "DDD"] I think this is probably non-standard escaping, as I can't figure out how to structure a csv dialect to handle it correctly. I can probably hack this with regular expressions but I thought I'd check to see if anyone had any quick suggestions for how to do this elegantly first. Thanks! Ramon From tjreedy at udel.edu Thu Jun 23 18:26:48 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 23 Jun 2005 18:26:48 -0400 Subject: Help me to log-in References: <42BB156F.3060305@gmail.com> Message-ID: "Apple Grew" wrote in message news:42BB156F.3060305 at gmail.com... > Well can anyone tell me how do I login into newsgroup using Mozilla > 1.7.7. What should be the username? (I tried with with my e-mail address > I subscribed with but failed to log-in). The password asked during > log-in is the one I subscribed with? You don't log into newsgroups. You do log into newsservers when they require you to do so. If and when you do so, you use the userid and password given to you or possibly selected by you. The userid is typically not your email address. You usually also have to 'register' the account with your newsreader, telling it whether login is required and if so, the id and passwd. It then does the login for you. The server news.gmane.org turns several technical mailing lists into newsgroups. For instance, the python mail list becomes gmane.comp.python.general. It does not require login, so it would be an easy one to start with. You may notice that I am posting thru gmane. Terry J. Reedy From riccardo_cut1 at cut2_sideralis.net Wed Jun 15 05:57:15 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Wed, 15 Jun 2005 11:57:15 +0200 Subject: __new__ and dynamic inheriting Message-ID: Hi all. It's easier if I show an example first. Say I have class A(object): def speak(self): print 'A!' class B(object): def speak(self): print 'B!' I also have a factory function like this. def foo(kind,*args,**kwds): if kind=='a': return A(*args,**kwds) else: return B(*args,**kwds) I need foo to be a class, so that I could inherit from it and still use it as a factory, so that I can do: Foo('a').speak() Foo('b'.speak() class Final(Foo): def __init__(self,kind,*args,**kwds): super(Foo,self).__init__(kind,*args,*kwds) Can I do it? How ? If it is possible, I'm pretty sure it involves using __new__ on Foo, but I can't figure out how to make it works. Any help is appreciated. Thank you, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From bvande at po-box.mcgill.ca Sat Jun 18 03:52:28 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 18 Jun 2005 03:52:28 -0400 Subject: OO approach to decision sequence? In-Reply-To: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> Message-ID: <42B3D2BC.3050406@po-box.mcgill.ca> Chinook said unto the world upon 18/06/2005 02:17: > OO approach to decision sequence? > --------------------------------- > > In a recent thread (Cause for using objects?), Chris Smith replied with (in > part): > > >> If your table of photo data has several types of photos, and you find >> yourself saying >> >> if is_mugshot: >> #something >> elif is_freehand: >> #something >> else: >> #something >> >> then OOP will help organize your code. > > > This struck a chord because I'm trying to refactor a top-down approach to an > OO approach. The reason I am doing such is to try and get my mind wrapped > around OO design, not because the particular module will benefit from an OO > approach (it's a simple top-down recursive tree utility). In fact it's > probably ill suited for OO and that is why I chose it. > > I've used an OO approach where I built up record (instance) content in a > variable record file, but here I'm trying to come at it from the opposite > direction as variable record mapping (deconstructing) would be to such. > > Anyway, a tree node can be any of seven types where: > > if node_type_1: > # recurse > elif node_type_2: > # terminus - do something > elif node_type_3: > # terminus - do something else > ... > else: > # terminus - catch all, do yet something else > return #to parent > > So, where is the magic :~) Seriously, how might OO help me organize this > type of problem (alleviate the conventional lengthy if structure)? I've > looked at the cookbook, class interface techniques, factory functions and > metaclasses till my head is swimming. Am I missing a bolt in the machinery > somewhere, or simply trying to find magic that doesn't exist for a > straightforward decision sequence? > > Thank you, > Lee C Hi Lee, I'm a hobbyist who came to grok the OO approach in the last 6 months or so ago. So, take the comments with that in mind. A simple toy example with the "if type" test approach: >>> class A(object): ... pass ... >>> class B(object): ... pass ... >>> a = A() >>> b = B() >>> for item in (a, b): ... if type(item) == A: ... ident = "an A" ... if type(item) == B: ... ident = "a B" ... print "Found %s" %ident ... Found an A Found a B >>> Now, the same sort of behaviour where the "if type" testing has been replaced with code more in keeping with the OOP approach: >>> class C(object): ... def report(self): ... print "Found a C" ... >>> class D(object): ... def report(self): ... print "Found a D" ... >>> c = C() >>> d = D() >>> for item in (c, d): ... item.report() ... Found a C Found a D >>> A metaphorical explanation that is a bit handwavy, but that I find useful: In both approaches, there is a common behaviour you want the various types of objects to exhibit. (In a less 'toy' example the behaviour would be more complicated.) In the "if type" style, you are asking each object what kind of object it is, and then setting an aspect of the behaviour as a function of the answer. In the more OOP approach, you rely on the fact that each object knows what kind of object it is. So, you don't need to ask it, and adjust the behaviour accordingly. You just tell it to behave, and, knowing what kind of thing it is, it knows how to behave as befits that kind of thing. Two big benefits in the context are that if you need to exhibit the same behaviour in multiple places, you don't have multiple "if type" chains, and, if you want to add a type, with its own specific behaviour, you just add a class, and there is no worry about hunting down the "if type" chains to update them. There was a thread on the tutor list around mid-Feb. which really helped me come to understand the idea. Actually, from Dec. to Feb. or so, there are several long tutor threads where people gave me much useful help coming to see how to employ OOP. Might be worth a trip through the archive. HTH, Brian vdB From cam.ac.uk at mh391.invalid Wed Jun 22 13:24:58 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 22 Jun 2005 18:24:58 +0100 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: <42b99d7b$0$21804$626a14ce@news.free.fr> References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: scott wrote: > can someone tell me, how to use a class like that* (or "simulate" more > than 1 constructor) : > #-- > class myPointClass: > def __init__(self, x=0, y=0): > self.x = x > self.y = y > def __init__(self, x=0, y=0, z=0): > self.__init__(self, x, y) > self.z = z > #-- Well for the example you used, multiple constructors are not needed. This will get you the same result as what I imagine you wanted the first example to do: class myPointClass: def __init__(self, x=0, y=0, z=0): self.x = x self.y = y self.z = z -- Michael Hoffman From jepler at unpythonic.net Fri Jun 24 11:47:48 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 24 Jun 2005 10:47:48 -0500 Subject: Frame widget (title and geometry) In-Reply-To: <785a1e003cabc.42bbde8d@Princeton.EDU> References: <785a1e003cabc.42bbde8d@Princeton.EDU> Message-ID: <20050624154744.GA30048@unpythonic.net> It would help if you posted your code, as we're in the dark about exactly what you tried to do and the error you received. It sounds like you may be using the wrong type of widget for what you want. The terms used in Tk are different than in some other systems. If you want a separate window with title bar etc, you want to create a new instance of Tkinter.Toplevel. It will have methods like wm_title and wm_geometry. Newer versions of Tk (8.4 and maybe 8.3) have a widget called "labelframe" (called Tkinter.LabelFrame in python2.3 and newer) which is the grooved-border-and-label container used to semantically group related widgets. "Frame" widgets are simply containers which are often useful for making the screen layout work the way you want with pack and grid. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From xah at xahlee.org Tue Jun 21 02:30:40 2005 From: xah at xahlee.org (Xah Lee) Date: 20 Jun 2005 23:30:40 -0700 Subject: references/addrresses in imperative languages In-Reply-To: <89jeb1ddsjsaq0l07j0vonehqlah3cq9ce@4ax.com> References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> <89jeb1ddsjsaq0l07j0vonehqlah3cq9ce@4ax.com> Message-ID: <1119335440.863575.24360@g14g2000cwa.googlegroups.com> Dear Andrea Griffini, Thanks for explaning this tricky underneath stuff. Xah xah at xahlee.org ? http://xahlee.org/ Andrea Griffini wrote: > On Sun, 19 Jun 2005 22:25:13 -0500, Terry Hancock > wrote: > > >> PS is there any difference between > >> t=t+[li] > >> t.append(li) > > > >No, but > > Yes, a big one. In the first you're creating a new list > and binding the name t to it, in the second you're extending > a list by adding one more element at the end. > To see the difference: > > >>> a = [1,2,3] > >>> b = a > >>> a = a + [4] > >>> print a > [1, 2, 3, 4] > >>> print b > [1, 2, 3] > >>> > >>> a = [1,2,3] > >>> b = a > >>> a.append(4) > >>> print a > [1, 2, 3, 4] > >>> print b > [1, 2, 3, 4] > >>> > > Andrea From merkosh at hadiko.de Fri Jun 24 03:25:38 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 24 Jun 2005 09:25:38 +0200 Subject: Favorite non-python language trick? References: Message-ID: Friday 24 June 2005 09:18 am Enrico wrote: [...] >> --This code will, because the first two dashes make the rest a comment, >> breaking the block >> ---[[ >> print(10) >> --]] [...] > python: > > """ > print 10 > """ > > and > > #""" > print 10 > #""" > > C++: > > /* > print(10); > */ > > and > > ///* > print(10); > //*/ > > ? I think the *trick* here was that if you had larger blocks you'd only have to change one side of the comment, i.e. the opening line, to de-comment the block without searching the end of it and commenting that out aswell. Ciao Uwe From rkern at ucsd.edu Wed Jun 29 18:22:17 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 29 Jun 2005 15:22:17 -0700 Subject: Graphs/statistics using wxPython In-Reply-To: <42c3021f$1@griseus.its.uu.se> References: <42c2df8b$1@griseus.its.uu.se> <42c2e859$1@griseus.its.uu.se> <42c2f21a$1@griseus.its.uu.se> <42c3021f$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > So, for future reference: I should *never* mix x and y versions in > verion: x.y.z. I've wondered why there are versions of libraries for > different versions of Python.. For packages with extension modules at least. Python maintains binary compatibility between micro-releases (i.e. different z). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mrmaple at gmail.com Mon Jun 13 16:15:30 2005 From: mrmaple at gmail.com (James Carroll) Date: Mon, 13 Jun 2005 16:15:30 -0400 Subject: Tiff Image Reader/writer In-Reply-To: <1118692248.242717.63770@g49g2000cwa.googlegroups.com> References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> Message-ID: What sort of things do you want to do with the TIFFs? How heavy-weight or light-weight are you interested in? For heavy-weight there are: - wxPython will do a bunch of tiff reading, and some image processing http://www.wxpython.org - GDAL >(quoting Khalid Zuberi:) >GDAL supports GeoTIFF and includes python bindings: > > http://www.remotesensing.org/gdal/ - ITK Insight Toolkit from Kitware (wicked heavy-weight) http://www.itk.org -Jim On 13 Jun 2005 12:50:48 -0700, PyPK wrote: > Is there any package out there which handles Tiff Images other than PIL > or ImageMagic . > > -- > http://mail.python.org/mailman/listinfo/python-list > > From __peter__ at web.de Mon Jun 27 12:57:32 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Jun 2005 18:57:32 +0200 Subject: tkinter radiobutton References: Message-ID: William Gill wrote: > I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep > references to them in a 2 dimensional list ( rBtns[r][c] ). It works > fine, and I can even make it so only one button per column can be > selected, by assigning each column to an intVar. In many languages a > radiobutton has a property that can be directly read to see if it is > selected on unselected. Tkinter radiobuttons don't seem to have any > such property. Is there any way to look (via the script not the screen) > to determine if it is selected?, or can this only be achieved via > control variables? You can either write a little helper function def selected(rbn): return rbn.getvar(rbn["variable"]) == rbn["value"] or use a custom subclass of Tkinter.Radiobutton with a 'selected' attribute: class Radiobutton(Tkinter.Radiobutton): def __getattr__(self, name): if name == "selected": return self.getvar(self["variable"]) == self["value"] raise AttributeError Peter From ggg at zzz.it Sat Jun 11 12:25:07 2005 From: ggg at zzz.it (deelan) Date: Sat, 11 Jun 2005 18:25:07 +0200 Subject: case/switch statement? In-Reply-To: References: Message-ID: Joe Stevenson wrote: > Hi all, > > I skimmed through the docs for Python, and I did not find anything like > a case or switch statement. I assume there is one and that I just > missed it. strictly speaking, python does not have a switch stamenent. "Why isn't there a switch or case statement in Python?" > Can someone please point me to the appropriate document, or > post an example? I don't relish the idea especially long if-else > statements. topic already beated to death, feel free to browse the group archives: HTH. -- deelan From kraus at hagen-partner.de Wed Jun 1 02:46:45 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Wed, 01 Jun 2005 08:46:45 +0200 Subject: What's wrong with Zope 3 ? In-Reply-To: <1117581035.584193.310060@g47g2000cwa.googlegroups.com> References: <1117581035.584193.310060@g47g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > The last downloadable release is from november 2004. The Windows > installer is configured for Python 2.3(!). The Zope.org main page > announces Zope 2.8 beta 2. Is it stillborn? > > Kay > What you see is not Zope 3, it is Zope X 3. To quote from the X3 information page: "Zope X3 3.0 is for developers. If you are expecting an end-user application, this is not for you." The current stable brance is Zope2.X If you want to incorporate some functionalty from X3 in Zope 2.X, do a search for "Five" HTH, Wolfram From applegrew at gmail.com Mon Jun 27 15:07:25 2005 From: applegrew at gmail.com (Apple Grew) Date: Tue, 28 Jun 2005 00:37:25 +0530 Subject: Boss wants me to program In-Reply-To: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: <42C04E6D.8040505@gmail.com> I think since speed is not such an issue (I heard that python can make faster GUI programs) you should use Visual Basic. It is very well suited for Windows programming. There is the good thing that you can visually create the GUI hence it is easier to create the GUI. xeys_00 at yahoo.com wrote: >I'm a manager where I work(one of the cogs in a food service company). >The boss needed one of us to become the "tech guy", and part of that is >writing small windows programs for the office. He wants the development >work done in house, and he knows I am in school for a CS minor. I know >basic C++(Part 2 of that is in the fall), and I will be taking Java 1 >in the fall also. What is the easiest way for me to make windows >programs that will do basic things like(Inventory, Menu Management, >etc...)? I have heard visual basic is where it's at. I want to keep an >open mind though, so I am wondering if python could be an option. The >programs have >no speed requirement. But they must be pretty, and not confuse my >boss. Plus he wants well documented help for each function. I asked the >windows programming group, but I thought I would ask here also. Thanks. > >Xeys > > > From peter at engcorp.com Thu Jun 9 21:56:37 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 21:56:37 -0400 Subject: Interpreter-like help in cmd.Cmd In-Reply-To: References: <2MCdnf5cFKCCLjXfRVn-pw@powergate.ca> Message-ID: Sarir Khamsi wrote: > Peter Hansen writes: > >>class _Helper(object): ... >> def __call__(self, *args, **kwds): >> import pydoc >> return pydoc.help(*args, **kwds) > > Thanks, but how do I integrate this with cmd.Cmd? I can't say exactly. That might depend on what you are doing with it, and how you are currently handling other things with it. All I know is that the builtin "help" just passes its arguments to pydoc.help() and that seems to do the job. I'd suggest you work from there and experiment with your current cmd.Cmd mechanisms to see what you can get working, then post a snippet or to back here for further assistance. Almost working code is almost always better than starting with nothing. (I would help if I remembered anything about cmd.Cmd, really, but it's been years.) -Peter From fredrik at pythonware.com Thu Jun 2 04:33:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 2 Jun 2005 10:33:25 +0200 Subject: viewing generated images References: Message-ID: Tim Flynn wrote: > def createWidgets(self): > self.image_size = (50,50) > self.pilim = Image.new( "1", self.image_size ) > > # Generate a blank image > f = lambda(x): 0 > Image.eval( self.pilim, f ) I'm not sure what you think that line is doing, but it probably doesn't do what you think it does. try changing the Image.new call to self.pilim = Image.new( "1", self.image_size, 0 ) instead. > self.bmi = ImageTk.BitmapImage( image = self.pilim, > foreground = 'black' ) > self.canvas = Canvas( width=100, > height = 100, > bg = 'white' ) > self.quitButton = Button( self, > text="Quit", > command=self.quit ) > self.quitButton.grid() > self.canvas.grid() > im_id = self.canvas.create_bitmap( 0, > 0, > anchor = 'nw', > bitmap = self.bmi ) it's a terminology confusion: for historical reasons, Tkinter distinguishes between bitmaps and images (this separation comes from the X window system). Bitmap- Image creates an image. changing to create_image should fix the problem. (if you're doing an image viewer, you may want to use PhotoImage instead of BitmapImage, btw). From skip at pobox.com Wed Jun 1 08:16:44 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Jun 2005 07:16:44 -0500 Subject: Another source of time for the logging package? Message-ID: <17053.42796.237107.623410@montanaro.dyndns.org> I have code I run in both live and historical modes. When running in historical mode the input stream is a set of stored event sequences that have their own timestamps. When picking through the logfiles for a particular run, I'd much prefer it if the timestamps in the logfile generated with the logging package corresponded to the timestamps on the stored events, not to wall clock time. Looking at the code for the logging package it's far from obvious that this is possible without some surgery. Before I get out my scalpel, has anyone found a non-invasive way to do this (or already done the surgery and would be willing to share it)? Thanks, Skip From d at e.f Fri Jun 24 13:54:34 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 12:54:34 -0500 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: Riccardo Galli wrote: > On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote: > > >>>Bo Peng wrote: >>> >>> >>>>I need to pass a bunch of parameters conditionally. In C/C++, I can >>>>do func(cond1?a:b,cond2?c:d,.....) >>>> >>>>Is there an easier way to do this in Python? >>> >>> >>The answer is simply no, just use an if statement instead. > > > That's not true. > One used form is this: > result = cond and value1 or value2 So anywhere someone uses x?y:z you recommend they use "x and y or z" instead, or else "[y,z][x]", but not: if x: val = y else: val = z I still would recommend just using an if statement, even though it is not easier to type than a ternary expression. It is the most readable and understandable equivalent in Python. And since his question was about an easier way to do it in Python, and I don't believe your alternative are any easier either, I believe the answer is still no. From mauriceling at acm.org Fri Jun 3 00:40:15 2005 From: mauriceling at acm.org (Maurice LING) Date: Fri, 03 Jun 2005 14:40:15 +1000 Subject: provide 3rd party lib or not... philosophical check Message-ID: Hi, Just a philosophical check here. When a program is distributed, is it more appropriate to provide as much of the required 3rd party libraries, like SOAPpy, PLY etc etc, in the distribution itself or it is the installer's onus to get that part done? Cheers Maurice From http Wed Jun 22 16:26:51 2005 From: http (Paul Rubin) Date: 22 Jun 2005 13:26:51 -0700 Subject: Avoiding deadlocks in concurrent programming References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> Message-ID: <7xhdfqgmsz.fsf@ruckus.brouhaha.com> "Eloff" writes: > I have a shared series of objects in memory that may be > 100MB. Often > to perform a task for a client several of these objects must be used. Do you mean a few records of 20+ MB each, or millions of records of a few dozen bytes, or what? > However imagine what would happen if there's 100 clients in 100 > threads waiting for access to that lock. One could be almost finished > with it, and then 100 threads could get switched in and out, all doing > nothing since they're all waiting for the lock held by the one thread. If the 100 threads are blocked waiting for the lock, they shouldn't get awakened until the lock is released. So this approach is reasonable if you can minimize the lock time for each transaction. > No doubt this is a common problem, how would you people deal with it? You're doing what every serious database implementation needs to do, and whole books have been written about approaches. One approach is to use a transaction and rollback system like a database does. A lot depends on the particulars of what you're doing. Are you sure you don't want to just use an RDBMS? From drjonfox at gmail.com Wed Jun 15 13:54:26 2005 From: drjonfox at gmail.com (drjonfox at gmail.com) Date: 15 Jun 2005 10:54:26 -0700 Subject: PIGIP (Python Interest Group In Princeton) Meeting Tonight Message-ID: <1118858066.340307.122280@g47g2000cwa.googlegroups.com> Meeting Tonight! Python Interest Group In Princeton (PIGIP -- http://www.pigip.org) PIGIP will hold its sixth meeting on Wednesday June 15, 2005 at the Lawrenceville Library. We don't have a formal topic, but Jon will show off using Archetypes in Plone for easy content management. Bring your favorite Python module and share... or bring a Python puzzle of problem. More information about the library is at http://www.mcl.org/branches/lawrbr.html. Bonus: The library has free WiFi access available for use during our meetings. Future Meetings Jon's wife will be having a baby in August so unless a groundswell of popular demand occurs, PIGIP will take a summer vacation. No meetings in July or August 2005. Call For Speakers Anyone interested in presenting a short, informal, Python-related talk should post to the forums or email Jon Fox (mailto:jonfox at drfox.com) About PIGIP PIGIP is a forum for open discussion about the Python computer language and source of exchange for people at different levels of learning about Python. Meetings are monthly (generally on the third Wednesday) and are open to the public. From p at ulmcnett.com Thu Jun 9 12:07:47 2005 From: p at ulmcnett.com (Paul McNett) Date: Thu, 09 Jun 2005 09:07:47 -0700 Subject: Start application & continue after app exits In-Reply-To: References: Message-ID: <42A86953.9070201@ulmcnett.com> Guy Lateur wrote: > I was wondering if it would be possible to launch an application, block > until the app exits, and do some cleanup afterwards. > Maybe an example will be clearer: I would like to make a temperary (text) > file, open it with MS Word for the user to edit/layout/print, and then > delete the temp file after the user shuts down Word. Is this feasible? Something like: import os import tempfile testString = "Life is but a dream." fileName = tempfile.mktemp() print fileName open(fileName, "w").write(testString) os.system("gedit %s" % fileName) os.remove(fileName) --- Note that I'm on Linux, and instead of launching Word I'm launching an editor named "gedit". You could likely change that call to winword.exe, but I haven't tested it on Windows. Also note that this method of creating tempfiles is technically unsafe, as it is theoretically possible that another process would create a file of the same name in the same directory and then try to use it, resulting in a race condition between the two processes. This is practically unlikely, however, and I'm a pragmatist. -- Paul McNett http://paulmcnett.com From fraca7 at free.fr Thu Jun 16 11:02:15 2005 From: fraca7 at free.fr (fraca7) Date: Thu, 16 Jun 2005 17:02:15 +0200 Subject: Multithreaded Python FSM (Harel State Machines) In-Reply-To: References: Message-ID: <42b19477$0$19556$626a14ce@news.free.fr> Leonard J. Reder a ?crit : > [snip] http://smc.sourceforge.net/ It's probably not what you're looking for, but it's the closest I can think of. From __peter__ at web.de Tue Jun 28 12:17:53 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 28 Jun 2005 18:17:53 +0200 Subject: tkinter radiobutton References: Message-ID: William Gill wrote: > The radiobutton widget knows if it is selected or unselected, or it > wouldn't be able to display correctly, but based on what I'm seeing, > that information is inaccessable to the app.??Instead?the?app?must > evaluate an associated control variable.??That?doesn't?make?sence?to?me, > but even trying to look at the code for the radiobutton class didn't help. I guessed you wanted to solve a practical problem, but the thoughts expressed above suggest, err, philosophical qualms. So, for the sake of the argument and since we both don't know the implementation details, be it in C or TCL, let's assume that the individual radiobuttons do *not* /know/ whether they are selected or not but instead compare their associated 'variable' with their 'value' every time they are /asked/ to draw themselves. That would avoid duplicate state and require only log N instead of N bits. Wouldn't that be an elegant implementation, at least in theory? So why bother about the layers below when you have all the information to write code that works? Peter From hongqn at gmail.com Mon Jun 13 11:34:34 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Mon, 13 Jun 2005 23:34:34 +0800 Subject: Show current ip on Linux In-Reply-To: References: Message-ID: <42ADA78A.8030609@gmail.com> David Van Mosselbeen wrote: > Hi, > Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine > man :-) > > My question is : How can i rwite a script that show my current ip. If i have > more than one network card, the script must then show all used ip. > > It's important that this will work on a linux. i Have rwite some piece of > code that realy work under Windows XP, but the same script wil not work on > Linux. > > Verry thanks to all vulunteers. > How about use the shell command "ifconfig | grep inet" ? -- Qiangning Hong _____________________________________________________________ ( so when I do a chroot /path /bin/bash, i can ) ( see the processes ) ( ) ( outside of the chroot and i can kill those processes ) ( * klieber claps for zhen oh go die ) ------------------------------------------------------------- o \_______ v__v o \ O ) (OO) ||----w | (__) || || \/\ From __peter__ at web.de Tue Jun 7 12:47:00 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 07 Jun 2005 18:47:00 +0200 Subject: time consuming loops over lists References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> Message-ID: querypk at gmail.com wrote: > Can some one help me improve this block of code...this jus converts the > list of data into tokens based on the range it falls into...but it > takes a long time.Can someone tell me what can i change to improve > it... > > def Tkz(tk,data): > no_of_bins = 10 > tkns = [] > dmax = max(data)+1 > dmin = min(data) > rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0))) > rngs = zeros(no_of_bins+1) > for i in xrange(no_of_bins+1): > rngs[i] = dmin + (rng*i) > for i in xrange(len(data)): > for j in xrange(len(rngs)-1): > if data[i] in xrange(rngs[j],rngs[j+1]): > tkns.append( str(tk)+str(j) ) > return tkns Use bisect(), e. g., with a slightly modified function signature: from __future__ import division import bisect from math import ceil def tkz(tk, data, no_of_bins=10): dmax = max(data) + 1 dmin = min(data) rng = ceil((dmax - dmin)/no_of_bins) rngs = [dmin + rng*i for i in xrange(1, no_of_bins+1)] tokens = [tk + str(i) for i in xrange(no_of_bins)] return [tokens[bisect.bisect(rngs, v)] for v in data] if __name__ == "__main__": print tkz("token_", [5, 7, 8, 9, 70, 200]) What are the tokens for, by the way? I'd recommend using the indices directly if possible. Peter From ccurvey at gmail.com Sun Jun 12 20:08:42 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 12 Jun 2005 17:08:42 -0700 Subject: How to use 8bit character sets? In-Reply-To: References: Message-ID: <1118621322.233577.107800@g14g2000cwa.googlegroups.com> Check out sitecustomize.py. http://diveintopython.org/xml_processing/unicode.html From exarkun at divmod.com Sat Jun 25 09:56:51 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 25 Jun 2005 09:56:51 -0400 Subject: a dictionary from a list In-Reply-To: Message-ID: <20050625135651.26278.2010126799.divmod.quotient.368@ohm> On Sat, 25 Jun 2005 09:10:33 -0400, Roy Smith wrote: >Terry Hancock wrote: >> Before the dict constructor, you needed to do this: >> >> d={} >> for key in alist: >> d[key]=None > >I just re-read the documentation on the dict() constructor. Why does it >support keyword arguments? > > dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"} > >This smacks of creeping featurism. Is this actually useful in real code? Constantly. Jp From agriff at tin.it Sat Jun 18 11:02:37 2005 From: agriff at tin.it (Andrea Griffini) Date: Sat, 18 Jun 2005 15:02:37 GMT Subject: Loop until condition is true References: <1119074614.700809@yasure> <11b88ok1tr67475@corp.supernews.com> Message-ID: On Sat, 18 Jun 2005 13:35:16 -0000, Grant Edwards wrote: >AFAICT, the main use for do/while in C is when you want to >define a block of code with local variables as a macro: When my job was squeezing most out of the CPU (videogame industry) I remember that the asm code generated by while (sz-- > 0) { /* do some stuff */ } was indeed worse than do { /* do some stuff */ } while (--sz); because of the initial "empty-loop" test (conditional jumps were bad, and forward conditional jumps were worse). So where at least one iteration was guaranteed the do-while loop was a better choice. Also I've been told there were compilers that if using for or while loops the generated code was L1: je L2 jmp L1 L2: Instead the do-while loop would have been L1: jne L1 I.e. the code was better *for each iteration* (one conditional jump instead of one conditional jump and one inconditional jump). I think compiler got better since then, even if I don't think they already so smart to be able to infer the "one interation guaranteed" property to avoid the initial test that often. Andrea From hancock at anansispaceworks.com Sat Jun 25 03:35:50 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 25 Jun 2005 02:35:50 -0500 Subject: A tool for Python - request for some advice In-Reply-To: <1119603875.247425.158910@g47g2000cwa.googlegroups.com> References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> <5jvf464maf.fsf@idiom.com> <1119603875.247425.158910@g47g2000cwa.googlegroups.com> Message-ID: <200506250235.50360.hancock@anansispaceworks.com> On Friday 24 June 2005 04:04 am, TPJ wrote: > > If your target platform is Linux, indications are that python is as > > portable as bash. > > I've thought about it for a few days and I disagree with you. Python > isn't as portable as bash because of one reason. The problem is that > development of Python is much more dynamic than development of bash. If > I wrote my script in Python it would be possible that this script > wouldn't run on the same distro with _different_ version of Python. > > (This is problem because someone has sugested that he'd like to run > this script on RH 9. So older distros must be considered as well as > newer.) If you write your scripts to work with Python 2.1, they will work on practically any Linux distribution that is still in wide use on desktops and servers. You might get into trouble on embedded systems or "rescue disk" Linuxes (i.e. you might have to go back to 1.5). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From roy at panix.com Thu Jun 30 08:48:19 2005 From: roy at panix.com (Roy Smith) Date: Thu, 30 Jun 2005 08:48:19 -0400 Subject: Add methods to string objects. References: <2fdabf19.0506300201.5fb56b59@posting.google.com> <1120134661.407265.251710@z14g2000cwz.googlegroups.com> Message-ID: In article <1120134661.407265.251710 at z14g2000cwz.googlegroups.com>, "simon.dahlbacka at gmail.com" wrote: > You can even get closer, but it is NOT recommended > > class foostr(str): > def plural (self): > if self.value[-1] in "sz": > return self.value + "es" > else: > return self.value + "s" > > > #ugly hack > setattr(__builtins__, "str", foostr) > > print str("apple").plural() > > # this however does not work > # print "apple".plural() It's fascinating that the setattr() works (and I agree with you that it's a bad idea), but given that it does work, why doesn't it work with a string literal? From fredrik at pythonware.com Tue Jun 28 10:17:56 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Jun 2005 16:17:56 +0200 Subject: Non-blocking raw_input References: Message-ID: Jorge Louis de Castro wrote: > I have indeed tried the msvcrt module but none of the examples given works > as described on a XP+SP2 box. what examples? how did you run the examples? (the keyboard interface functions in msvcrt only work if the program's attached to a Windows console. if you run the program under an IDE, that may not be true). From duncan.booth at invalid.invalid Wed Jun 22 04:41:03 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jun 2005 08:41:03 GMT Subject: tree functions daily exercise: Table References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119357221.467207.149480@f14g2000cwb.googlegroups.com> <1119389873.409227.225680@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > oops, another error. The example should be: > > Table(f,[1,2,1],[2,6,2]) returns > [[f(1,2),f(1,4),f(1,6)],[f(2,2),f(2,4),f(2,6)]] > >> Wouldn't it be more sensible just to take the iterators directly as >> arguments, so for this example you would do: >> >> Table(f, range(1,3), range(2,7,2)) > > well yes... but this was emulation of Mathematica functions. > (Disclaimer: Mathematica is a trademark of Wolfram Research Inc, who is > not affliated with this project) > > What you suggested is a function called Outer in Mathematica. The Table > function is in a sense multi-dimentional version of Range, so they > share syntax form. > Ok, so, if I understand you, the definition of Table is just: def Table(f, *lists): return Outer(f, *[range(start,end+1,step) for (start,end,step) in lists]) Is that about right? From skromta at gmail.com Sun Jun 12 09:02:35 2005 From: skromta at gmail.com (Kalle Anke) Date: Sun, 12 Jun 2005 15:02:35 +0200 Subject: How to get/set class attributes in Python References: <42ac0c6d$0$10102$626a14ce@news.free.fr> Message-ID: <0001HW.BED1FF0B002B4EACF0407550@news.gmane.org> On Sun, 12 Jun 2005 12:20:29 +0200, tiissa wrote (in article <42ac0c6d$0$10102$626a14ce at news.free.fr>): > You can 'hide' you getsetters using a property attribute[1]: > > [1]http://docs.python.org/lib/built-in-funcs.html Thanks, this is exactly what I was looking for From donnal at donnal.net Thu Jun 30 16:50:26 2005 From: donnal at donnal.net (Donnal Walter) Date: Thu, 30 Jun 2005 15:50:26 -0500 Subject: class attribute to instance attribute Message-ID: This is a question about Python patterns or idioms. Over a period of time, I have evolved a pattern of usage that seems to work better for me than other ways I tried previously, but in writing some documentation I don't know what to call this syntax or how best to describe it. I have not seen it used in other places. The somewhat longish version is that I have implemented an MVP (model-view-presenter) architecture where each "presenter" has a "view" as an attribute. Take the TextField and Frame presenters for example. Here is one way to do it: import wx class TextField: def __init__(self): # do some things here to calculate *args self.view = wx.TextCtrl(*args) # do more things to set up the view # and more methods to make this a presenter class Frame: def __init__(self): # do some things here to calculate *args self.view = wx.Frame(*args) # do more things to set up the view # and more methods to make this a presenter There are a number of presenters, some of which have the same type of view (TextField and NumberField, for example) and many of which have different views (Frame and Notebook, for example). The way I have chosen to do this is to put the logic in one superclass, "Presenter": class Presenter: view = None def __init__(self): # do some things here to calculate *args # if view is class, create instance if callable(self.view): self.view = self.view(*args) # do more things to set up the view # and more methods to make this a presenter class TextField(Presenter): view = wx.TextCtrl class Frame(Presenter): view = wx.Frame Then: >>> app = wx.App(False) >>> f = Frame() >>> isinstance(f.view, wx.Frame) True To summarize, each subclass has a class attribute "view" that is converted to an instance attribute of the same name at runtime. Is this a common Python idiom? If so, does it have a name? Is there a better way to do the same thing? Regards, Donnal Walter Arkansas Children's Hospital From jrastrick at student.usyd.edu.au Mon Jun 20 18:36:56 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 20 Jun 2005 15:36:56 -0700 Subject: references/addrresses in imperative languages In-Reply-To: <42b739d1$0$3116$ed2619ec@ptn-nntp-reader01.plus.net> References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> <42b739d1$0$3116$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <1119307016.831624.194280@g44g2000cwa.googlegroups.com> You can add Australia to the list :) Any volunteers for a fourth continent? Antarctica, perhaps? ;) - Jordan From kveretennicov at gmail.com Mon Jun 20 21:02:44 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 03:02:44 +0200 Subject: Tuple Unpacking in raise In-Reply-To: References: Message-ID: <4660fe30050620180252640501@mail.gmail.com> On 6/21/05, Steven Bethard wrote: > James Stroud wrote: > P.S. If you insist on using the two argument version of raise, you can > do it like this: > > py> class E(Exception): > ... def __init__(self, atup): > ... Exception.__init__(self, "Error with %s-%s" % atup) > > But that seems a lot less elegant than simply using the one argument > version. Another workaround would be to use __init__(self, *atup), but raising an explicitly constructed exception is preferable (IMO). - kv From news at NOwillmcguganSPAM.com Wed Jun 22 16:54:53 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 22 Jun 2005 21:54:53 +0100 Subject: Database recommendations for Windows app In-Reply-To: <42b97240$0$24467$da0feed9@news.zen.co.uk> References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: <42b9d01e$0$2588$da0feed9@news.zen.co.uk> Thanks for the replies. I think I'm going to go with sqllite for now. For the curious, Im writing an interface to a nutritional database. So you can type in a foodstuff and it will tell you whats in it.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From dan at nospam.com Wed Jun 22 11:41:06 2005 From: dan at nospam.com (Dan) Date: Wed, 22 Jun 2005 10:41:06 -0500 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: Take a look at Firebird. It can be run in embedded mode. It might be overkill for your needs though... On 6/22/2005 10:37 AM, Gregory Pi?ero wrote: > I always figured a problem with using MySQL was distribution. Would > you have to tell your users to install MySQL and then to leave the > service running? I've never found an easy way to embed MySQL into a > python app, and even if you could, would you then have to pay for it? > > -Greg > > > On 6/22/05, Thomas Bartkus wrote: > >>"Will McGugan" wrote in message >>news:42b97240$0$24467$da0feed9 at news.zen.co.uk... >> >>>Hi, >>> >>>I'd like to write a windows app that accesses a locally stored database. >>>There are a number of tables, the largest of which has 455,905 records. >>> >>>Can anyone recommend a database that runs on Windows, is fast / >>>efficient and can be shipped without restrictions or extra downloads? >>> >>>I have googled and found plenty of information on databases, its just >>>that I dont have enough experience with databases to know which one is >>>best for my task! >> >>If you are writing strictly for the MS Windows platform >> And >>If the database is running single user with a "locally stored database" on a >>Windows workstation. >> Then >>The MS Access file based (.mdb) system is hard to argue with. >>You wouldn't have to distribute the (rather expensive) Access application >>since this is little more than a front for the underlying DAO/ADO database >>libraries that are built into the warp and woof of MS Windows. Your Python >>application can address the DAO or ADO directly as these will libraries will >>be pre-installed and/or freely available for MS Windows. Fast, freely >>available, no license restrictions, and no need for extra downloads for a >>reasonably recent (Win2000, XP) operating system. >> >>On the other hand, if operating system portability were a concern (as it >>should be!), I might suggest MySQL. >>A Python/MySQL application can jump between Windows to Linux (all flavors!) >>to Unix to BSD without need to alter a single line of code. >> >>You were writing a Python app, weren't you :-) >>Thomas Bartkus >> >> >>-- >>http://mail.python.org/mailman/listinfo/python-list >> From msoulier at digitaltorque.ca Sat Jun 18 16:05:53 2005 From: msoulier at digitaltorque.ca (Michael P. Soulier) Date: Sat, 18 Jun 2005 16:05:53 -0400 Subject: oddness in super() Message-ID: <20050618200553.GD7892@piglet.digitaltorque.ca> Ok, this works in Python on Windows, but here on Linux, with Python 2.4.1, I'm getting an error. The docs say: A typical use for calling a cooperative superclass method is: class C(B): def meth(self, arg): super(C, self).meth(arg) However, when I try this, which works on windows, with ActiveState ActivePython 2.4.0... class RemGuiFrame(RemGlade.RemFrame): """This class is the top-level frame for the application.""" def __init__(self, *args, **kwds): "Class constructor." # Constructor chaining super(RemGuiFrame, self).__init__(*args, **kwds) ...on linux I get this... [msoulier at piglet pysrc]$ ./RemGui.py Traceback (most recent call last): File "./RemGui.py", line 206, in ? frame_1 = RemGuiFrame(None, -1, "") File "./RemGui.py", line 30, in __init__ super(RemGuiFrame, self).__init__(*args, **kwds) TypeError: super() argument 1 must be type, not classobj Why the difference? Is Python portability overrated? Is this a bug? I'm confused. Mike -- Michael P. Soulier http://www.digitaltorque.ca http://opag.ca python -c 'import this' Jabber: msoulier at digitaltorque.ca -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From thaddon at equilar.com Wed Jun 8 20:37:11 2005 From: thaddon at equilar.com (Tom Haddon) Date: Wed, 8 Jun 2005 17:37:11 -0700 Subject: Decimal Places Incorrect Message-ID: <0E52D69E86D25840AAE3611CB657F9F8365D9D@millenium.equilar.com> Hi Folks, When I run: print "%0.2f" % ((16160698368/1024/1024/1024),) I get 15.00 I should be getting 15.05. Can anyone tell me why I'm not? Thanks, Tom From roccomoretti at hotpop.com Fri Jun 24 18:32:03 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 24 Jun 2005 17:32:03 -0500 Subject: a dictionary from a list In-Reply-To: <2133494.bAtaJnSUkF@teancum> References: <2133494.bAtaJnSUkF@teancum> Message-ID: David Bear wrote: > I know there must be a better way to phrase this so google understands, but > I don't know how.. So I'll ask people. > > Assume I have a list object called 'alist'. > > Is there an easy way to create a dictionary object with the members of > 'alist' being the keys in the dictionary, and the value of the keys set to > null? Are you sure you need a dictionary? You may want to look at the Set module instead, if the values aren't important. From tjreedy at udel.edu Wed Jun 22 17:55:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Jun 2005 17:55:27 -0400 Subject: Python internals and parser References: <42b9d592$0$31813$ba624c82@nntp06.dk.telia.net> Message-ID: "Michael Barkholt" wrote in message news:42b9d592$0$31813$ba624c82 at nntp06.dk.telia.net... > Is there any detailed documentation on the structure of Pythons > internals, > besides the source code itself? In detail, in one place, no. There are bits and pieces in the C API docs and the Lib man chapters on the parser and dis modules and perhaps the compiler module. Terry J. Reedy From deets at web.de Sat Jun 18 16:37:38 2005 From: deets at web.de (Diez B. Roggisch) Date: Sat, 18 Jun 2005 22:37:38 +0200 Subject: oddness in super() In-Reply-To: References: Message-ID: <3hjf0nFhc1t9U1@uni-berlin.de> Michael P. Soulier wrote: > Why the difference? Is Python portability overrated? Is this a bug? Certainly a bug - but not in python. The super-method works for new-style classes only. The attached script reproduces your observed behaviour. So kit seems that whatever toolkit you use, it uses new-style classes on windows, and old-style ones on linux. Regards, Diez -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.py URL: From phillip.watts at anvilcom.com Fri Jun 10 14:41:13 2005 From: phillip.watts at anvilcom.com (phil) Date: Fri, 10 Jun 2005 13:41:13 -0500 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <42A9DEC9.3050303@anvilcom.com> > > What experiences have those in the Python community had in these kinds > of situations? > Ive had lots of experience updating my resume and developing software at home. In Python. Java is a clumsy kludge. And the java environment has gone to hell. Managers DO NOT listen to engineers. Marketing people cannot spell indianere. Sorry, to be so pessimistic. They are gonna outsource anyway. It's such a sexy buzzword, how can they resist? How can you have an interesting management/marketing meeting in which noone knows their head from their richard, without cool buzzwords? There are lots of good projects to work on at home. Get your unemployment then a good waiter job. Seriously, its cottage industry/small business that drives this world, not the clowns you are describing. They are losers. Don't let them drag you down. If you really want to fight this on their terms, you need engineering to write a white paper which is absolute horsedooey but is loaded with stuff they cannot possible comprehend and arrives at totally unsupported conclusions that you like. Have all the engineers sign off and get some authoritative endorsement. This will introduce fear and paralysis at the mgmt level. Then get a couple happy customers and lock it in. From jrastrick at student.usyd.edu.au Mon Jun 6 12:42:04 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 6 Jun 2005 09:42:04 -0700 Subject: Lost in the inheritance tree... THANKS! In-Reply-To: References: <1118073214.264097.85130@g49g2000cwa.googlegroups.com> Message-ID: <1118076124.766146.270470@f14g2000cwb.googlegroups.com> comp.lang.python is a great newsgroup in that respect - so long as you ask a semi-intelligent question, you nearly always end up with a quick and helpful response. Good luck with learning programming, and Python (IMO its one of the best possible languages to do it in) From I.DIEZ at csee-transport.com Thu Jun 9 03:45:38 2005 From: I.DIEZ at csee-transport.com (DIEZ Ignacio) Date: Thu, 9 Jun 2005 09:45:38 +0200 Subject: problems between 2.4 and 2.1 Message-ID: Hi, I have changed the Python release from 2.1 to 2.4 and the results haven't been the expected... With the same code, and with the new release (2.4) the execution of my program raise the following exception: Traceback (most recent call last): File "C:\users\diez\Socle\tools\PARAME~1\GENERA~1\main.py", line 151, in ? viewParser = XmlParser.XmlParser(viewFilePath,viewDtdFilePath) File "c:\Users\diez\Socle\tools\parametrage\Generation\XmlParser.py", line 18, in __init__ self.__initTrees() File "c:\Users\diez\Socle\tools\parametrage\Generation\XmlParser.py", line 25, in __initTrees diagram.normalize() File "C:\software\Python24\lib\xml\dom\minidom.py", line 208, in normalize self.childNodes[:] = L TypeError: object doesn't support slice assignment Could anybody help me, please?? Why the program raise this kind of traceback? Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From enjoylife_95135 at hotmail.com Fri Jun 3 19:41:01 2005 From: enjoylife_95135 at hotmail.com (Sandman) Date: 3 Jun 2005 16:41:01 -0700 Subject: tutorial In-Reply-To: References: Message-ID: <1117842061.208361.278120@g47g2000cwa.googlegroups.com> I'm a beginner as well, and I liked this one: http://docs.python.org/tut/tut.html But I ended up buying the "Learning Python" book anyway. From ronan_boisard at yahoo.com Thu Jun 2 10:31:30 2005 From: ronan_boisard at yahoo.com (ronan_boisard at yahoo.com) Date: 2 Jun 2005 07:31:30 -0700 Subject: calling ksh script from python Message-ID: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> hi all, I'm trying to call ksh script from python. I have a file (toto.env) with a scirpt looking like: -- begin --- #!/bin/ksh # export TOTO_ENV=/home/toto -- end --- I call it from python like that: -- begin --- import commands commands.getstatusoutput('. toto.env') -- end --- but it always return an error saying: sh: TOTO_ENV=/home/home: is not an identifier doesn anyone know why ? no matter what I use (popen,system...) it's always the same error... if I directly try to do commands.getstatusoutput('export TOTO_ENV=/home/toto') it's the same error... and what about this sh primpt in the error message, can't I use ksh script ? thanks for any help ronan From aisaac0 at verizon.net Sun Jun 5 23:20:53 2005 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 06 Jun 2005 03:20:53 GMT Subject: default values of function parameters Message-ID: Alan Isaac wrote: > Default parameter values are > evaluated once when the function definition is > executed. Where are they stored? ... Where is this documented? Forgive any poor phrasing: I'm not a computer science type. At http://www.network-theory.co.uk/docs/pytut/tut_26.html we read: "The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the global symbol table, and then in the table of built-in names." But the default values of function parameters seem rather like a static attributes of a class. Is that a good way to think of them? If so, are they somehow accessible? How? Under what name? Thanks, Alan Isaac From chris.arndt at web.de Wed Jun 29 16:05:03 2005 From: chris.arndt at web.de (Christopher Arndt) Date: Wed, 29 Jun 2005 21:05:03 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: <3ian37Fkjle0U1@individual.net> References: <3ian37Fkjle0U1@individual.net> Message-ID: Reinhold Birkenfeld schrieb: > Do you have any other good and valued Python modules that you would think are > bug-free, mature (that includes a long release distance) and useful enough to > be granted a place in the stdlib? Hmmm, let's look into /site-packackes, That's what I always have installed: - pysqlite - Numeric - PIL - mxExtensions (mostly for mxDateTime) - ClientForm - ClientCookie - pycrypto Most of these are probably not elegible due to license issues but I'd love to see SQLite support added to Python-out-of-the-box. Also, when on windows, I always install the ActiveState distro because it comes with the win23 extensions and more useful documentation. Maybe there should be rather a separate "add-on-packs" distribution? I think, this would be mostly useful for developers though. With solutions like p2exe and python eggs becoming more widely used, caring about what is installed and what not, shouldn't be such an issue anymore. Chris From zanesdad at bellsouth.net Sun Jun 19 23:14:32 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Sun, 19 Jun 2005 23:14:32 -0400 Subject: references/addrresses in imperative languages In-Reply-To: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: <42B63498.3070805@bellsouth.net> I think the only reason I read your posts is for comedy, seeing if this is yet another "Xah Lee just threw a tantrum" post. I don't know why I'm wasting my time responding, though... It's against my better judgment and my previous advice to the group. Xah Lee wrote: >in coding Python yesterday, i was quite stung by the fact that lists >appened to another list goes by as some so-called "reference". e.g. > > What would you have it do? A list is just a collection of objects. If I want to append my object to some list, I don't want a copy of it appended. If I did, I'd pass in a copy of it. Otherwise, a reference gets appended. >t=range(5) >n=range(3) >n[0]='m' >t.append(n) >n[0]='h' >t.append(n) >print t > > >in the following code, after some 1 hour,finally i found the solution >of h[:]. (and that's cheating thru a google search) > >def parti(l,j): > '''parti(l,j) returns l partitioned with j elements per group. If j >is not a factor of length of l, then the reminder elements are dropped. > Example: parti([1,2,3,4,5,6],2) returns [[1,2],[3,4],[5,6]] > Example: parti([1,2,3,4,5,6,7],3) returns [[1,2,3],[4,5,6]]''' > n=len(l)/j > r=[] # result list > h=range(j) # temp holder for sublist > for n1 in range(n): > for j1 in range(j): > h[j1]=l[n1*j+j1] > r.append( h[:] ) > return r > >interesting that a dictionary has copy method, but not list. (the pain >is coupled with the uselessness of the Python doc) > > You keep blasting the Python documentation. You have *yet* to produce anything of 1/10th the quality of any piece of the Python documentation. Until you are able to do so, I recommend shutting your proverbial trap. You have no grounds for raising the first criticism of the Python documentation since you have obviously not spent a significant amount of time reading them. In another thread from yesterday (entitled "functions with unlimited variable arguments..."), you asked where one could find a certain feature in the documentation (functionality which is, in my opinion, pretty basic). You appear to have found a reference in the tutorial by yourself and one person kindly pointed to a reference in the Python reference doc. >------ > > You really don't do a good job making a good point in this section. Maybe it's the poor English, although I can typically extract good thought from poor English. Maybe it really is just poor thought. >Btw, behavior such as this one, common in imperative languages and info >tech industry, is a criminality > Nice. If you don't like something, just call it "a criminality". Let me try: the criminality of Xah Lee's postings caused all occupants of at least 4 continents to roll their eyes. You know - even though I think my assertion had some validity, I think even there it's ridiculous to make such a forceful assertion without a foundation for it. > arose out of hacks C, Unix, and from >there all associated imperative langs. (C++, csh, perl, Java... but >each generation improves slightly) > >The gist of the matter is that these behaviors being the way they are >really is because they are the easiest, most brainless implementation, >as oppose to being a design decision. > > Again, prove it. Why is passing references (or appending references - you're not totally clear on what your beef is) brainless? What better implementation do you have to offer the world, oh great one? >In hindsight analysis, such language behavior forces the programer to >fuse mathematical or algorithmic ideas with implementation details. A >easy way to see this, is to ask yourself: how come in mathematics >there's no such thing as "addresses/pointers/references". > > Maybe because in pure mathematics there isn't the need for a computer. Although, if we updated Descartes, Pascal, Fermat, Newton, and Leibnitz with some of Rambaldi's works, you might see the concept of addresses/pointers/references in pure mathematics. >--------- > >PS is there any difference between >t=t+[li] >t.append(li) > > In [1]: def summit(lst, item): ...: lst = lst + item ...: print lst ...: In [2]: def appender(lst, item): ...: lst.append(item) ...: print lst ...: In [3]: def plus_equals(lst, item): ...: lst += item ...: print lst ...: In [5]: import dis In [6]: dis.dis(summit) 2 0 LOAD_FAST 0 (lst) 3 LOAD_FAST 1 (item) 6 BINARY_ADD 7 STORE_FAST 0 (lst) 3 10 LOAD_FAST 0 (lst) 13 PRINT_ITEM 14 PRINT_NEWLINE 15 LOAD_CONST 0 (None) 18 RETURN_VALUE In [7]: dis.dis(appender) 2 0 LOAD_FAST 0 (lst) 3 LOAD_ATTR 1 (append) 6 LOAD_FAST 1 (item) 9 CALL_FUNCTION 1 12 POP_TOP 3 13 LOAD_FAST 0 (lst) 16 PRINT_ITEM 17 PRINT_NEWLINE 18 LOAD_CONST 0 (None) 21 RETURN_VALUE In [8]: dis.dis(plus_equals) 2 0 LOAD_FAST 0 (lst) 3 LOAD_FAST 1 (item) 6 INPLACE_ADD 7 STORE_FAST 0 (lst) 3 10 LOAD_FAST 0 (lst) 13 PRINT_ITEM 14 PRINT_NEWLINE 15 LOAD_CONST 0 (None) 18 RETURN_VALUE Figure it out. >--------- >References: > >for a analysis of the same situation in Java, see >http://xahlee.org/java-a-day/assign_array_to_list.html > >How to write a tutorial >http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html > > Xah > xah at xahlee.org >? http://xahlee.org/ > > > It's really bad enough that you waste the time of the folks on comp.lang.python. Why cross post like you are? I really fail to see the point. Jeremy Jones From foundsabin at gmail.com Tue Jun 21 02:56:50 2005 From: foundsabin at gmail.com (Sabin.A.K) Date: 20 Jun 2005 23:56:50 -0700 Subject: .dll files In-Reply-To: <42B6CA2B.3030909@syscononline.com> References: <1119265966.661838.186320@g44g2000cwa.googlegroups.com> <42B6CA2B.3030909@syscononline.com> Message-ID: <1119337010.540555.226800@g43g2000cwa.googlegroups.com> Thank you Larry, And one more thing to ask, Will the COM Object be a total solution for my problems? I just try to make a dll to encapsulate some 'icon and text' files for my application. Which should get installed in the users system while installing it. but user should not be able to edit those files. thats why i ve turned towards dlls. Is it possible with COM objects? i am unaware of it. SABIN. Larry Bates wrote: > You are most likely better off creating COM objects than > trying to create old .dll files. Good treatment of COM > object creation is in the book titled Python Programming > on Win32. Most other languages have no problem interfacing > with COM objects. > > -Larry > > Sabin wrote: > > How can i create dll files in Python? > > Is it possible? > > > > If yes, > > how to enclose image and font files in a dll ? > > > > Plis reply. > > SABIN. > > B'lore. > > From mfranklin1 at gatwick.westerngeco.slb.com Tue Jun 7 08:02:13 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 07 Jun 2005 13:02:13 +0100 Subject: separate IE instances? In-Reply-To: <1118144873.935177.287190@g43g2000cwa.googlegroups.com> References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> Message-ID: Chris Curvey wrote: > Bummer. No change at all. (In fact, I can't even call Navigate() > without throwing an error). I'm on win2k, if that makes any difference. > I could be way off, but isn't windows one of those OS's that doesn't allow you to have two instances of IEXPORE.EXE running IOW the OS is preventing you from running two instances of this executable. Someone with a lot more knowledge of windows internals will I'm sure come along and correct me ;-) Mart From rem642b at Yahoo.Com Mon Jun 27 01:59:58 2005 From: rem642b at Yahoo.Com (Robert Maas, see http://tinyurl.com/uh3t) Date: Sun, 26 Jun 2005 22:59:58 -0700 Subject: A Module on Time & Date References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: > From: John Abel > time - http://docs.python.org/lib/module-time.html Ah, thanks! It works here, whereas: > datetime - http://docs.python.org/lib/module-datetime.html doesn't work, no such module, see: http://groups-beta.google.com/group/comp.lang.python/msg/0e4307f5cfa28b6a Message-ID: Anyway, I'll update my one-step-after-hello-world demo for Python tomorrow or sometime to include the time stuff. From gatti at dsdata.it Fri Jun 24 04:17:16 2005 From: gatti at dsdata.it (gatti at dsdata.it) Date: 24 Jun 2005 01:17:16 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <1119601035.966587.255360@g14g2000cwa.googlegroups.com> Joseph Garvin wrote: > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? Duff's device is a classic masterpiece of lateral thinking. It is not possible in Python for many fundamental reasons, we are not at risk. Lorenzo Gatti From unclebob at objectmentor.com Sun Jun 26 23:47:25 2005 From: unclebob at objectmentor.com (Robert C. Martin) Date: Sun, 26 Jun 2005 22:47:25 -0500 Subject: Acceptance test spike example References: Message-ID: <1ltub1lkvu3t83nvs46ul1e3camuhgogjv@4ax.com> On Sun, 26 Jun 2005 16:10:05 -0700, Steve Jorgensen wrote: >I'm posting this message for 2 reasons. > >First, I'm still pretty new and shakey to the whole Acceptance Testing thing, >and I'm hoping for some feedback on whether I'm on the right track. Second, >although all the Agile literature talks about the importance of doing >Acceptance Testing, there's very little in any of the books or out on the Web >that helps with how to do it. If I am on the right track, this will be one >more helpful item folks can find on a Google search. Check out "Fit For Software Development". It should be published now. ----- Robert C. Martin (Uncle Bob) | email: unclebob at objectmentor.com Object Mentor Inc. | blog: www.butunclebob.com The Agile Transition Experts | web: www.objectmentor.com 800-338-6716 "The aim of science is not to open the door to infinite wisdom, but to set a limit to infinite error." -- Bertolt Brecht, Life of Galileo From noreply at gcgroup.net Tue Jun 28 11:35:12 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 28 Jun 2005 15:35:12 GMT Subject: tkinter radiobutton In-Reply-To: References: Message-ID: > or use a custom subclass ... I had considered extending radiobutton to add whatever properties needed, but the net/net is the same, that property must be set using methods that trigger on the rb command procedure, or an external (to the rb) control variable value. The radiobutton widget knows if it is selected or unselected, or it wouldn't be able to display correctly, but based on what I'm seeing, that information is inaccessable to the app. Instead the app must evaluate an associated control variable. That doesn't make sence to me, but even trying to look at the code for the radiobutton class didn't help. I guess I need to set up an observer on the control variable, or a command procedure on the radiobutton (effectively to create my own control variable). I know I can 'slice' my original 4 X 4 matrix vertically, by associating a different intVar to each 'column', but I can't figure out how to 'slice' them horizontally w/o breaking their vertical relationships. Bill Peter Otten wrote: > William Gill wrote: > > >>I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep >>references to them in a 2 dimensional list ( rBtns[r][c] ). It works >>fine, and I can even make it so only one button per column can be >>selected, by assigning each column to an intVar. In many languages a >>radiobutton has a property that can be directly read to see if it is >>selected on unselected. Tkinter radiobuttons don't seem to have any >>such property. Is there any way to look (via the script not the screen) >>to determine if it is selected?, or can this only be achieved via >>control variables? > > > You can either write a little helper function > > def selected(rbn): > return rbn.getvar(rbn["variable"]) == rbn["value"] > > or use a custom subclass of Tkinter.Radiobutton with a 'selected' attribute: > > class Radiobutton(Tkinter.Radiobutton): > def __getattr__(self, name): > if name == "selected": > return self.getvar(self["variable"]) == self["value"] > raise AttributeError > > > Peter > From deets at web.de Thu Jun 23 14:07:10 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 23 Jun 2005 20:07:10 +0200 Subject: newbie - modules for jython (under grinder 3) ? In-Reply-To: <42bae670$0$41928$ed2619ec@ptn-nntp-reader03.plus.net> References: <42bac1b8$0$2021$ed2e19e4@ptn-nntp-reader04.plus.net> <3i00ndFho4uoU1@uni-berlin.de> <42bae670$0$41928$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <3i0c2fFj651hU1@uni-berlin.de> OK - of course this means I'll have to tell Grinder to > use "my" Jython, not "its" Jython. > > Hopefully that's well documented :-) If they use 2.1 - which you should hope :) - teaching it shouldn't be much more as issuing -Dpython.home= as argument to the VM. Diez From simon.brunning at gmail.com Fri Jun 24 06:45:06 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 24 Jun 2005 11:45:06 +0100 Subject: suggestions invited In-Reply-To: <1119559578.075157.289290@g44g2000cwa.googlegroups.com> References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119552092.000448.10230@g47g2000cwa.googlegroups.com> <1119555027.087947.100970@g43g2000cwa.googlegroups.com> <1119559578.075157.289290@g44g2000cwa.googlegroups.com> Message-ID: <8c7f10c605062403451b55202f@mail.gmail.com> On 23 Jun 2005 13:46:18 -0700, Peter Herndon wrote: > Reasonable enough. As per Mike's suggestion below, building a few web > pages to document the apps is a good start. To expand on that idea, > you could write daemons/cron jobs, perhaps in Python if Python runs on > OS/400, http://www.iseriespython.com/ > that monitor each app's status and log that information to the > web server. I'm ot sure how you'd define an 'application' on a '400. You just have a bunch of progams in libraries. I'm not sure what the 'status' of an application might meain, either, in general terms. This is really very pooly specified. > You could then write a web application that takes the > monitoring data and formats it appropriately for human consumption. Running a Python web application on a '400 would be a pretty daunting task, if it's even possible. > Perhaps an RSS or Atom feed for each application's status. > > I don't know anything about OS/400, but if it has a tool similar to > syslog, you could configure the application hosts to report their > status to a remote syslogd, perhaps on your web server, and parse the > log file for the status data. QHST is similar to syslog - but what's an application host in 400 terms? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From plasters at opendoortechnologies.com Thu Jun 2 11:56:43 2005 From: plasters at opendoortechnologies.com (Rosaline) Date: Thu, 2 Jun 2005 17:56:43 +0200 Subject: Software for System Builders, Resellers, and Hardware Purchasers Only. Message-ID: <130709126501.7239466046@i528C3EC2.versanet.de> GET latest softwares, 99% savings. http://jtj.pebms6p0mh7wm87.narrjl.com Human nature is not of itself vicious. I believe in God, only I spell it Nature. From hancock at anansispaceworks.com Wed Jun 15 13:38:19 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 15 Jun 2005 12:38:19 -0500 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42AED7B3.8060009@carmen.se> References: <42AED7B3.8060009@carmen.se> Message-ID: <200506151238.19623.hancock@anansispaceworks.com> On Tuesday 14 June 2005 08:12 am, Magnus Lycka wrote: > Oh well, I guess it's a bit late to try to rename the Computer > Science discipline now. Computer programming is a trade skill, not a science. It's like being a machinist or a carpenter --- a practical art. Unfortunately, our society has a very denigrative view of craftsmen, and does not pay them well enough, so computer programmers have been motivated to attempt to elevate the profession by using the appellative of "science". How different would the world be if we (more accurately) called it "Computer Arts"? -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ChuckDubya at gmail.com Tue Jun 28 23:51:01 2005 From: ChuckDubya at gmail.com (ChuckDubya at gmail.com) Date: 28 Jun 2005 20:51:01 -0700 Subject: Newbie: Help Figger Out My Problem In-Reply-To: References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> <42c174ab$1@nntp0.pdx.net> <1119987053.884256.211190@g49g2000cwa.googlegroups.com> Message-ID: <1120017061.447691.255360@f14g2000cwb.googlegroups.com> Thanks to all who replied. I did not ask for other iterations of my program. I asked what was wrong with it. To those who did just that, explained what was wrong, thank you for answering my question. From roy at panix.com Fri Jun 17 20:00:39 2005 From: roy at panix.com (Roy Smith) Date: Fri, 17 Jun 2005 20:00:39 -0400 Subject: exceptions considered harmful References: <1119027185.832640.291760@g43g2000cwa.googlegroups.com> Message-ID: "H. S. Lahman" wrote: > > Never throw an exception. And if someone throws one at you, > > catch it immediately and don't pass it on. > > IMO, this is generally fine advice. Languages provide exception > handlers so that applications have a chance to respond gracefully when > the software is in an unstable state. IOW, you should never see an > exception unless the software is seriously broken. A corollary is that > if the software is corrupted, then even processing the exception becomes > high risk. So one should do as little as possible when processing > exceptions. (Some languages provide a degree of bullet proofing, but > that just make the exception handling facility too expensive to use for > routine processing.) This sounds like a very C++ view of the world. In Python, for example, exceptions are much more light weight and perfectly routine. From idontneednostinkinid at yahoo.com Wed Jun 1 18:19:24 2005 From: idontneednostinkinid at yahoo.com (Mac) Date: 1 Jun 2005 15:19:24 -0700 Subject: bug with isinstance() ? In-Reply-To: References: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> Message-ID: <1117664364.603412.73230@g49g2000cwa.googlegroups.com> I see, interesting. OK, I understand that recursive importing can be problematic (having to "hide" the test2 import should have been a tip off; it's just that in my original app this relationship is not as clear), but what is the lesson I should take away from this? I mean, I was under the impression that "once a Foo, always a Foo", while from the above I'm starting to see that a single class definition can give rise to a multiple number of classes, and that the classes are parametrized by the module they come from (I guess that makes sense... else class names would have to be unique throughout all the source for a single program)... I guess the problem is I'm thinking of "classes" as these abstract concepts, sort of like Platonian "forms", whereas I should be thinking of classes as "class objects", object instances, each coming from some module's namespace... is this sort of the idea? Someone help me wrap my head around this, please. :) From peter at engcorp.com Thu Jun 2 09:50:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 09:50:21 -0400 Subject: decimal and trunkating In-Reply-To: <8dKdnRm_WPb3kALfRVn-vw@powergate.ca> References: <8dKdnRm_WPb3kALfRVn-vw@powergate.ca> Message-ID: <8f-dneYR35hAkwLfRVn-tw@powergate.ca> Peter Hansen wrote: > >>> d = decimal.Decimal('199.999') > >>> decimal.getcontext().rounding = decimal.ROUND_FLOOR > >>> d.quantize(decimal.Decimal('1.00')) > Decimal("199.99") Or skip changing the context and use the second argument to quantize: d.quantize(Decimal('1.00'), decimal.ROUND_FLOOR) -Peter From pfiland at mindspring.com Mon Jun 20 04:58:12 2005 From: pfiland at mindspring.com (pete) Date: Mon, 20 Jun 2005 08:58:12 GMT Subject: references/addrresses in imperative languages References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: <42B68528.196D@mindspring.com> Xah Lee wrote: > > in coding Python yesterday, It seems to be giving you anxiety. Have you considered not coding on python? -- pete From rex.eastbourne at gmail.com Thu Jun 23 21:30:54 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 23 Jun 2005 18:30:54 -0700 Subject: Running Python interpreter in Emacs In-Reply-To: References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> Message-ID: <1119576654.090762.106010@z14g2000cwz.googlegroups.com> Hi Skip and Philippe. I added the path for Python to PATH, but I still get the same message (when I try executing the current buffer, I get the message: "The system cannot find the path specified." Philippe, I have the above lines of code in my .emacs file. As for my environment, I'm running Emacs 21.4 on Windows XP. Thanks a lot! From jabel at plus.net Wed Jun 29 09:54:10 2005 From: jabel at plus.net (John Abel) Date: Wed, 29 Jun 2005 14:54:10 +0100 Subject: Got an interesting problem. (platform ruuning issue) In-Reply-To: <6829832e05062906341c3a8999@mail.gmail.com> References: <6829832e05062906341c3a8999@mail.gmail.com> Message-ID: <42C2A802.7050801@plus.net> Jeffrey Maitland wrote: >when running scripts they seem to work fine on ia-32 but I get >segfault on ia-64 what the heck should I be looking for? > >I did notice that it seems to work ok only for certain scripts but any >script that imports MySQLdb or glob seems to make this occur. > >Thanks Jeff > > That sounds to me like an issue with compiled libraries. Does cli mysql work on the machine ( would verify a working libmysqlclient_r )? I'm guessing glob fails due to it's dependence on re, and the os specific parts of os? J From peter at engcorp.com Sun Jun 12 22:06:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Jun 2005 22:06:13 -0400 Subject: case/switch statement? In-Reply-To: References: Message-ID: Chinook wrote: > On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote: >>Case statements are actually more suitable in many cases even when >>performance is not a goal for reasons of *readability*. >> >>When reading an if statement, you have to scan down through effective >>each statement attempting to find the case in which you are interested. >> Some cases can be compound. The nested ifs can get confused with the >>surrounding ones (in Python or a language with explicit block >>delimiters). The cases are often not written in any particular order, >>or they are ordered *for* performance reasons, but in ways that make it >>harder to "scan". > > The problem I do see is your apples and oranges argument. You are equating > at the extreme, "compound" if conditions with "_simple_" case statement > conditionals. Yet you are leaving out of your argument the transition from > the former to the latter. If mapping one to the other is simple then the > readability is no harder with if statements. I dispute that, and believe you've misunderstood my core point. It's not anything to do with "equivalence" between the two approaches. It's that if you see a set of if/else statements, you have to look at all of them to understand completely what's happening. (I mean the structure of the if/else... the conditionals, not the contents of the blocks.) With a case statement, on the other hand, you *know* that it must be just simple conditionals (a series of x == some_constant tests), so you don't need to look at all the cases, just the one that interests you. So it's not a comparison between two ways of writing the same thing, it's about the fact that with a case statement there are many things you *cannot* write, so reading one is much easier than reading a similarly sized compound if/else. This is much like saying that a short function is easier to read than a long one. The long one can obviously do much more, so it's an apples and oranges comparison in that sense. But clearly if the short one fits all on one screen and the long one does not, the short one is basically much easier to grok. That's all I'm saying. > In my experience I've also seen where case statements promote overly long and > partially repetitive code blocks, which would be better constructed in a > top-down fashion. Admittedly, if statements could be used in a similar way > but I've not seen the same level of abuse with such. That's true. > So arguably, if the translation is pretty much one to one then the argument > is mute :~) ^^^^ "moot" Sort of, except my point here would be that a case statement is then the better choice in many cases because it communicates to the reader that the entire thing *is* simple, while the if/else/if/else does not. -Peter From zathras at thwackety.com Mon Jun 13 18:25:10 2005 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 13 Jun 2005 23:25:10 +0100 Subject: BBC R&D White Paper on Kamaelia Published (Essentially a framework using communicating python generators) References: <42ab5b17$0$2046$ed2e19e4@ptn-nntp-reader04.plus.net> <1118629263.552489.236130@f14g2000cwb.googlegroups.com> Message-ID: <42ae07ad$0$2974$ed2619ec@ptn-nntp-reader01.plus.net> pmaupin at gmail.com wrote: > >> I've written up the talk I gave at ACCU Python UK on the Kamaelia >> Framework, and it's been published as a BBC R&D White Paper and is >> available here: >> >> * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml > I enjoyed the paper. I'm pleased to hear that and I hope the ideas are useful at some point in time! (directly or indirectly :) > I don't have time to play with the code right now, but it sounds like fun. > I do have one question -- in practice, how difficult have you found it > that Python generators don't maintain separate stacks? I'm not sure I understand the question! (I think you're either coming from a false assumption or mean something different) I can see 3 possible answers... How difficult is it to build systems using them? Well, we managed to get a novice programmer up to speed and happy with python and using the core ideas in Kamaelia in a 2 week period. And over the 3 month period he was with us he implemented a small system essentially demoing previewing streamed content from a PVR on a Series 60 mobile (and on a desktop/laptop PC). (Of course that could be because he was a natural, *or* because it can be fairly easy - or both) Regarding the idea that python generators stacks "collide" aren't separate. If you mean an implementation detail I'm not aware of, it doesn't cause any problems at all. If you are coming from the assumption that they share the same state/stack frame... Consider the example generator function: >>> def fib(): ... a,b = 0,1 ... while 1: ... yield b ... a,b = b, a+b ... Then call this twice yielding two different generator objects: >>> G = fib() >>> G >>> H = fib() >>> H If they shared the same stack (by which I assume you mean stack frame), then advancing one of these should advance both. Since in practice they run independently you get the following behaviour: >>> G.next() 1 >>> G.next() 1 >>> G.next() 2 >>> G.next() 3 >>> G.next() 5 >>> H.next() 1 >>> H.next() 1 >>> H.next() 2 >>> G.next() 8 ie both generators "run" independently with different local values for a,b since they *don't* share stack frames. (Also as I understand it the stack frame associated with each generator is effectively put aside between invocations) As a result from that interpretation of your question (that it's based on the mistaken assumption that state is shared between generators), we haven't found it a problem at all because it's a false assumption - the generators naturally don't share stacks. The alternative is that you're talking about the fact that if you put "yield" in a def statement that it forces that definition to define a generator function. (ie you can't nest a yield) For example in some TCP client code we have: def runClient(self,sock=None): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); yield 1 try: sock.setblocking(0); yield 2 try: while not self.safeConnect(sock,(self.host, self.port)): yield 1 ... snip ... It would be a lot more natural (especially with full co-routines) to have: def runClient(self,sock=None): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM); yield 1 try: sock.setblocking(0); yield 2 try: self.safeConnect(sock,(self.host, self.port)): ... snip ... And to still have runClient be the generator, but have safeConnect doing the yielding. (You can do this using Greenlets and/or Stackless for example) However in practice it seems that this limitation is in fact more of a strength - it encourages smaller simpler generators whose logic is more exposed. Furthermore we very rarely have to nest calls to generators because the way we deal with multiple generators is to set them running independently and wait for communications between them. These small generators also seem to lend themselves better to composition. For example: clientServerTestPort=1500 pipeline(TCPClient("127.0.0.1",clientServerTestPort), VorbisDecode(), AOAudioPlaybackAdaptor() ).run() If you allow nested calls, it's perhaps natural to couple the last two together as one component - but that is ultimately limiting - because each component would then be trying to do too much. Finally, in practice, it's pretty easy to write new components - we tend to focus on the functionality we want, find it's main loop, add in yields in key locations to effectively time slice it to turn it into a generator. That then becomes the core of the component, and we then remove code that deals with direct input/output (eg from files) and recv/send to/from in/out-boxes. It leads to a fairly natural process for creating generator based components. (And can also lead to a fast assimilation process for existing python based code, when needed) There's a walk through the creation of multicast handling components here: http://kamaelia.sourceforge.net/cgi-bin/blog/blog.cgi?rm=viewpost&postid=1113495151 It's a bit long winded - mainly due to repeatedly copying code to highlight differences inplace - but should show that in practice it's a number of small simple incremental steps. (Showing how we can go from standalone test programs to generators to components) It also shows how the system can end up causing you to create more general code than originally intended, which is also more compact and obvious. I suppose the short answer to your question though is that the defined limitations of python's (simple) generators do in fact turn out to be a strength IMO. Anyhow, I hope that's answered your original question ? (or hopefully explained why I found your question unclear!) Best Regards, Michael -- http://kamaelia.sourceforge.net/ From ptmcg at austin.rr.com Thu Jun 30 23:30:54 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Jun 2005 20:30:54 -0700 Subject: Escaping commas within parens in CSV parsing? References: <1120184545.602314.294790@g44g2000cwa.googlegroups.com> Message-ID: <1120188654.466828.257540@g44g2000cwa.googlegroups.com> Well, this doesn't have the terseness of an re solution, but it shouldn't be hard to follow. -- Paul #~ This is a very crude first pass. It does not handle nested #~ ()'s, nor ()'s inside quotes. But if your data does not #~ stray too far from the example, this will probably do the job. #~ Download pyparsing at http://pyparsing.sourceforge.net. import pyparsing as pp test = "AAA, BBB , CCC (some text, right here), DDD" COMMA = pp.Literal(",") LPAREN = pp.Literal("(") RPAREN = pp.Literal(")") parenthesizedText = LPAREN + pp.SkipTo(RPAREN) + RPAREN nonCommaChars = "".join( [ chr(c) for c in range(32,127) if c not in map(ord,list(",()")) ] ) nonCommaText = pp.Word(nonCommaChars) commaListEntry = pp.Combine(pp.OneOrMore( parenthesizedText | nonCommaText ),adjacent=False) commaListEntry.setParseAction( lambda s,l,t: t[0].strip() ) csvList = pp.delimitedList( commaListEntry ) print csvList.parseString(test) From david.baelde at ens-lyon.fr Fri Jun 10 16:11:47 2005 From: david.baelde at ens-lyon.fr (David Baelde) Date: Fri, 10 Jun 2005 22:11:47 +0200 Subject: Abstract and concrete syntax References: <11af9le2v96r1ac@news.supernews.com> Message-ID: > For instance, if assignment were done in an expression, the targets would > have to be quoted to avoid having them evaluated. Or the assignment > expression would have to be a 'special expression' that did not evaluate > all its terms (like setq in some (just older?) lisps). In Python, that > 'special expression', with its 'quote, don't evaluate, targets' rule, is a > statement! That's not such a big issue, many languages solve that without quoting. Ruby, for example. I agree that there's a point here. But nothing to do with quoting. You refer to Lisp, here's how things work in Caml: standard variables cannot be assigned, only defined with [let x = v in ...]. But you can create references, which can be assigned. When you wanna get the value of a ref you use [!x], if you wanna set it, use [x := ...]. It allows you to write [(if test then x else y) := ...], which is actually rarely needed. Thus, making implicit the ! everywhere except before := is acceptable. And you get the usual behavior with python. Finally, you just have to choose the value of [x = v], maybe [v], maybe [None]. __ David From nicola-mingotti at libero.it Wed Jun 15 23:21:17 2005 From: nicola-mingotti at libero.it (Nicola Mingotti) Date: Thu, 16 Jun 2005 03:21:17 +0000 Subject: splitting delimited strings References: <42B0BB98.2020106@lexicon.net> Message-ID: On Thu, 16 Jun 2005 09:36:56 +1000, John Machin wrote: >> like this ? > > No, not like that. The OP said that an embedded @ was doubled. you are right, sorry :) anyway, if @@ -> @ an empty field map to what ? From newsgroups at jhrothjr.com Sun Jun 12 19:41:21 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 12 Jun 2005 17:41:21 -0600 Subject: changing how instances are "created" References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> Message-ID: <11api166se4itcc@news.supernews.com> "newseater" wrote in message news:1118617483.215438.318980 at o13g2000cwo.googlegroups.com... > Hello. I need to be able to control how objects are created. Sometimes > when creating an object, i want to reuse another object instead. I've > searched for factory method implementations and singleton > implementations. They were too much of a hack! > > My first attempt of doing this was to play around with the __new__() > method. But i didn't quite succed. Then i came up with making a static > method which can create my instances or re-use other instances. > However, the below code I cannot get to work :( > > class Creator > def createInstance(cls, *args, **kwargs): > anewinstance = cls.__new__(cls, *args, **kwargs) > anewinstance.__init__(*args, **kwargs) > > return anewinstance > createInstance = staticmethod(createInstance) > > > can anyone help?? __new__ is the proper way to do this, but making it work is a bit tricky. If you could post the code you tried to get to work for __new__(), we could critique it. The current documentation is in 3.3.1 of the Python Reference Manual (Python 2.4 version). In earlier versions, there were a couple of other documents that did a better (IMO) job of explaining things. The trick is that __new__ must return an instance. It can be a newly created instance (and the doc shows how to do this) or an existing instance of any new style class. By the way - when you post code, please use spaces for indentation. There are a number of popular mail clients that don't play fair with tabs, and people using these clients will frequently ignore code that isn't properly indented. John Roth From gene.tani at gmail.com Wed Jun 22 18:19:44 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jun 2005 15:19:44 -0700 Subject: No subject In-Reply-To: References: <54D46A9CCE56F04D802E186634F8BCA701E58050@pros-mail.prosrm.com> Message-ID: <1119478784.378969.68970@g44g2000cwa.googlegroups.com> i think this came up yesterday\ http://www.python.org/cgi-bin/moinmoin/IntegratedDevelopmentEnvironments From roy at panix.com Tue Jun 14 18:27:38 2005 From: roy at panix.com (Roy Smith) Date: Tue, 14 Jun 2005 18:27:38 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> <863brlzmy9.fsf@guru.mired.org> <86ekb4y5ut.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > I've never seen someone explain why, for instance, string addition is > O(n^2) beyond the very abstract "it creates a new string with each > addition". No concrete details at all. I took a shot at that very question a while ago. Elephants never forget, and neither does google (http://tinyurl.com/9nrnz). From kveretennicov at gmail.com Fri Jun 24 07:16:09 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Fri, 24 Jun 2005 14:16:09 +0300 Subject: printing indented html code In-Reply-To: References: Message-ID: <4660fe30050624041674da1b7b@mail.gmail.com> On 6/24/05, Lowell Kirsh wrote: > Is there a module or library anyone knows of that will print html code > indented? Depends on whether you have to deal with xhtml, valid html or just any, possibly invalid, "pseudo-html" that abounds on the net. Here's an example of (too) simple html processing using standard HTMLParser module: from HTMLParser import HTMLParser class Indenter(HTMLParser): def __init__(self, out): HTMLParser.__init__(self) self.out = out self.indent_level = 0 def write_line(self, text): print >> self.out, '\t' * self.indent_level + text def handle_starttag(self, tag, attrs): self.write_line( '<%s %s>' % (tag, ' '.join('%s=%s' % (k, v) for k, v in attrs)) ) self.indent_level += 1 def handle_endtag(self, tag): self.indent_level -= 1 self.write_line('' % tag) handle_data = write_line # handle everything else... # http://docs.python.org/lib/module-HTMLParser.html if __name__ == '__main__': import sys i = Indenter(sys.stdout) i.feed('foobarbody') i.close() - kv From cam.ac.uk at mh391.invalid Wed Jun 29 18:05:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 29 Jun 2005 23:05:37 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Herb starts with H, not E. It isn't "ouse" or "ospital" or "istory". It > isn't "erb" either. You just sound like tossers when you try to pronounce > herb in the original French. And the same with homage. Strangely enough there are Brits who pronounce "hotel" without an H at the beginning. And even those who pronounce it with an H sometimes say "an hotel" rather than "a hotel" because it used to be pronounced starting with the vowel! Similarly, the Brits should note that "idea" does not end in an "r" and that "Eleanor" does. -- Michael Hoffman From ognjen at mailshack.com Sat Jun 4 04:52:14 2005 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Sat, 04 Jun 2005 09:52:14 +0100 Subject: If - Or statements Message-ID: <42A16BBE.4080301@mailshack.com> Another newbie-ish question. I want to create an if statement which will check if a particular variable matches one of the statements, and willl execute the statement if the variable matches any of the statements. I have tried the following (the pass is just used for testing) if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or ext[1] == "aac" or ext[1] != "wma": print "we have a valid extension: " + ext[1] #here would go the code for decoding the above pass but it does not work, running the program the if statement is totally ignored. if the variable (ext[1]) matches it does not execute the instructions under the if statement, but also does not return anyerrors. So how do you create proper if statements using the 'or' function (or something similar). thx. P.S Please CC me as i am having email-list troubles. From benji at benjiyork.com Fri Jun 10 13:56:08 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 10 Jun 2005 13:56:08 -0400 Subject: Abstract and concrete syntax In-Reply-To: <1118422393.345692.180340@g47g2000cwa.googlegroups.com> References: <1118422393.345692.180340@g47g2000cwa.googlegroups.com> Message-ID: <42A9D438.3010705@benjiyork.com> George Sakkis wrote: > Another case I've found handy to use lambdas and expressions instead of > named functions and statements is for simple properties: > > class SomeArray(object): > dimensions = property( > fget = lambda self: (self.x,self.y), > fset = lambda self,(x,y): setattr(self,'x',x) or > setattr(self,'y',y)) How about: class SomeArray(object): @apply def dimensions(): def fget(self): return (self.x, self.y) def fset(self, (x, y)): self.x = x self.y = y return property(fget, fset) It doesn't have the "one-liner" appeal of the lambda version, but it reads well. -- Benji York From onurb at xiludom.gro Wed Jun 29 04:58:25 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 29 Jun 2005 10:58:25 +0200 Subject: How to connect python and Mysql? In-Reply-To: References: Message-ID: <42c262b4$0$7667$636a15ce@news.free.fr> praba kar wrote: > Dear All, > > I am using python2.4 and Mysql 4.0.20. Now I am > want to connect python and mysql. I have problem to > install Mysql-python-1.2.0 interface into my machine. > When I try to install this interface the following > error restrict to install fully. > > /System/Links/Executables/ld: cannot find > -lmysqlclient_r > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 This is not a Python problem, but what... Your linker doesn't find the librairy libmysqlclient_r.so. Check if this lib is installed on your system, and if yes if it's located somewhere where your linker can find it. > So If anybody knows regarding this kindly mail me post on usenet, get the answer on usenet !-) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From hongqn at gmail.com Thu Jun 30 00:41:13 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Thu, 30 Jun 2005 12:41:13 +0800 Subject: how to shrink a numarray array? Message-ID: <42C377E9.3040200@gmail.com> To draw a large array of data on a small panel, I need to shrink it to a given size. e.g: To draw numarray.arange(10000) on a panel of width of 100, I only need to draw the points of (0, 100, 200, 300, ...) instead of (0, 1, 2, ...). So I need a method to shrink it to an 100-item array. x[::len(x)/panel_width] will not work. If the panel's width is 60, that expression will return an array of 61 elements. I believe there is an existing function in numarray to do this, however English is not my mother tongue and math is not my speciality, I can't find it in the document full of math terms... -- Qiangning Hong ______________________________________________ ( Michael: ) ( ) ( Hi. I'm Michael Jackson, from The Jacksons. ) ( ) ( Homer: I'm Homer Simpson, from the Simpsons. ) ( ) ( Stark Raving Dad ) ---------------------------------------------- o o \ \ /\ ( ) .( o ). From guy.lateur at b-b.be Thu Jun 23 07:37:05 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 23 Jun 2005 11:37:05 GMT Subject: List of all installed applications (XP)? References: Message-ID: | What -- from your point of view -- is an "application"? Good question. Let me try to elaborate: I would like to know if people in our company (building techniques) are using non-licensed software (eg Photoshop, Office, AutoCad). So I guess by 'application' I mean commercial software packages like those. Is it safe to assume those apps get listed in AppPath? I don't think my users are cunning enough to mess with the registry, so I guess we're talking about the 'standard' installation. | Neither does every app have an Add/Remove Program | entry. (And some things have entries which aren't apps). Just out of curiosity: can one read the info/list one gets in Add/Remove Programs? It's not a problem I get results that aren't actually apps, but it is important I get all apps. Thanks, g From edvard+news at majakari.net Tue Jun 28 08:30:02 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Tue, 28 Jun 2005 15:30:02 +0300 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1119946239.413507.93080@g44g2000cwa.googlegroups.com> Message-ID: <87k6keu0j9.fsf@titan.staselog.com> gatti at dsdata.it writes: > Ivan Van Laningham wrote: > [...] >> >> Seriously, PostScript is a lot more fun to learn than Forth, and more >> directly useful. Since the rewards are so immediate, a kid's attention >> could be gained and kept pretty easily. > > PostScript is easy, but I'm afraid some technical details could get in > the way of enjoyable exploration, e.g. font types or scaling. > PostScript is also a single purpose language: it can print static > graphics and with a slightly more complex setup it can display static > graphics on the screen, period. No interactivity, no files, no network, > no general computation or data structures. PostScript is _not_ limited to static stuff, and it _does_ support interactivity. See eg. http://www.cs.technion.ac.il/~wagner/index_files/aaa.html Of course, this is just academic fun(?). PostScript is mostly used for printers, and as for yet, quite few papers support animated graphics :-> And yes, I also encourage to try Python. > List comprehensions, however, *are* the basic control flow; loops are > much more verbose and they should be used only when necessary. Hm. My experience is that people find loops easier to understand - varies somewhat, though. For some, 'more verbose' is 'more easy to understand'. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From kent37 at tds.net Thu Jun 16 08:25:28 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Jun 2005 08:25:28 -0400 Subject: pyunit: remove a test case on the fly In-Reply-To: <1118869989.840138.16520@g44g2000cwa.googlegroups.com> References: <1118869989.840138.16520@g44g2000cwa.googlegroups.com> Message-ID: <42b16f47$1_2@newspeer2.tds.net> chris wrote: > We have a number of TestCase classes that have multiple test methods. > We are interested in removing any of the individual test methods on the > fly (dynamically, at runtime, whatever). > > We currently have an "isSupported" method in the TestCase classes that > return a bool by which the greater test harness decides whether to run > the enclosed test methods or not. We would like to have > per-test-method granularity, however, for essentially skipping that > particular test method; basically another isSupported call within the > individual methods. We took a quick look at such options as: > generating the entire test suite, then iterating through and renaming > SomeTestClass.testSomeTest to SomeTestClass.SKIPsomeTest, and seeing if > PyUnit would skip it (since the method name no longer starts with > "test"). But this seemed pretty unwieldy. We have also considered > breaking up the test class to a number of smaller test classes and > calling isSupported with that finer-granularity set of test classes. > That is probably the easiest way, but we do still want to consider > alternatives. ISTM you could write a custom TestLoader that filters the test names, then pass that loader to unittest.main(). For example, assuming a classmethod or staticmethod on the test case that filters test case names, something like this (not tested): def MyTest(TestCase): @staticmethod def isSupportedTest(testName): return True def testSomething... class FilteringTestLoader(TestLoader): def getTestCaseNames(self, testCaseClass): names = TestLoader.getTestCaseNames(self, testCaseClass) names = filter(testCaseClass.isSupportedTest, names) return names unittest.main(testLoader=FilteringTestLoader()) You could do something similar with a FilteringTestSuite if that fits your harness better. Kent From lambacck at gmail.com Thu Jun 2 22:39:21 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Thu, 2 Jun 2005 22:39:21 -0400 Subject: thread vs GC In-Reply-To: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> References: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> Message-ID: You probably have one or more of several problems. If a __del__ method exists, the object might be stuck in the gc.garbage list. In general you are better off explicitly stopping it my adding a method that is called to set your threading.Event. Likely you will still be stuck waiting on your queue and unable to check the status of threading.Event. Try setting a timeout on the blocking Queue.put call and then checking the status of the event. If it is set break out, otherwise go try the put again. Depending on how makeprime works, you may have to cache the value so you can keep trying to put the number in the queue. class primegen: def __init__(self): self.q = Queue.Queue(5) # cache up to 5 primes self.e = threading.Event() def background_generator(): n = makeprime() while True: try: self.q.put(makeprime(),True, 1) # sleeps if 5 primes are already cached except Queue.Full: pass else: n = makeprime() if self.e.isSet(): return threading.Thread(target=background_generator).start() def next(self): return self.q.read() def __iter__(self): return self def stop(self): self.e.set() -Chris On 02 Jun 2005 17:50:06 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Another of those "how can I kill a thread" questions. > > Let's say I have an app that needs a random prime number for something > every now and then, based on user interaction. I have a function > makeprime() which creates such a prime, but it's pretty slow, so I > don't want to wait for it when the user clicks for a new prime. I want > to generate some primes in the background and cache a few of them. Let's > say I want to make an iterator object to wrap all this: > > class primegen: > def __init__(self): > self.q = Queue.Queue(5) # cache up to 5 primes > def background_generator(): > while True: > self.q.put(makeprime()) # sleeps if 5 primes are already cached > threading.Thread(target=background_generator).start() > > def next(self): > return self.q.read() > def __iter__(self): return self > > Now I can make a caching prime stream with > > g = primegen() > > and it's all rather elegant. But maybe g will sit in some other > object or for some other reason I end up making a bunch of these > generators. The generators get cleaned up by GC when they go out of > scope, but the threads they spawn are left hanging around. > > Adding a __del__ method that sets a flag (actually threading.Event) > which the background_generator function checks doesn't seem to do > the job. > > Any suggestions for the cleanest way to get rid of the thread? I can > think of some awful kludges that I'd rather not resort to. > > Extra points if it works in both Python and Jython, i.e. it isn't GIL > dependent. > > Thanks for any ideas. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From flamesrock at gmail.com Sun Jun 5 21:40:58 2005 From: flamesrock at gmail.com (flamesrock) Date: 5 Jun 2005 18:40:58 -0700 Subject: Question about Object Oriented + functions/global vars? Message-ID: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> ok, so to my knowledge, object oriented means splitting something into the simplest number of parts and going from there. But the question is- when is it enough? For example I have the following code: #def put_file(file_id, delete=False): # """ Function to put the file on the FTP Server # """ # print "["+file_id+"] FTP for this file started" # print "[" + file_id + "] Connecting to machine " + global_addr # ftp_pool = FTP_pool(file_id,1,40,global_uid,global_pwd) # print 'in put_file' # try: # ftp = ftplib.FTP(global_addr) # ftp.login(global_uid, global_pwd) # print ftp.getwelcome() +'\n' # ftp.cwd(global_ftp_loc) ># ext = os.path.splitext(file_id)[1] ># if ext not in (".sc4", ".snpickle"): ># ftp.storlines("STOR " + file_id, open(file_id)) ># else: ># ftp.storbinary("STOR " + file_id, open(file_id, "rb"), 1024) # ftp.quit() # ftp_pool.close_all() # except: # ftp_pool.close_all() # print "[" + file_id + "]Unable to access FTP location" # print "[" + file_id + "]Error:" + str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1]) # upload_status[file_id] = "FAILED" # raise # else: # print "[" + file_id + "] FTP for file completed" # upload_status[file_id] = "SUCCESS" would the lines with '>#' best be split up into a seperate function, for example: #def upload(ftp, file): # ext = os.path.splitext(file)[1] # if ext in (".txt", ".htm", ".html"): # ftp.storlines("STOR " + file, open(file)) # else: # ftp.storbinary("STOR " + file, open(file, "rb"), 1024) and then doing the call 'upload(file_id)', or is it a better practice to leave things the way they were? I'm confused. Finally, is it considered 'un-object-oriented' in python to have functions inside a module that are called by objects (ie the upload function above) and/or use global variables in combination? -thanks in advance From leo at lspace.org Fri Jun 3 11:34:23 2005 From: leo at lspace.org (Leo Breebaart) Date: 3 Jun 2005 15:34:23 GMT Subject: tempfile.gettempdir() result on Windows Message-ID: <3gbbjvFbgg3sU1@individual.net> On MS Windows, I am trying to find out a good default location to save some temporary files. The tempfile module seemed to have exactly what I wanted: >>> import tempfile >>> tempfile.gettempdir() 'c:\\docume~1\\admini~1\\locals~1\\temp' >>> My problem (entirely cosmetic, but still) is that I also need to show this location to the users of my program, who I suspect would be much happier with a 'proper' Windows path than with this '~1' DOS malarkey. Does anybody know how I can obtain a temp directory in 'verbose' format (or somehow convert the gettempdir() result to that)? -- Leo Breebaart From nid_oizo at yahoo.com_remove_the_ Fri Jun 3 15:26:54 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 03 Jun 2005 15:26:54 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: Message-ID: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Guido van Rossum wrote: > After many rounds of discussion on python-dev, I'm inviting public > comments for PEP 343. Rather than posting the entire PEP text here, > I'm inviting everyone to read it on line > (http://www.python.org/peps/pep-0343.html) and then post comments on a > Wiki page I've created for this purpose > (http://wiki.python.org/moin/WithStatement). > > I think this is a good one; I hope people agree. Its acceptance will > obsolete about 4 other PEPs! (A sign that it fulfills a need and that > the proposed solution is powerful.) I like the PEP very much; I guess most C++ programmers are missing that capability in Python. (I was following the discussion on python-dev, and I'm pleased and surprised how good the result/compromise is). What about making the ':' optional (and end implicitly at end of current block) to avoid over-indentation? def foo(): with locking(someMutex) with opening(readFilename) as input with opening(writeFilename) as output ... would be equivalent to: def foo(): with locking(someMutex) with opening(readFilename) as input with opening(writeFilename) as output ... Regards, Nicolas From mwm at mired.org Sat Jun 4 23:29:43 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 04 Jun 2005 22:29:43 -0500 Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> Message-ID: <86slzxa3bs.fsf@guru.mired.org> Steve Holden writes: > But this would only be a restriction if the code were to be > redistributed, of course. It's stil perfectly legal to use it > internaly without making the modified source available. I've heard people argue otherwise on this case. In particular, if you allow an employee to use your GPL'ed-but-not-distributed software, they are the end user, and have all the rights granted by the GPL. So they can distribute the software - possibly to your competitors. Employment contracts can't prohibit this, because the GPL specifically disallows "distribution" (allowing your employee to use the software) under licenses that restrict the rights granted by the GPL. I don't know whether this would hold water in court. I'd certainly hate to be the one responsible for a company finding out the hard way. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From invalid at invalid.com Sun Jun 12 23:21:11 2005 From: invalid at invalid.com (copx) Date: Mon, 13 Jun 2005 05:21:11 +0200 Subject: How to use 8bit character sets? References: <1118621322.233577.107800@g14g2000cwa.googlegroups.com> Message-ID: "Chris Curvey" schrieb im Newsbeitrag news:1118621322.233577.107800 at g14g2000cwa.googlegroups.com... > Check out sitecustomize.py. > > http://diveintopython.org/xml_processing/unicode.html Thanks but I'm looking for a way to do this on application level (i.e. I want my app to run in an unmodified interpreter enviroment). copx From mauriceling at acm.org Sat Jun 18 11:10:52 2005 From: mauriceling at acm.org (Maurice LING) Date: Sun, 19 Jun 2005 01:10:52 +1000 Subject: Migrating from Windows to OS X References: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> Message-ID: ladasky at my-deja.com wrote: > Hello, fellow programmers! > > I am sitting in front of a nice new PowerBook portable which has OS > 10.4 installed. The Python.org web site says that Apple has shipped OS > 10.4 with Python 2.3.5 installed. How exactly do I access this? I > have searched through the Applications and Libraries folders. I found > the site-packages directory, but nothing other than that. > > Thanks for your help, > John Ladasky > If I recall correctly, the actual Python installation is in /System/Library/Frameworks/Python.framework but the site-package is symlinked to /Library/Python. Do not attempt to touch that. This installation can be accessed in Terminal by typing "pythonw". Are you or will you be using package managers such as darwinports or Fink? maurice From roy at panix.com Sun Jun 12 20:22:28 2005 From: roy at panix.com (Roy Smith) Date: Sun, 12 Jun 2005 20:22:28 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Andrea Griffini wrote: > I think that for a programmer skipping the > understanding of the implementation is just > impossible: if you don't understand how a > computer works you're going to write pretty > silly programs. Note that I'm not saying that > one should understand every possible implementation > down to the bit (that's of course nonsense), but > there should be no room for "magic" in a computer > for a professional programmer. How far down do you have to go? What makes bytes of memory, data busses, and CPUs the right level of abstraction? Why shouldn't first-year CS students study "how a computer works" at the level of individual logic gates? After all, if you don't know how gates work, things like address bus decoders, ALUs, register files, and the like are all just magic (which you claim there is no room for). Digging down a little deeper, a NAND gate is magic if you don't know how a transistor works or can't do basic circuit analysis. And transistors are magic until you dig down to the truly magical stuff that's going on with charge carriers and electric fields inside a semiconductor junction. That's about where my brain starts to hurt, but it's also where the quantum mechanics are just getting warmed up. > Also concrete->abstract shows a clear path; starting > in the middle and looking both up (to higher > abstractions) and down (to the implementation > details) is IMO much more confusing. At some point, you need to draw a line in the sand (so to speak) and say, "I understand everything down to *here* and can do cool stuff with that knowledge. Below that, I'm willing to take on faith". I suspect you would agree that's true, even if we don't agree just where the line should be drawn. You seem to feel that the level of abstraction exposed by a language like C is the right level. I'm not convinced you need to go that far down. I'm certainly not convinced you need to start there. From fuzzyman at gmail.com Thu Jun 9 05:05:38 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 9 Jun 2005 02:05:38 -0700 Subject: Saving/retrieving user preferences In-Reply-To: <42a78012@dnews.tpgi.com.au> References: <42a78012@dnews.tpgi.com.au> Message-ID: <1118307938.922528.106390@o13g2000cwo.googlegroups.com> ConfigObj is a nice way of reading/writing text config files. It's case insensitive and handles quoting of keywords/values. Reading and writing config files are single line commands. You get access to keyword values using a dicitionary interface. Values can be single values or lists (including nested lists if you want). Lots of other options. http://www.voidspace.org.uk/python/configobj.html Regards, Fuzzy http://www.voidspace.org.uk/python/ From skip at pobox.com Wed Jun 1 23:25:25 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Jun 2005 22:25:25 -0500 Subject: PySol not working on WinXP, SP2 In-Reply-To: <429E2464.42EF8539@pauahtun.org> References: <429DC8F7.38AFB2B5@pauahtun.org> <429E2464.42EF8539@pauahtun.org> Message-ID: <17054.31781.461678.239330@montanaro.dyndns.org> Ivan> Nope. The pyc files don't match the py files, and he imports the Ivan> pyc files directly. That's what 'imp.load_compiled("__main__", Ivan> sys.argv[0])' means. The windows version that Markus shipped Ivan> never included the .py files anyway, since he didn't need them. Ivan, It's not as slick as Brian Lenihan's OSX package, but all I needed was the sound package (seems you have that), the raw source and the data directory from a not-to-old PySol distribution to get going. Until I downloaded Brian's package this evening I just ran from source using Python from CVS. I imagine you could do the same on Windows with Python 2.3 or 2.4. Ivan> I can get it working eventually, I suppose, but I was really Ivan> hoping someone else had done the work already, or at least had Ivan> pointers to docs on how to get it working. Here's my "pysol" command: #!/bin/bash cd ~/src/pysol-4.82/src pythonw pysol.py I'd be happy to package up a tar or zip file for you with a couple notes on installing it. Skip From dan at nospam.com Wed Jun 22 12:55:00 2005 From: dan at nospam.com (Dan) Date: Wed, 22 Jun 2005 11:55:00 -0500 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: On 6/22/2005 11:38 AM, Thomas Bartkus wrote: > Will McGugan" wrote in message > news:42b97240$0$24467$da0feed9 at news.zen.co.uk... > >>Hi, >> >>I'd like to write a windows app that accesses a locally stored database. >>There are a number of tables, the largest of which has 455,905 records. >> >>Can anyone recommend a database that runs on Windows, is fast / >>efficient and can be shipped without restrictions or extra downloads? >> >>I have googled and found plenty of information on databases, its just >>that I dont have enough experience with databases to know which one is >>best for my task! > > > If you are writing strictly for the MS Windows platform > And > If the database is running single user with a "locally stored database" on a > Windows workstation. > Then > The MS Access file based (.mdb) system is hard to argue with. > You wouldn't have to distribute the (rather expensive) Access application > since this is little more than a front for the underlying DAO/ADO database > libraries that are built into the warp and woof of MS Windows. Your Python > application can address the DAO or ADO directly as these will libraries will > be pre-installed and/or freely available for MS Windows. Fast, freely > available, no license restrictions, and no need for extra downloads for a > reasonably recent (Win2000, XP) operating system. > And then XP Autoupdate executes, some of those Access/MSDE libraries are updated, and you app is broken. From greg_miller at nexpress.com Wed Jun 29 07:02:23 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 29 Jun 2005 04:02:23 -0700 Subject: COM problem .py versus .exe References: Message-ID: <1120042943.163591.25860@g14g2000cwa.googlegroups.com> The two machines are both running Windows XP, the desktop is running XP Pro, the "virgin" PC is running XP embedded. I would say the biggest difference is that the embedded machine has only the py2exe executable running/installed, while the desktop has the full python24 installation. I get no build errors when compiling the executable, and all other parts of the application run correctly. I'll try the non-installed moveable python and see what happens. The idea of the executable is that in the machines first release, we didn't have time to work the bugs out of the executable, so we released with the python code ( pyc's ) intact. I didn't have this problem on the first release as we weren't interested in displaying the file version of the .dll. With this improved version of the product the request has come down to have all software package versions displayed, so that is why I am now attempting to extract the file version of the dll. Thanks again for everyone's assistance................. From bulliver at badcomputer.org Fri Jun 3 06:42:32 2005 From: bulliver at badcomputer.org (darren kirby) Date: Fri, 3 Jun 2005 03:42:32 -0700 Subject: Formatting Time In-Reply-To: <42A014F5.40308@mailshack.com> References: <42A014F5.40308@mailshack.com> Message-ID: <200506030342.38043.bulliver@badcomputer.org> quoth the Ognjen Bezanov: > I never thought id need help with such a thing as time formatting > (admittadly i never did it before) but ok, i guess there is a first for > everything. > > I have a float variable representing seconds, and i want to format it > like this: > > 0:00:00 (h:mm:ss) > > Now search as I might i am finding this quite elusive, i had a look at > the time module but that seems overly complicated for this. Anyone got > any simple solutions to doing this? cheers! def printTime(seconds): hours = seconds / 3600 seconds = seconds - (hours * 3600) minutes = seconds / 60 seconds = seconds - (minutes * 60) print "%i:%s:%s" % (hours, str(minutes).zfill(2), str(seconds).zfill(2)) I am certainly no pro at python but this seems to do it for me. I am sure someone could write it much more elegantly. I am still a little confused as to how you have a float that represents seconds? This will only work if 'seconds' is an int ( al la ' 44342865') but maybe it could help you? -d -- darren kirby :: Part of the problem since 1976 :: http://badcomputer.org "...the number of UNIX installations has grown to 10, with more expected..." - Dennis Ritchie and Ken Thompson, June 1972 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From grig.gheorghiu at gmail.com Fri Jun 10 23:52:51 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 10 Jun 2005 20:52:51 -0700 Subject: Sending mail from 'current user' in Python In-Reply-To: <3gsve7Fe8957U1@individual.net> References: <3gsve7Fe8957U1@individual.net> Message-ID: <1118461971.461936.327550@g14g2000cwa.googlegroups.com> I use this function as a platform-independent way of finding out the current user name: def get_username(): if sys.platform == 'win32': return win32api.GetUserName() else: return getpass.getuser() From noreply at gcgroup.net Wed Jun 22 12:27:06 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 22 Jun 2005 16:27:06 GMT Subject: a comprehensive Tkinter document? In-Reply-To: <42b98634_2@newspeer2.tds.net> References: <42b98634_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > William Gill wrote: > >> I know a major problem I am having is that I am finding lots of >> Tkinter information in 'fragments' of various , sometimes conflicting >> vintages. For example the python reference I was using didn't show >> the '%%' as an escape sequence, I posted asking how to escape the '%' >> and after several helpful responses voila I found a more complete >> table of escape sequences. Is there a comprehensive document or book >> that I can get that is relatively current? > > > Maybe not comprehensive but I think reasonably current: > http://www.pythonware.com/library/tkinter/introduction/index.htm > http://infohost.nmt.edu/tcc/help/pubs/tkinter/ > > Kent Yes, these are two of my staples, though I have occasionally slipped into 'copies' elsewhere that aren't kept up. Thanks, Bill From darkpaladin79 at hotmail.com Mon Jun 6 19:00:23 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 19:00:23 -0400 Subject: Creating file of size x In-Reply-To: <42A4D458.2020604@gmail.com> Message-ID: What version of python do you use? I'll send you the module library. . .(sorry for double message) -Ivan _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From richardlewis at fastmail.co.uk Mon Jun 20 11:24:51 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Mon, 20 Jun 2005 16:24:51 +0100 Subject: Python choice of database In-Reply-To: References: Message-ID: <1119281091.23911.236755467@webmail.messagingengine.com> On Mon, 20 Jun 2005 15:18:58 GMT, "Philippe C. Martin" said: > Hi, > > I am looking for a stand-alone (not client/server) database solution for > Python. > > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K > SQLite might be worth a look. There are Python bindings at: http://initd.org/tracker/pysqlite Cheers, Richard From cam.ac.uk at mh391.invalid Fri Jun 17 03:40:18 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 17 Jun 2005 08:40:18 +0100 Subject: Unbound names in __del__ In-Reply-To: References: Message-ID: Torsten Bronger wrote: > When my __del__ methods are called because the program is being > terminated, I experience difficulties in calling functions that I > need for a clean shutdown of my instances. So far, there has been > only one of these functions, and a class-local alias solved the > problem. However, now there are many of them. __del__ is messy and I avoid it whenever possible. Make sure you read all the caveats and warnings on these pages: http://www.python.org/doc/ref/customization.html http://www.python.org/doc/lib/module-gc.html Most importantly, "It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits." > Or do you know a cleaner solution? For example, if I have > > import vpp43 > > would it help to say > > def __init__(self): > __vpp43 = vpp43 > ... > > to guarantee that I can access all the routines in vpp43 in the > __del__ method? A similar idiom is found in the standard library (e.g. tempfile.py): # Cache the unlinker so we don't get spurious errors at # shutdown when the module-level "os" is None'd out. Note # that this must be referenced as self.unlink, because the # name TemporaryFileWrapper may also get None'd out before # __del__ is called. unlink = _os.unlink def close(self): if not self.close_called: self.close_called = True self.file.close() self.unlink(self.name) def __del__(self): self.close() -- Michael Hoffman From xah at xahlee.org Sat Jun 18 03:19:11 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jun 2005 00:19:11 -0700 Subject: functions with unlimeted variable arguments... Message-ID: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> how can i define a function with variable parameters? For example, f(a) would return [a] f(a,b) would return [a,b] f(a,b,...) would return [a,b,...] One solution is of course to make the argument as a list. i.e. f([a,b,...]) but are there other solutions? Xah xah at xahlee.org ? http://xahlee.org/ From rune.strand at gmail.com Mon Jun 20 18:51:19 2005 From: rune.strand at gmail.com (Rune Strand) Date: 20 Jun 2005 15:51:19 -0700 Subject: reading a list from a file References: <223874235.UzX6FoQtyG@teancum> <1119305164.006906.133590@z14g2000cwz.googlegroups.com> <1119306766.673306.220350@z14g2000cwz.googlegroups.com> Message-ID: <1119307879.606696.238410@g49g2000cwa.googlegroups.com> But iif it are many lists in the file and they're organised like this: ['a','b','c','d','e'] ['a','b','c','d','e'] ['A','B','C','D','E'] ['X','F','R','E','Q'] I think this'll do it data = open('the_file', 'r').read().split(']') lists = [] for el in data: el = el.replace('[', '').strip() el = el.replace("'", "") lists.append(el.split(',')) # further processing of lists but the type problem is still to be resolved ;-) From oddr at home.no.no Tue Jun 28 10:45:19 2005 From: oddr at home.no.no (Odd-R.) Date: 28 Jun 2005 14:45:19 GMT Subject: Dictionary to tuple Message-ID: I have a dictionary, and I want to convert it to a tuple, that is, I want each key - value pair in the dictionary to be a tuple in a tuple. If this is the dictionary {1:'one',2:'two',3:'three'}, then I want this to be the resulting tuple: ((1,'one'),(2,'two'),(3,'three')). I have been trying for quite some time now, but I do not get the result as I want it. Can this be done, or is it not possible? I must also add that I'm new to Python. Thanks in advance. -- Har du et kj?leskap, har du en TV s? har du alt du trenger for ? leve -Jokke & Valentinerne From kristian.zoerhoff at gmail.com Wed Jun 1 13:27:54 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Wed, 1 Jun 2005 12:27:54 -0500 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117644113.523658.173830@g43g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> Message-ID: <3511dc75050601102729c52154@mail.gmail.com> On 1 Jun 2005 09:41:53 -0700, infidel wrote: > Why in the name of all that is holy and just would you need to do such > a thing? Is anyone else amused that this came from the mouth of someone named "Infidel"? -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From flyingfred0 at gmail.com Thu Jun 9 21:50:57 2005 From: flyingfred0 at gmail.com (flyingfred0) Date: Fri, 10 Jun 2005 01:50:57 GMT Subject: DB API 2.0 and transactions In-Reply-To: References: Message-ID: <5m6qe.1736$pa3.1392@newsread2.news.atl.earthlink.net> I've found it's occasionally necessary to go one lever deeper and use the _pg module directly so you are in control of your transactions (instead of letting pgdb automatically put you in one). vincent wehren wrote: > "Christopher J. Bottaro" schrieb im > Newsbeitrag news:mailman.92.1118167102.10512.python-list at python.org... > | Hi, > | Why is there no support for explicit transactions in the DB API? I mean > | like transaction() to start the trans and commit() and rollback() would > end > | the trans or something. > | > | The reason why I ask is because I wrote a daemon that interacts with a > | Postgres DB. The value of CURRENT_TIMESTAMP according to Postgres is NOT > | the actual walltime, but the walltime when the current transaction > started. > | > | This gets weird when using the Python DB API to interact with Postgres > | because a transaction gets started in 3 places: connection, commit, > | rollback. > | > | So consider the daemon: > | > | [pseudo code] > | connect # begin trans at 12:00 > | sleep waiting # lets say 15 mins > | wake up > | put entry in db using CURRENT_TIMESTAMP # oops > | [/code] > | > | Oops, the CURRENT_TIMESTAMP evaluates to 12:00, not 12:15. > | > | Now I know there are ways around this... > | 1) In Postgres, you can get the walltime and cast it to a timestamp. > | 2) In Python, you can just do an empty commit in order to "manually" > start > | a new transaction. > | > | I just think its a bit weird because this bit me in the butt for quite a > | while and this didn't happen when doing the same thing in other langs. > | > | Anyone have any opinions on this? > > The described behavior seems to be totally in synch with expectations > > (both in accordance with PostgreSQL docs and the DB-API.) > > These "other languages" *must* be doing something wrong! ;) > > ( Auto-commit set to "on" perhaps? ) > > > > Regards, > > - > > Vincent Wehren > > > | > > > From facundobatista at gmail.com Sat Jun 4 17:19:38 2005 From: facundobatista at gmail.com (Facundo Batista) Date: Sat, 4 Jun 2005 18:19:38 -0300 Subject: decimal and trunkating In-Reply-To: <1117780492.437558.242370@g47g2000cwa.googlegroups.com> References: <1117780492.437558.242370@g47g2000cwa.googlegroups.com> Message-ID: On 2 Jun 2005 23:34:52 -0700, Raymond Hettinger wrote: > >> i want to trunkate 199.999 to 199.99 > >> getcontext.prec = 2 isn't what i'm after either, all that does > >> is E's the value. do i really have to use floats to do this? > > The precision is the total number of digits (i.e 199.99 has 5 digit > precision). Either round to that precision level or use the quantize > method to round to a fixed number of places after the decimal point: God, I must stop sending mails at 2AM. I replied doing the remark that some burden should be taken at the beggining of the program, and I repeated that mistake, confusing everybody. Sorry, :( . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From danricofer at gmail.com Fri Jun 10 11:08:27 2005 From: danricofer at gmail.com (Daniel) Date: 10 Jun 2005 08:08:27 -0700 Subject: Changing entities In-Reply-To: <42a6ed6e$1_1@newspeer2.tds.net> References: <1118235783.224018.281490@g44g2000cwa.googlegroups.com> <42a6ed6e$1_1@newspeer2.tds.net> Message-ID: <1118416106.992079.196560@g47g2000cwa.googlegroups.com> Hi Kent This isn't work with the following line: FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 BYTES) >>> byter = re.compile(r'SIZE \((\d+) BYTE\)') >>> s = 'SIZE (1 BYTE)' >>> byter.sub(r'SIZE(\1)', s) 'SIZE(1)' >>> byter.sub(r'SIZE(\1)', line) 'FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 BYTES)' >>> line 'FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 BYTES)' >>> Any idea? :-p From steve at REMOVETHIScyber.com.au Thu Jun 16 19:30:05 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 17 Jun 2005 09:30:05 +1000 Subject: Set of Dictionary References: <4660fe3005061608023c4f96ab@mail.gmail.com> <20050616160959.34219.qmail@web53910.mail.yahoo.com> Message-ID: On Thu, 16 Jun 2005 21:21:50 +0300, Konstantin Veretennicov wrote: > On 6/16/05, Vibha Tripathi wrote: >> I need sets as sets in mathematics: > > That's tough. First of all, mathematical sets can be infinite. It's > just too much memory :) > Software implementations can't fully match mathematical abstractions. :-) But lists can be as long as you like, if you have enough memory. So can longs and strings. So I don't think the infinity issue is a big one. >> sets of any unique type of objects including those >> of dictionaries, I should then be able to do: >> a_set.__contains__(a_dictionary) and things like that. Standard Set Theory disallows various constructions, otherwise you get paradoxes. For example, Russell's Paradox: the set S of all sets that are not an element of themselves. Then S should be a set. If S is an element of itself, then it belongs in set S. But if it is in set S, then it is an element of itself and it is not an element of S. Contradiction. The price mathematicians pay to avoid paradoxes like that is that some sets do not exist. For instance, there exists no universal set (the set of all sets), no set of all cardinal numbers, etc. So even in mathematics, it is not true that sets can contain anything. > Maybe you can use a list for that: > >>>> d1 = {1: 2} >>>> d2 = {3: 4} >>>> s = [d1, d2] >>>> {1: 2} in s > True >>>> {5: 6} in s > False > >> Can sets in Python 2.4.1, be reimplemented from >> scratch to not have it work on top of dict? > > Sure, why not? Take a close look at the sets module, written in Python. You could copy and modify the source code (taking care to obey whatever licencing restrictions, if any, there are). -- Steven From hancock at anansispaceworks.com Sun Jun 19 23:02:04 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 19 Jun 2005 22:02:04 -0500 Subject: Extensions on Linux: import without underscore? In-Reply-To: References: Message-ID: <200506192202.04087.hancock@anansispaceworks.com> On Saturday 18 June 2005 10:35 pm, James Carroll wrote: > Hi, I'm creating an extension called _bright.so on linux. I can > import it with import _bright, but how can I import bright and get the > package? > > On windows, I've been able to import bright instead of import _bright, > but on Linux it seems to need the underscore. I'm tempted to create a > bright.py with from _bright import *, but I'm wondering if there's a > more direct way. Okay, you may want a more elegant way to do this and other people have already responded to that point, but you do at least know you can just give it a new name: import _bright bright = _bright right? You can attach a new name to any Python object trivially (this is akin to a pointer assignment in C, it does not copy any significant amount of data). -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From peter at engcorp.com Tue Jun 14 09:21:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 09:21:11 -0400 Subject: Where is Word? In-Reply-To: References: Message-ID: Guy Lateur wrote: > My original post is called "Start application & continue after app exits". > Is there a better way to refer to past posts, btw? No, the subject is a good way to refer to past posts. I just meant forcing us to dig back, when the post may no longer even be on our servers, is not helpful. > I want to make a temporary file (directory listing), open it in Word to let > the user edit, layout and print it, and then delete the temp file > afterwards. I don't think we'll be able to fully automate it, though. The > user should be able to set her own fonts and stuff. I understand now. Definitely if you are doing this to allow customizing fonts and such, at the user's whim, you can't automate it, by definition... (Perhaps I should ask why anyone would want to waste time putting arbitrary fonts and colours and such around a simple directory listing, but I won't. ) -Peter From danb_83 at yahoo.com Thu Jun 9 23:10:35 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Jun 2005 20:10:35 -0700 Subject: Is pyton for me? References: Message-ID: <1118373035.311897.141300@g47g2000cwa.googlegroups.com> Mark de+la+Fuente wrote: > I need to write simple scripts for executing command line functions. Up till > now I've used C-Shell scripts for this, but I'm looking for a better > alternative. And I keep reading about how "easy" it is to program with > python. > > Unfortunately after reading "diveintopython" and the python tutorial, I'm not > sure how to do what I need to do. > > Here is an example of the type of thing I would like to be able to do. > Can I do this with python? How do I get python to execute command line > functions? import os os.system('gensky 3 21 12 > sky.rad') From kay.schluehr at gmx.net Fri Jun 10 09:57:19 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Jun 2005 06:57:19 -0700 Subject: Abstract and concrete syntax References: Message-ID: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Mandus schrieb: > As someone who like to do functional style programming, but without a > lot of training in that dept., I miss what you ask for from time to > time. > > I don't want to go to much into this discussion, just comment on a tiny > little bit: > > Thu, 09 Jun 2005 03:32:12 +0200 skrev David Baelde: > [snip] > > > > set_callback(obj, > > lambda x: (if a: > > 2 > > else: > > 3) > > > [snip] > > You can do stuff like this: lambda x: x and 2 or 3 You can also do this lambda x: {True:2,False:3}.get(bool(a)) which is both beautiful and pythonic. Kay From sjmachin at lexicon.net Mon Jun 20 19:58:16 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 21 Jun 2005 09:58:16 +1000 Subject: reading a list from a file In-Reply-To: <1119307879.606696.238410@g49g2000cwa.googlegroups.com> References: <223874235.UzX6FoQtyG@teancum> <1119305164.006906.133590@z14g2000cwz.googlegroups.com> <1119306766.673306.220350@z14g2000cwz.googlegroups.com> <1119307879.606696.238410@g49g2000cwa.googlegroups.com> Message-ID: <42B75818.3090901@lexicon.net> Rune Strand wrote: > But iif it are many lists in the file and they're organised like this: > > ['a','b','c','d','e'] > ['a','b','c','d','e'] > ['A','B','C','D','E'] ['X','F','R','E','Q'] > > I think this'll do it > > data = open('the_file', 'r').read().split(']') > > lists = [] > for el in data: > el = el.replace('[', '').strip() > el = el.replace("'", "") > lists.append(el.split(',')) > > # further processing of lists > > but the type problem is still to be resolved ;-) > Try this: ["O'Reilly, Fawlty, and Manuel", '""', ',', '"Hello", said O\'Reilly'] :-) From phm4 at kent.ac.uk Thu Jun 30 07:30:06 2005 From: phm4 at kent.ac.uk (Philipp H. Mohr) Date: Thu, 30 Jun 2005 12:30:06 +0100 (BST) Subject: Store multiple dictionaries in a file In-Reply-To: <42c3cccd$0$12707$626a14ce@news.free.fr> References: <42c3cccd$0$12707$626a14ce@news.free.fr> Message-ID: Thank you for you answer. > > I would like to store multiple dictionaries in a file, if possible one per > > line. > > Why "one per line" ? I agree with you that it sounds like nasty code :-) but there is a good reason for doing it this way - I think. My code collects data (attributes) of its current environment, e.g. date, time, location, etc. These values are put into a dictionary and passed to another program which processes the data. The dictionary (or vector of attributes) is the only interface between both progs. The one which creates the dictionary can forget about it after it has passed it on. This is where the storing comes into action. In order to be able to re-run an experiment I want to store the dictionaries in a file. Also the program might not run continuasly, therefore if I write all of them to a file, on after the other, I would be able to re-run the experiment much easier. Hope this makes sense. Thank you, Phil > > A pretty simple solution could be to store all the dicts in another > container (list or dict, depending on how you need to retrieve'em, but > from what you explain I'd say a list) and then pickle this container. From nyamatongwe+thunder at gmail.com Sun Jun 5 22:55:15 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 06 Jun 2005 02:55:15 GMT Subject: GUI builders considered harmful (Was: anygui, anydb, any opinions?) In-Reply-To: <86fyvwa91z.fsf_-_@guru.mired.org> References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> <86fyvwa91z.fsf_-_@guru.mired.org> Message-ID: Mike Meyer: > The obvious solution would be for the system to detect all these > environmental factors, and scale the applications > accordingly. However, things like viewing distance and the quality of > my eyesight are hard to detect automatically, and it would be a pain > to have to enter all those things manually. Since the end result of > all these is a single factor - a UI scale factor - a system wide knob > to scale applications would seem to be the solution. Treating scalability as a matter of magnification is problematic. User interfaces consist of a mixture of smoothly magnifiable and discrete aspects. Pixels are discrete (well, almost) and sometimes, such as at the edge of a button, you need to be able to control whole pixels to ensure that you get a visible transition rather than a blur. Text is often unreadable under a certain size so that places a lower bound under magnification. Often when scaling down, you want to remove elements or move them onto extra pages or pop-ups. This sort of change generally requires human intelligence. The toolkit I am most familiar that does try to be magnifiable is Windows.Forms and it is also my least favourite currently having particularly ugly text. To achieve resolution independence Windows.Forms (and the underlying GDI+) uses sub-pixel positioning as do other recent rendering libraries. This leads to the possibility of each render of a particular character being different. For example, in a text editor, if the font height is 10.5 pixels then two assignment lines x = 1 y = 0 may display the first '=' legibly with one black line, one white line and another black line but the second line, offset by .5 pixels will show a 4 pixel high grey rectangle. Forcing the '=' onto the pixel grid will distort the text appearance. Neil From jzgoda at gazeta.usun.pl Thu Jun 2 17:41:30 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 02 Jun 2005 23:41:30 +0200 Subject: (OT) lincense protection generator In-Reply-To: References: Message-ID: flupke napisa?(a): > I'm thinking of a function that will generate such a code and put it in > a file. Then when the program starts it checks this file and checks the > code in there with a code that it generates at that time again based for > instance on the current directory and other components unique to that > computer. It could be a long string (but what info?) and then take a > hash from it and store the hash value. Better, generate sha1 sum of general machine configuration (i.e. what "set" command returns) and store it on random internet node. You can be sure nobody would get it. Anyway, it's bad idea. Restrict program usage in license) or any other contract), but don't do such a mess to people who pay your bills. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From gatti at dsdata.it Tue Jun 28 04:10:39 2005 From: gatti at dsdata.it (gatti at dsdata.it) Date: 28 Jun 2005 01:10:39 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <1119946239.413507.93080@g44g2000cwa.googlegroups.com> Ivan Van Laningham wrote: [...] > > Seriously, PostScript is a lot more fun to learn than Forth, and more > directly useful. Since the rewards are so immediate, a kid's attention > could be gained and kept pretty easily. PostScript is easy, but I'm afraid some technical details could get in the way of enjoyable exploration, e.g. font types or scaling. PostScript is also a single purpose language: it can print static graphics and with a slightly more complex setup it can display static graphics on the screen, period. No interactivity, no files, no network, no general computation or data structures. > But I'd still recommend Python as a first programming language. Keep to > the standard stuff--ignore list comprehensions and so on--until he or > she has the basic control flow down pat. Python is general purpose; it can do graphics with a path/stroke model like Postscript's and a whole world of other things. There are many complex features in Python that shouldn't be introduced before the need arises. List comprehensions, however, *are* the basic control flow; loops are much more verbose and they should be used only when necessary. Lorenzo Gatti From paulm at barley.vel.net Thu Jun 30 19:00:33 2005 From: paulm at barley.vel.net (paulm) Date: Thu, 30 Jun 2005 18:00:33 -0500 Subject: Newbie backreference question References: <42C463F4.2040005@syscononline.com> <1120171065.884074.216240@z14g2000cwz.googlegroups.com> Message-ID: George Sakkis wrote: > > Did you have a look at my other reply ? It's still the same, just > change the regexp: > > import re > a = 'test string two' > b = re.match(r'test \w{2}(.+)', a, re.DOTALL).group(1) > print b > > By the way, if you want to catch any single character (including new > lines), '.' with re.DOTALL flag is more clear than [\W\w]. > > George > Of course, this is the answer I need. I've been futzing around with \1 and such without much luck. I'm still thinking a bit too perlishly. :) Thanks again, all! From Sebastien.Boisgerault at gmail.com Wed Jun 15 09:08:47 2005 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 15 Jun 2005 06:08:47 -0700 Subject: FAQ: __str__ vs __repr__ In-Reply-To: <1118840774.643768.218300@o13g2000cwo.googlegroups.com> References: <42b021ba$1@griseus.its.uu.se> <1118840774.643768.218300@o13g2000cwo.googlegroups.com> Message-ID: <1118840927.552679.233620@o13g2000cwo.googlegroups.com> Errata: >>> str(0.1) '0.1' >>> str("it's a bad idea") "it's a bad idea" >>> repr(0.1) ' 0.10000000000000001' >>> repr("it's a bad idea") '"it\'s a bad idea"' SB From drool.galz at gmail.com Fri Jun 24 05:38:46 2005 From: drool.galz at gmail.com (Aditi) Date: 24 Jun 2005 02:38:46 -0700 Subject: suggestions invited In-Reply-To: References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119552092.000448.10230@g47g2000cwa.googlegroups.com> <1119555027.087947.100970@g43g2000cwa.googlegroups.com> Message-ID: <1119605926.749701.164010@g47g2000cwa.googlegroups.com> Konstantin Veretennicov wrote: > Pardon me, is it a real company or a fictious one? I think my previous mail was in plain understandable english which can be easily interpreted and clearly says the project has been assigned in a not so intelligent spirit and thus sounds fictitious. I think going through a problem before trying to reply is also a good idea. > If you have real users, your first step is to talk to them to define > project goals. Everything else (xml, python, etc.) is irrelevant until > you know *what* you want to build. Had this been possible I would not have posted the problem at all. > Go talk to your potential users, know why (if at all) they need this > monitoring system, learn their current tools and processes, see how > your system could help them do their job more efficiently. Don't start > coding until you have clear understanding of requirements. > There are lots of nice intelligent people on this list, but they can't > substitute people you are building this system for :) Nice and intelligent people on this list and many other lists have helped my by giving some suggestions and sharing their knowledge ...others who have not understood the problem can continue thinking that they are also nice and intelligent. (:-)) Regards. Aditi. From deets at web.de Sun Jun 19 17:48:49 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 19 Jun 2005 23:48:49 +0200 Subject: calling subclass constructor question In-Reply-To: References: Message-ID: <3hm7i3FhnalsU1@uni-berlin.de> In Han Kang wrote: > Hello everyone and thank you for being such a good community. > > Anyway, I was wondering...I have an super class which is the superclass > for 5 other classes. However, I want to be able to call the subclass > constructors from the super class. Is this possible? If you have a subclass, it's constructor is called - so why do you want to call it again ? It smells after bad design here - you might consider providing more dtail on the problem you want to solve by this, thus we might be able to suggest a more viable solution (or actually, a solution at all...) Diez From jarausch at skynet.be Sat Jun 25 11:17:36 2005 From: jarausch at skynet.be (Helmut Jarausch) Date: Sat, 25 Jun 2005 17:17:36 +0200 Subject: regex question In-Reply-To: <3i59q5Fjm0hsU1@individual.net> References: <3i59q5Fjm0hsU1@individual.net> Message-ID: <42BD7590.7070107@skynet.be> Felix Schwarz wrote: > Hi all, > > I'm experiencing problems with a regular expression and I can't figure > out which words I use when googling. I read the python documentation for > the re module multiple times now but still no idea what I'm doing wrong. > > What I want to do: > - Extract all digits (\d) in a string. > - Digits are separated by space (\w) > > What my program does: > - It extracts only the last digit. > > Here is my program: > import re > line = ' 1 2 3' > regex = '^' + '(?:\s+(\d))*' + '$' > match = re.match(regex, line) > print "lastindex is: ",match.lastindex > print "matches: ",match.group(1) > > > Obviously I do not understand how (?:\s+(\d))* works in conjunction with > ^ and $. > I am sure what you like to do. What about regex= re.compile('\s+\d') print regex.findall(line) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From rune.strand at gmail.com Wed Jun 29 00:00:47 2005 From: rune.strand at gmail.com (Rune Strand) Date: 28 Jun 2005 21:00:47 -0700 Subject: How to find Windows "Application data" directory?? In-Reply-To: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> Message-ID: <1120017647.696243.154880@f14g2000cwb.googlegroups.com> You have the environment variable APPDATA. You can access it with os.environ(). From lycka at carmen.se Tue Jun 14 06:10:28 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 14 Jun 2005 12:10:28 +0200 Subject: Generating HTML from python In-Reply-To: References: Message-ID: <42AEAD14.3090206@carmen.se> Philippe C. Martin wrote: > I now need to generate the HTML wxHtmlEasyPrinting can print: I need to have > a title followed by lines of text that do not look too ugly. If possible I > would like to use an existing module. How to do this really depends on what your data looks like, and how you get it. E.g. if you just want uniform pages with paragraphs of plain texts with headings in between, you can just make a template HTML file with the main block of text replaced with %s, and then do something like: text = [] for heading, paragraph in data_source: text.append('

%s

' % heading) text.append(paragraph) templ = open('template.html').read() print templ % '\n'.join(text) If your data has more structure, you might find a tool like Fredrik Lundh's elementtree useful. From rbt at athop1.ath.vt.edu Thu Jun 16 09:31:52 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 16 Jun 2005 09:31:52 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <42af1b28$0$10131$626a14ce@news.free.fr> References: <42af1b28$0$10131$626a14ce@news.free.fr> Message-ID: <1118928712.18452.15.camel@athop1.ath.vt.edu> On Tue, 2005-06-14 at 19:51 +0200, Gilles Lenfant wrote: > rbt a ?crit : > > Here's the scenario: > > > > You have many hundred gigabytes of data... possible even a terabyte or > > two. Within this data, you have private, sensitive information (US > > social security numbers) about your company's clients. Your company has > > generated its own unique ID numbers to replace the social security numbers. > > > > Now, management would like the IT guys to go thru the old data and > > replace as many SSNs with the new ID numbers as possible. You have a tab > > delimited txt file that maps the SSNs to the new ID numbers. There are > > 500,000 of these number pairs. What is the most efficient way to > > approach this? I have done small-scale find and replace programs before, > > but the scale of this is larger than what I'm accustomed to. > > > > Any suggestions on how to approach this are much appreciated. > > Are this huge amount of data to rearch/replace stored in an RDBMS or in > flat file(s) with markup (XML, CSV, ...) ? > > -- > Gilles I apologize that it has taken me so long to respond. I had a hdd crash which I am in the process of recovering from. If emails to rbt at athop1.ath.vt.edu bounced, that is the reason why. The data is in files. Mostly Word documents and excel spreadsheets. The SSN map I have is a plain text file that has a format like this: ssn-xx-xxxx new-id-xxxx ssn-xx-xxxx new-id-xxxx etc. There are a bit more than 500K of these pairs. Thank you, rbt From Steve.Coates at smiths-aerospace.com Fri Jun 3 06:17:57 2005 From: Steve.Coates at smiths-aerospace.com (Coates, Steve (ACHE)) Date: Fri, 3 Jun 2005 04:17:57 -0600 Subject: Formatting Time Message-ID: <3082C9F9373DAD43918C64BAC1CF038CE286F8@COSSMGMBX04.EMAIL.CORP.TLD> > -----Original Message----- > From: Ognjen Bezanov [mailto:ognjen at mailshack.com] > Sent: 03 June 2005 09:30 > To: python-list at python.org > Subject: Formatting Time > > I never thought id need help with such a thing as time > formatting (admittadly i never did it before) but ok, i guess > there is a first for everything. > > I have a float variable representing seconds, and i want to > format it like this: > > 0:00:00 (h:mm:ss) > > Now search as I might i am finding this quite elusive, i had > a look at the time module but that seems overly complicated > for this. Anyone got any simple solutions to doing this? cheers! > c:\Python24\programs>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> t=36100.0 >>> time.strftime('%H:%M:%S',time.gmtime(t)) '10:01:40' >>> Steve ****************************************** The information contained in, or attached to, this e-mail, may contain confidential information and is intended solely for the use of the individual or entity to whom they are addressed and may be subject to legal privilege. If you have received this e-mail in error you should notify the sender immediately by reply e-mail, delete the message from your system and notify your system manager. Please do not copy it for any purpose, or disclose its contents to any other person. The views or opinions presented in this e-mail are solely those of the author and do not necessarily represent those of the company. The recipient should check this e-mail and any attachments for the presence of viruses. The company accepts no liability for any damage caused, directly or indirectly, by any virus transmitted in this email. ****************************************** From lee at example.com Sat Jun 25 11:48:41 2005 From: lee at example.com (Lee Harr) Date: Sat, 25 Jun 2005 15:48:41 GMT Subject: BaseHTTPServer and priviledge separation? References: <42bd7671$0$341$ba620e4c@news.skynet.be> Message-ID: > to use a port below 1000 on a Unix system one needs root priviledges. > But it's dangerous to execute all of a script under those priviledges. > Therefore I'd like to drop the root priviledges as soon as possible. > (How) is this possible? > Are you sure you don't just want to use twisted? http://twistedmatrix.com/ It is a bit more complex to start, but for just serving web pages it may actually be simpler. Plus you get a lot of extra functionality built in (like dropping privelege and chroot). Looking at the code for twistd, they use os.setuid and os.setgid From hancock at anansispaceworks.com Sat Jun 11 00:23:22 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Jun 2005 23:23:22 -0500 Subject: circular import Module In-Reply-To: References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Message-ID: <200506102323.22413.hancock@anansispaceworks.com> On Friday 10 June 2005 07:27 am, Magnus Lycka wrote: > ajikoe at gmail.com wrote: > > I have two modules (file1.py and file2.py) > > Is that ok in python (without any weird implication) if my module > > import each other. I mean in module file1.py there exist command import > > file2 and in module file2.py there exist command import file1? > > Even if it works, it gives you a hint of a design > problem that might come back and bite you later. > > If file1 depends on file2 *and* vice versa, it seems > those two modules are tightly coupled. Perhaps they > should be one module rather than two, or perhaps > some redesign should be made to untangle this cycle. True in principle, but what if the resulting module is 1000 lines long? It doesn't happen often, because python programs don't usually get that complicated (e.g. lots of tightly interacting classes), but there are enough exceptions to make it seem desireable to have modules divided only for readability (i.e. logically the same module). I can only think of one way to pull this off at present, though, and that is to create a package: big_package/ __init__.py mod1.py mod2.py mod3.py where __init__.py looks something like: from mod1 import * from mod2 import * from mod3 import * Then you treat "big_package" as the module to import. You'll still have problems with names that need to be global to all three modules (I think they'd have to be in __init__.py or possibly in mod1 in order to work correctly), but it's pretty close. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ville at spammers.com Wed Jun 22 05:06:39 2005 From: ville at spammers.com (Ville Vainio) Date: 22 Jun 2005 12:06:39 +0300 Subject: *Python* Power Tools References: <42b8a85d$1@news.eftel.com> Message-ID: >>>>> "John" == John Machin writes: John> For windows users, apart from cygwin, there are a couple of John> sources of binaries for *x command-line utilities (unxutils, John> gnuwin32). unxutils is my personal favourite - cygwin is way too much an "environment", and gets broken too easily. I for one would like to see various shell tools implemented in pure python, if only to be able to import them as a module and use cross platform tools that have more power than e.g. 'shutil' or 'os' functions. The API exposed through the module (as opposed to normal execution from shell) could also be much richer, providing hooks for calling own stuff for just-in-time error handling, progress notification etc. So no, it doesn't seem like bad idea at all. It's also something that could evolve gradually, and reach a useful stage (i.e. have several handy tools) quickly. -- Ville Vainio http://tinyurl.com/2prnb From http Wed Jun 8 20:38:11 2005 From: http (Paul Rubin) Date: 08 Jun 2005 17:38:11 -0700 Subject: Fast text display? References: Message-ID: <7xu0k8s6to.fsf@ruckus.brouhaha.com> Jp Calderone writes: > What does "included with Python" mean anyway? Different packagers > make different decisions. I mean included with the source distro from python.org. > This applies to other libraries as well, of course. Installing > wxPython on Debian is a 5 second ordeal. I don't believe that, unless you're installing a binary. I only want to install from source. From tjreedy at udel.edu Sun Jun 5 03:57:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Jun 2005 03:57:29 -0400 Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: "Robert Kern" wrote in message news:d7u737$8or$1 at sea.gmane.org... > Mike Meyer wrote: >> I've heard people argue otherwise on this case. In particular, if you >> allow an employee to use your GPL'ed-but-not-distributed software, >> they are the end user, and have all the rights granted by the GPL. So >> they can distribute the software - possibly to your >> competitors. Employment contracts can't prohibit this, because the GPL >> specifically disallows "distribution" (allowing your employee to use >> the software) under licenses that restrict the rights granted by the >> GPL. > > Well, the FSF at least thinks that internal use within an organization > does not constitute distribution. The fact that GPL effectively discriminates in favor of large corporations (and other organizations) and programmers employed by such (versus those contracting with such), is something I don't like about it. This seems contrary to the spirit of the thing. It certainly supports the myth that organizations are 'people'. What if a whole country claimed to be 'one organization' (as the entire Soviet Union once was, in a real sense). Could it distribute modifications 'privately' while denying such to the rest of the world? Terry J. Reedy From UNIEMFXHWQZB at spammotel.com Wed Jun 29 01:42:33 2005 From: UNIEMFXHWQZB at spammotel.com (BORT) Date: 28 Jun 2005 22:42:33 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <1120023753.231890.182890@g43g2000cwa.googlegroups.com> All, The Forth-Python pull was heading to a conclusion just like "Tastes Great" vs. "Less Filling" or Ford-Chevy. However, friendly folks at comp.lang.forth pointed me to Amazon.com and _Mindstorms: Children, Computers, and Powerful Ideas_ by Seymour Papert. The book is by Logo's inventor and, according to the reviews, addresses the larger goal I most want to achieve. I now want to read the book. Period. However, my kids both love Legos which uses a Logo implementation for their robotics toys. I could probably capture both the 10 yr old AND the 7 yr old if we can spring for the $200 Lego Mindstorm set. Sort of blows away my specification of "free," but... In my earlier browsing, I eliminated Logo early on, thinking we would hit its capability ceiling too quickly and then backtrack in order to make a transition to a "REAL" language. uh... I've been browsing on Logo tonight and, even without the Lego robots, I may go that route. Shoot, I thought Logo was just moving hokey sprites in increasingly complex patterns until I saw the book list at: http://el.media.mit.edu/logo-foundation/products/books.html Hmm... When all is said and done, maybe the choice is kind of like physical exercise. I can spend weeks choosing the most effective work out and diet combination. But, until I cut back on biggie size grease brugers with double shakes and get off of the couch every now and then, the choice of workout is moot. In fact, one I use is better than the "best" that I don't use. Gentle folk of comp.lang.python, I heartily thank you all for your input. I think I'm taking the boys through the door marked "Logo." We may be back this way, though. We will likely need MORE in the nebulous future. I am impressed with the outpouring of support here! Thanks to all! From dsa at unilestemg.br Wed Jun 8 17:04:46 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Wed, 8 Jun 2005 21:04:46 +0000 Subject: Tabnanny? In-Reply-To: <20050608234409.8737C7AB7E@mail.internet.is> References: <20050608234409.8737C7AB7E@mail.internet.is> Message-ID: <200506082104.47084.dsa@unilestemg.br> Hi Anna ! > ? ? idx = idxLargest(data, len(data) In this line we have a missing ")", for me, this was the problem. Anyway, Check this line too: passes = len(max) + 1 It is giving me an error. See ya ! -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From http Wed Jun 29 13:27:28 2005 From: http (Paul Rubin) Date: 29 Jun 2005 10:27:28 -0700 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> Message-ID: <7xwtodvzsv.fsf@ruckus.brouhaha.com> Gregory Pi?ero writes: > I'd like to see some database API's to the most common databases > included. Yes, certainly, this is a serious deficiency with Python. From usenet.20.evilspam at spamgourmet.com Sun Jun 12 10:06:18 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 14:06:18 GMT Subject: ElementTree Namespace Prefixes Message-ID: Does anyone know how to make ElementTree preserve namespace prefixes in parsed xml files? The default behavior is to strip a document of all prefixes and then replace them autogenerated prefixes like ns0, ns1, etc. The correct behavior should be to write the file in the form that it was read, which it seems to do correctly for everything except namespace prefixes. The docs mention "proper" output can be achieved by using the Qname object, but they don't go into any detail. Any help is appreciated. Thanks, Chris Spencer From R.Brodie at rl.ac.uk Wed Jun 29 09:24:44 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 29 Jun 2005 14:24:44 +0100 Subject: XMLRPC and non-ascii characters References: Message-ID: "Joxean Koret" wrote in message news:mailman.1057.1120050564.10512.python-list at python.org... > I'm having troubles to make my XMLRPC application working with non > ASCII characters. I don't think XMLRPC has a mechanism for specifying an encoding other than UTF-8 (and that only by default). If you recode to that, you'll probably be OK. From pwilkins at noaddress.org Fri Jun 24 15:21:57 2005 From: pwilkins at noaddress.org (pwilkins) Date: Fri, 24 Jun 2005 15:21:57 -0400 Subject: Newbie question: how to keep a socket listening? References: <1119637288.536579.249340@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 24 Jun 2005 11:21:28 -0700, ncf wrote: > I think your problem /may/ be in the following line of code: > sa.listen(1) > > I believe what's happening is that the listen() creates a decremental > counter of the number of connections to accept. Once it decrements to > 0, it won't accept any more connections. (I'm not at all sure, but that > sounds like what it's doing.) Good point, will read up on socket.listen(x) > If you find out the problem, please post it up here for all to learn > from :) Will do that > > Oh, and just a suggestion, do something like a 'netstat -a -p --inet' on > the daemon end. (Might not be the completely correct command =\) I did that is how I know the ports are still begin held thx, pete From riccardo_cut1 at cut2_sideralis.net Fri Jun 17 21:00:09 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Sat, 18 Jun 2005 03:00:09 +0200 Subject: dynamic References: Message-ID: On Wed, 15 Jun 2005 11:50:27 +0200, Riccardo Galli wrote: Hi. Thanks to all who answered. Scott David posted a solution (clever, scott) which was what I asked for, but I noticed some oddness while using it (about __init__). I also understood that this way should be avoided. I ended up using a proxy approach, wich works. Thank you, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From philippe at philippecmartin.com Sun Jun 26 22:24:04 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 27 Jun 2005 02:24:04 GMT Subject: Running Python interpreter in Emacs References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> <1119811726.576282.59500@g49g2000cwa.googlegroups.com> Message-ID: <8rJve.254$U61.134@newssvr11.news.prodigy.com> Hi, I was refering to the Windows $PATH which you can modify in the same dialog. To make sure it's done properly, open a console (cmd.exe) and type python Regards, Philippe Rex Eastbourne wrote: > I went to My Computer | Properties | Advanced | Environment Variables > and added c:\program files\python24 to both the PYTHONPATH and Path > variables. Still no luck. I don't know whether the path I'm talking > about is the same as the $PATH you referred to, or whether I'm supposed > to put python.exe explicitly somewhere; could someone refer me to a > place where I can read about these things? > > Thanks! > > Rex From tjreedy at udel.edu Wed Jun 29 15:54:03 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Jun 2005 15:54:03 -0400 Subject: map vs. list-comprehension References: <42c27238$0$26269$626a14ce@news.free.fr> Message-ID: "F. Petitjean" wrote in message news:42c27238$0$26269$626a14ce at news.free.fr... >res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] > Hoping that zip will not be deprecated. Cease worrying. Zip was added to replace the zipping behavior of map and the idiom map(None, a, b, ...). It simultaneously altered the behavior for unequal length inputs to stop with the shortest instead of padding to the longest. tjr From tjreedy at udel.edu Sat Jun 18 19:23:11 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 18 Jun 2005 19:23:11 -0400 Subject: struct.(un)pack and ASCIIZ strrings References: Message-ID: "Sergey Dorofeev" wrote in message news:d926sj$1jc8$1 at gavrilo.mtu.ru... >I can use string.unpack if string in struct uses fixed amount of bytes. I presume you mean struct.unpack(format, string). The string len must be known when you call, but need not be fixed across multiple calls with different strings. > But is there some extension to struct modue, which allows to unpack > zero-terminated string, size of which is unknown? > E.g. such struct: long, long, some bytes (string), zero, short, > short,short. Size is easy to determine. Given the above and string s (untested code): prelen = struct.calcsize('2l') strlen = s.find('\0', prelen) - prelen format = '2l %ds h c 3h' % strlen # c swallows null byte Note that C structs can have only one variable-sized field and only at the end. With that restriction, one could slice and unpack the fixed stuff and then directly slice out the end string. (Again, untested) format = 2l 3h' # for instance prelen = struct.calcsize(format) tup = struct.unpack(format, s[:prelen]) varstr = s[prelen, -1] # -1 chops off null byte Terry J. Reedy From saint.infidel at gmail.com Mon Jun 27 18:45:10 2005 From: saint.infidel at gmail.com (infidel) Date: 27 Jun 2005 15:45:10 -0700 Subject: pulling multiple instances of a module into memory In-Reply-To: <1119881167.255259.251880@f14g2000cwb.googlegroups.com> References: <1119881167.255259.251880@f14g2000cwb.googlegroups.com> Message-ID: <1119912310.553597.98890@g49g2000cwa.googlegroups.com> Do you have control over the eggs.so module? Seems to me the best answer is to make the start method return a connection object conn1 = eggs.start('Connection1') conn2 = eggs.start('Connection2') From tzot at sil-tec.gr Mon Jun 27 19:06:12 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 02:06:12 +0300 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Message-ID: <5i11c1ls42kisluuhnt4rua1f3bqmud0q3@4ax.com> On 27 Jun 2005 15:38:59 -0700, rumours say that "Inkiniteo" might have written: >Hi guys. I have a script that sends the info by email, but i'd like to >avoid the convertion to HTML by the email client or Gmail, because it >ruins all the formatting i did (with tabs, mostly). Briefing, i wanna >be able to send SMTP mail and the receiver only get it in plain text. Please tell us what you do more precisely: * do you send the "info" as an attachment using the email package? * do you create alternative text and HTML parts for the body? I have never managed to send plain text email and receive it as HTML. Perhaps you mean that some "smart" client does something stupid with your text, eg. it removes line-breaks you have in your message? Try this: import smtplib def send(server, from_whom, to_whom_list): smtp = smtplib.SMTP(server) smtp.sendmail(from_whom, to_whom_list, """From: %s To: %s Subject: test email This is a test. It has line breaks. Does it come as three separate lines?""" % (from_whom, ", ".join(to_whom_list)) I tried it as send('localhost', 'tzot at sil-tec.gr', ['tzot at sil-tec.gr']) and I had no problem. What happens for you (substitute other server and email addresses, obviously :) ? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From irmen.NOSPAM at xs4all.nl Sat Jun 4 18:58:46 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 05 Jun 2005 00:58:46 +0200 Subject: Problem on python 2.3.x was: [ANN] Snakelets 1.41 and Frog 1.6 In-Reply-To: <42a0a7f4$0$29628$e4fe514c@news.xs4all.nl> References: <42a0a7f4$0$29628$e4fe514c@news.xs4all.nl> Message-ID: <42a23228$0$33283$e4fe514c@news.xs4all.nl> ...darn, some users have reported that a strange problem occurs when running Snakelets 1.41 on Python 2.3.x (Python 2.4 is fine!) It seems that there is a bug in older versions of inspect.getmodule() and that bug causes Snakelets to stop working correctly on Python 2.3.x If you experience this bug (you can see it in the server.log "arg is not a module, class, method, function, traceback, frame, or code object") please upgrade to Python 2.4.1 if possible. In the meantime I will try to make a workaround so that Snakelets will work again on older Python versions. Sorry for the trouble, --Irmen. From desertgarden at netscape.com Sat Jun 11 09:58:19 2005 From: desertgarden at netscape.com (Brian) Date: Sat, 11 Jun 2005 13:58:19 GMT Subject: Best Web dev language In-Reply-To: <11al0nhr4opfgaa@corp.supernews.com> References: <11al0nhr4opfgaa@corp.supernews.com> Message-ID: <%5Cqe.2453$NX4.1075@newsread1.news.pas.earthlink.net> Hi Jon, Yes, there are a variety of tutorials on the Internet that can help you learning how to use Python with the web. Two of the best ones you can get for free by clicking on the link below. 1) http://www.devshed.com/c/a/Python/Writing-CGI-Programs-in-Python/ 2) http://www.devshed.com/c/a/Python/Python-on-the-Web/ However, in order to understand the tutorials above, it is important to first have a basic understanding of the Python programming language. Python is not hard to learn, but it might take you a few hours to learn it, if you have not done so already. 1) http://www.greenteapress.com/thinkpython/ 2) http://www.devshed.com/c/a/Python/ Hope this helps, Brian :-) --- Jon Slaughter wrote: > I'm trying to get into web development for creating a professional web site > and I'm confused on which language I should use. I've read some comparisons > between the major languages and I was thinking that python might be the way > to go for the most powerful and general language but I am not sure. Does > anyone know of any detailed and objective comparisons between the major > languages(perl, php, java, javascript, etc...) that might help me get a > clearer picture? > > I have some experience with C/C++ but it has been some time since I have > done any real programming... I'd prefer to use C++ style so I would no thave > to learn a new language completely. I've also read that one can use C/C++ > to develop just as one would use any other language and I'm wondering if > this is advisable? (since it seems most web pages are done in perl, python, > or php?) > > Also, can anyone recommend any book or web page that gives an introduction > to the method in which one programs web sites? I am not clear on who one, > for instance, would use C++ as the language for a web site except by using > it to create html... I'm not sure if basicaly all languages goal is creating > html dynamically or if there is more to do. What I mean is that basicaly > one is using some other language to wrap the html code or possibly generate > it at run-time for dynamic results. (so all client based web interfaces are > really just html readers but all this "extra" stuff is used to make certain > things easier and dynamic(just as generating tables and forms and all that). > > Thanks for any help, > Jon > > From me at privacy.net Mon Jun 27 22:10:53 2005 From: me at privacy.net (Dan Sommers) Date: Mon, 27 Jun 2005 22:10:53 -0400 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> <11c166s2sh66b93@news.supernews.com> <1119923787.531336.292220@z14g2000cwz.googlegroups.com> Message-ID: On 27 Jun 2005 18:56:27 -0700, "Inkiniteo" wrote: > I see. So... what about sending HTML email? If i send HTML tagged > text, the client will be able to read it as HTML? > For example, if i send an email with:
> Yo! will the client read a bold Yo! ? That depends on the client. IMO, HTML belongs on web pages, not in email. YMMV. Regards, Dan -- Dan Sommers From tdaitx at gmail.com Fri Jun 3 08:15:26 2005 From: tdaitx at gmail.com (=?ISO-8859-1?Q?Tiago_St=FCrmer_Daitx?=) Date: Fri, 3 Jun 2005 09:15:26 -0300 Subject: Importing and source structure troubles In-Reply-To: <910885da050603005949f8d51e@mail.gmail.com> References: <910885da050603005949f8d51e@mail.gmail.com> Message-ID: The "best" way depends on how you have structured your program. From what you've told I believe that setting the directories like dir1 dir2 dir3 is a good approach. As for the import errors you're getting, check this section from the tutorial: http://docs.python.org/tut/node8.html#SECTION008400000000000000000 It describes how to setup packages in Python - and that's exactly what you need. You'll see that in order to import dir3 from dir2 you must import the full name of the package (ie. import dir1.dir3). See the intra-packages reference http://docs.python.org/tut/node8.html#SECTION008420000000000000000 Regards, Tiago S Daitx On 6/3/05, Echo wrote: > Hello, > > I am having trouble with putting the source for a program I am working on in different directories. > I have the directories set up like this: > > dir1 > dir2 > dir3 > > I want the source in dir2 to be able to import from the source in dir3(is this possible). I get import errors when I tried doing this. > > A less preferred structure that I tried was like this: > dir1 > dir3 > dir2 > > I thought that this way would work. but this way I get even more import errors. two files in dir2 have a 'from dir3.dir2 import bla' however, in one of the files, I get an import error. any idea why this is?? > > What is the best way to structure the program I am working on? I have 3 groups of source files. One has the files that start the program and some tools. Another group has all the main files. And the last group is just some misc stuff. How would the best way to accomplish this be? > > -- > -Echo > -- > http://mail.python.org/mailman/listinfo/python-list > > From darkpaladin79 at hotmail.com Mon Jun 6 17:59:42 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 17:59:42 -0400 Subject: help with sending mail in Program Message-ID: Hey i'm new here and relatively new to python. I've made a few small programs and now I'm making a program for my friends that at the end has a feedback form. I want to send the feedback back to my email adress. I know I should use the SMTP module and I have figured out how to send with it, but I can't figure out how to include my variables in it, such as the questions I ask them. Can someone explain this to me? -Ivan _________________________________________________________________ On the road to retirement? Check out MSN Life Events for advice on how to get there! http://lifeevents.msn.com/category.aspx?cid=Retirement From thomasbartkus at comcast.net Wed Jun 22 11:07:12 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 22 Jun 2005 10:07:12 -0500 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: "Will McGugan" wrote in message news:42b97240$0$24467$da0feed9 at news.zen.co.uk... > Hi, > > I'd like to write a windows app that accesses a locally stored database. > There are a number of tables, the largest of which has 455,905 records. > > Can anyone recommend a database that runs on Windows, is fast / > efficient and can be shipped without restrictions or extra downloads? > > I have googled and found plenty of information on databases, its just > that I dont have enough experience with databases to know which one is > best for my task! If you are writing strictly for the MS Windows platform And If the database is running single user with a "locally stored database" on a Windows workstation. Then The MS Access file based (.mdb) system is hard to argue with. You wouldn't have to distribute the (rather expensive) Access application since this is little more than a front for the underlying DAO/ADO database libraries that are built into the warp and woof of MS Windows. Your Python application can address the DAO or ADO directly as these will libraries will be pre-installed and/or freely available for MS Windows. Fast, freely available, no license restrictions, and no need for extra downloads for a reasonably recent (Win2000, XP) operating system. On the other hand, if operating system portability were a concern (as it should be!), I might suggest MySQL. A Python/MySQL application can jump between Windows to Linux (all flavors!) to Unix to BSD without need to alter a single line of code. You were writing a Python app, weren't you :-) Thomas Bartkus From nicolas.riesch at genevoise.ch Fri Jun 17 04:43:24 2005 From: nicolas.riesch at genevoise.ch (nicolas.riesch at genevoise.ch) Date: 17 Jun 2005 01:43:24 -0700 Subject: strxfrm works with unicode string ? Message-ID: <1118997804.678723.170070@g44g2000cwa.googlegroups.com> I am trying to use strxfm with unicode strings, but it does not work. This is what I did: >>> import locale >>> s=u'\u00e9' >>> print s ? >>> locale.setlocale(locale.LC_ALL, '') 'French_Switzerland.1252' >>> locale.strxfrm(s) Traceback (most recent call last): File "", line 1, in -toplevel- locale.strxfrm(s) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 0: ordinal not in range(128) >>> Someone sees what I did wrong ? From max at alcyone.com Mon Jun 27 21:13:46 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 27 Jun 2005 18:13:46 -0700 Subject: Pickling limitation with instances defining __cmp__/__hash__? Message-ID: <5OKdnav6rfDWOV3fRVn-hQ@speakeasy.net> I've come across a limitation in unpickling certain types of complex data structures which involve instances that override __hash__, and was wondering if it was known (basic searches didn't seem to come up with anything similar) and if there is a workaround for it short of restructuring the data structures in question. The fundamental issue rests with defining classes which override __cmp__ and __hash__ in order to be used as keys in dictionaries (and elements of sets). __cmp__ and __hash__ are defined to manipulate a single attribute of the class, which never changes for the lifetime of an object. In a simplified form: class C: def __init__(self, x): self.x = x def __cmp__(self, other): return cmp(self.x, other.x) def __hash__(self): return hash(self.x) Even if C contains other members which are manipulated, making it technically mutable, since the one attribute (in this example, x) which is used for __cmp__ and __hash__ is never changed after the creation of the object, it is legal to use as a dictionary key. (Formally, the atrribute in question is a name which is guaranteed to be unique.) The difficulty arises when the data structures that are built up in C contain a circular reference to itself as a dictionary key. In my particular case the situation is rather involved, but the simplest example which reproduces the problem (using C) would be: c = C(1) c.m = {c: '1'} So far this is fine and behaves as expected. Pickling the object c results in no problems. Unpickling it, however, results in an error: data = pickle.dumps(c) d = pickle.loads(data) # line 25 Traceback (most recent call last): File "/home/max/tmp/hash.py", line 25, in ? d = pickle.loads(data) File "/usr/local/lib/python2.4/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/local/lib/python2.4/pickle.py", line 872, in load dispatch[key](self) File "/usr/local/lib/python2.4/pickle.py", line 1218, in load_setitem dict[key] = value File "/home/max/tmp/hash.py", line 15, in __hash__ return hash(self.x) AttributeError: C instance has no attribute 'x' By poking around, one can see that the error is occurring because the unpickler algorithm is trying to use the instance as a key in a dictionary before the instance has been completely initialized (in fact, the __dict__ of this object is the empty dictionary!). The error happens regardless of whether pickle or cPickle is used (so I used pickle to give a more meaningful traceback above), nor whether the protocol is 0 or HIGHEST_PROTOCOL. Is this issue known? I don't see any mention of this kind of circularity in the Python Library Reference 3.14.4. Second, is there any reasonably straightforward workaround to this limitation, short of reworking things so that these self-referenced objects aren't used as dictionary keys? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis You'll learn / Life is worth it / Watch the tables turn -- TLC From dieter at handshake.de Mon Jun 13 13:29:15 2005 From: dieter at handshake.de (Dieter Maurer) Date: 13 Jun 2005 19:29:15 +0200 Subject: subprocess module and blocking References: <42ABFEEC.3010505@jessikat.fsnet.co.uk> Message-ID: Robin Becker writes on Sun, 12 Jun 2005 09:22:52 +0000: > I'm using a polling loop in a thread that looks approximately like this > > while 1: > p = find_a_process() > rc = p.poll() > if rc is not None: > out, err = p.communicate() > #deal with output etc > sleep(1) >.... > I notice that under both win32 and freebsd that things are fine > provided that the subprocess doesn't write too much to > stdout/stderr. However, the subprocess seems to lock often if too much > is written (under freebsd I see a process state of POLL). I assume > that the subprocess is filling up the pipe and then failing to wake up > again. I had expected that subprocess would take care of this for me, You just found out that this is not the case. The warning attached to "communicate"s docstring might have you averted: "Note: the data read is buffered in memory... do not use for large size". If subprocess would do what you expect, it would need to buffer the output (to make room in the pipes again). But, for large data, this could have dramatic consequences. Thus, you should use "select" on the pipes to find out when to read data. Dieter From Michael.J.Fromberger at Clothing.Dartmouth.EDU Sat Jun 18 19:39:16 2005 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Sat, 18 Jun 2005 19:39:16 -0400 Subject: Loop until condition is true References: <1119074614.700809@yasure> <11b88ok1tr67475@corp.supernews.com> Message-ID: In article , Andrea Griffini wrote: > On Sat, 18 Jun 2005 13:35:16 -0000, Grant Edwards > wrote: > > >AFAICT, the main use for do/while in C is when you want to > >define a block of code with local variables as a macro: > > When my job was squeezing most out of the CPU (videogame > industry) I remember that the asm code generated by > > while (sz-- > 0) > { > /* do some stuff */ > } > > was indeed worse than > > do > { > /* do some stuff */ > } while (--sz); > > because of the initial "empty-loop" test (conditional jumps > were bad, and forward conditional jumps were worse). > So where at least one iteration was guaranteed the do-while > loop was a better choice. Hmm. I don't know what compiler you were using, but in my experience it's fairly typical to compile while( ...) { ... } as j test body: ... test: ... je body ;; or whatever your condition is To turn this into a do { ... } while( ...), you need only remove the initial "j test" instruction. Even if forward conditional jumps are bad for your particular architecture, this method avoids the problem neatly. Personally, I'd be pretty suspicious of the quality of a compiler that produced radically different code for these two constructs without some damned good reason. -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From vdavidster at gmail.com Mon Jun 27 00:58:11 2005 From: vdavidster at gmail.com (vdavidster at gmail.com) Date: 26 Jun 2005 21:58:11 -0700 Subject: Beginner question: Converting Single-Element tuples to list Message-ID: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> Hello everyone, I want to convert a tuple to a list, and I expected this behavior: list(('abc','def')) -> ['abc','def'] list(('abc')) -> ['abc'] But Python gave me this behavior: list(('abc','def')) -> ['abc','def'] list(('abc')) -> ['a','b','c'] How do I do get Python to work like the in former case? Many thanks! David From kay.schluehr at gmx.net Sun Jun 5 10:46:41 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 5 Jun 2005 07:46:41 -0700 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117982203.857569.101730@z14g2000cwz.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <1117982203.857569.101730@z14g2000cwz.googlegroups.com> Message-ID: <1117982801.887761.90310@g43g2000cwa.googlegroups.com> Kay Schluehr wrote: > Mac wrote: > > Is there a way to mimic the behaviour of C/C++'s preprocessor for > > macros? The problem: a lot of code like this: > > > > def foo(): > > # .... do some stuff > > if debug: > > emit_dbg_obj(DbgObjFoo(a,b,c)) > > > > # .... do more stuff > > if debug: > > emit_dbg_obj(DbgObjBar(d,e)) > > > > # ... and so on ... > > > > Notes: > > > > * the two-lines of debug conditional tend to really break up the flow > > of the surrounding code > > > > * in C you could wrap them with a macro so you could do > > DEBUG_EMIT(DbgObjFoo(a,b,c)), etc, with the macro only instantiating > > the object and processing it if the debug flag was set. The one-liner > > is MUCH less disruptive visually when reading code > > Make emit_dbg_obj() a class to create one-liners: > > class Emit_dbg_obj: > debug = True > def __init__(self, algo): > self.algo = algo > > def call_if_debug(self): > if self.debug: > return self.algo > > def foo2(): > # .... do some stuff > Emit_dbg_obj(DbgObjFoo(a,b,c)).call_if_debug() > > # .... do more stuff > Emit_dbg_obj(DbgObjFoo(c,d)).call_if_debug() > > > Ciao, > Kay Hmmm... this won't work as expected. class Emit_dbg_obj: debug = True def __init__(self, algo, args): self.algo = algo self.args = args def call_if_debug(self): if self.debug: self.algo(*self.args) def foo2(): # .... do some stuff Emit_dbg_obj(DbgObjFoo,(a,b,c)).call_if_debug() # .... do more stuff Emit_dbg_obj(DbgObjFoo,(c,d)).call_if_debug() Regards, Kay From kbilsted at hotmail.com Sun Jun 12 19:04:43 2005 From: kbilsted at hotmail.com (newseater) Date: 12 Jun 2005 16:04:43 -0700 Subject: changing how instances are "created" Message-ID: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> Hello. I need to be able to control how objects are created. Sometimes when creating an object, i want to reuse another object instead. I've searched for factory method implementations and singleton implementations. They were too much of a hack! My first attempt of doing this was to play around with the __new__() method. But i didn't quite succed. Then i came up with making a static method which can create my instances or re-use other instances. However, the below code I cannot get to work :( class Creator def createInstance(cls, *args, **kwargs): anewinstance = cls.__new__(cls, *args, **kwargs) anewinstance.__init__(*args, **kwargs) return anewinstance createInstance = staticmethod(createInstance) can anyone help?? From myfriendmyfriend at gmail.com Wed Jun 15 15:45:56 2005 From: myfriendmyfriend at gmail.com (Your Friend) Date: 15 Jun 2005 12:45:56 -0700 Subject: Read System.out.println From Java Using popen ? Message-ID: <1118864756.680646.234400@f14g2000cwb.googlegroups.com> Hello All, I'm relatively new to Python programming but have been working on this problem for a little bit now ... I initially began writing UNIX scripts in Python and thought it was the greatest because I could do the following very easily : pswwaux = os.popen( "ps wwaux | grep /usr/sbin/httpd" ) for line in pswwaux.readlines() : print line.strip() This made writing wrapper scripts for restarting servers ( and handling all the errors that may occur on a restart ... ) a snap ... now I'm trying to make a call to a Java service that utilizes System.out.println to say whether the action was performed, or if there were errors or any other piece of information ... I'm having issues reading what comes out of System.out.println, and I'm beginning to wonder if my Java service is being called at all and if so, is it even possible to capture System.out.println ? Here's the gist of my call to the Java service: result = os.popen( "%s/bin/java com.foo.service.JavaService %s" % ( JAVA_HOME, FILE_TO_CREATE ) ) print result.readlines() The result.readlines() always results in this output: [] Furthurmore, the file that is supposed to be created is not created ... If I replace the result = os.popen with a print, and then copy what the script prints out and run that ( straight up on the command line ), the file is created and the expected output is spit out ... It should be noted that I'm trying to loop over a list of files and create a Thread for each action since the Java service can take a bit of time to run : for id in ids : thread = threading.Thread( target=export, args=( [ id ] ) ) thread.start() So I guess my questions are: 1) Am I executing the Java service the correct way 2) Am I capturing the System.out.println from the Java service the correct way Any help would be greatly appreciated From philippe at philippecmartin.com Tue Jun 28 19:56:45 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 23:56:45 GMT Subject: Embedding python in C References: <3Qfwe.519$Ox3.92@newssvr12.news.prodigy.com> <200506281653.46932.philippecmartin@sbcglobal.net> <200506281709.58266.philippecmartin@sbcglobal.net> Message-ID: <1tlwe.655$U61.468@newssvr11.news.prodigy.com> Thanks, I cannot get the demo to compile, but I joined their list. Thanks Philippe Chris Lambacher wrote: > pyrex can be used for embedding too. > http://www.freenet.org.nz/python/embeddingpyrex/ > > On 6/28/05, Philippe C. Martin wrote: >> Actually maybe not ... looking at the doc: >> >> I have modules already coded in Python, and I need a C wrapper so C >> applications may link with it. >> >> Regards, >> >> Philippe >> >> >> >> On Tuesday 28 June 2005 04:53 pm, Philippe C. Martin wrote: >> > Sounds like it, thanks. >> > >> > Philippe >> > >> > On Tuesday 28 June 2005 09:10 pm, Chris Lambacher wrote: >> > > Pyrex might be what you are looking for: >> > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ >> > > >> > > -Chris >> > > >> > > On 6/28/05, Philippe C. Martin wrote: >> > > > Hi, >> > > > >> > > > Is there a program out there that would generate the C code to >> > > > instantiate objects and call them: >> > > > >> > > > ex: miracle.exe -i mymodule.py -o module_internface.c ? >> > > > >> > > > I seem to recall a _yes_ to that but I got a memory overflow :-) >> > > > >> > > > Thanks, >> > > > >> > > > Philippe >> > > > -- >> > > > http://mail.python.org/mailman/listinfo/python-list >> >> -- >> ************************************* >> Philippe C. Martin >> SnakeCard, LLC >> www.snakecard.com >> +1 405 694 8098 >> ************************************* >> > > From enas_khalil at yahoo.com Mon Jun 27 14:04:58 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Mon, 27 Jun 2005 11:04:58 -0700 (PDT) Subject: Help - im a beinner in using python Message-ID: <20050627180458.32120.qmail@web50304.mail.yahoo.com> dear all could you if you please tell me how can i start learning python im reading on tutorial and i have questions about: - how can i adjust the environmental variable on windows platform -where should i put the NLTK data to be accessible by python -how can i use TKinter in python is it only the "fom Tkinter import *" command ,i did this it sometimes woks and sometimes doesnt -i want to know the way to have a Tkinter GUI fo any python code i write thanks in advance --------------------------------- Yahoo! Mail Stay connected, organized, and protected. Take the tour -------------- next part -------------- An HTML attachment was scrubbed... URL: From hancock at anansispaceworks.com Thu Jun 9 10:26:35 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 9 Jun 2005 09:26:35 -0500 Subject: Software licenses and releasing Python programs for review In-Reply-To: <1117694543.931985.290720@g44g2000cwa.googlegroups.com> References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> Message-ID: <200506090926.35752.hancock@anansispaceworks.com> On Thursday 02 June 2005 01:42 am, poisondart wrote: > If this thread has shown anything it is I'm a bit green with respect to > software licenses, Yep. We've all been there at some time, though. ;-) > but the other thing is that I consider myself as an > isolated case and I wanted to know if there were others who wanted the > same thing as me. I think the real problem is that you *think* you want something which is not what you *really* want. For example, I think you don't really get the full range of implications of a "non-commercial" clause, nor do you fully appreciate its chilling effects on development. > I'm curious to know what the money that open source or GPL'd projects > get and what this money means to these people's overall income. Free-licensed projects get almost no direct money for development in probably 99% of cases. On the other hand, people make billions of dollars every year off of the *use* of free-licensed software (consider Apache, for example). Quite a few of the people making the money are naturally part of the developer community for their particular gravy-train. That's because they generally have specific needs they want to see the software address, and it's worth the effort to contribute the necessary changes. The community benefits from the changes (which is why "copyleft" is good), and they benefit (a lot!) from not having to maintain a separate patched version of the code. > I am > sure that any amount would motivate somebody to continue their work on > a project, but myself in particular, I consider my project to be a tool > for teaching and I view teaching as helping others...which I would > gladly offer without price. So you're unpaid teacher? What do you do for a living, then? ;-) > I wanted to see if there were others who > shared my view of helping others freely with their knowledge. Actually, you see, as I've already tried to point out to you, using software to teach *is* COMMERCIAL USE of the software. At least it is, if you draw a salary for teaching. Yes, I know that teaching is a public benefit and a joy, and I do occasionally teach for free, but most of the time, even teachers need to make a living, right? Is it right to restrict use of the software only to those who teach without pay? > Yes, what I ask may seem ridiculous, but I don't view it that way. > Instead, I find that it is the implication of using a restrictive > license such as I described to be ridiculous: if there is no monetary > gain option in the license, then this implies that nobody (or very few) > will be willing to do any work or "asking for something for nothing". > It isn't for nothing if you value knowledge and learning. It took me awhile to parse that: You are saying that the implication that the lack of a "monetary gain option" will chill development is ridiculous. Sorry, but history disagrees with you: projects with restrictions on sale prices for copies of the software have much reduced distribution and development interest, because it prevents distribution. Note that prices will be driven down by natural market forces anyway --- just because source A can sell a copy of free software doesn't prevent source B from giving it away, and this is in practice what happens. But it does allow source A to bundle copies and cover CD-ROM distribution and printing expenses, pay for web and FTP servers, etc. Even if they only capture a small "pay for convenience" market, they may be able to do this, thus providing an important resource for users of free software. When you put in a clause to restrict such sales you are attacking a friendly: somebody who the community values as a service provider. It may well be that 9/10ths of my free software is downloaded directly from developer sites or from free download sites, but even many of those sites are supported by advertising, and I want the OPTION to buy copies on a CD if I need or want to. That's not at all the same as buying proprietary software, where I would be FORCED to make such a purchase, and then at an artificially inflated price. Finally, you are wrongly conflating a "restriction against selling copies" with a "restriction against all commercial use of the software". The latter includes virtually EVERY use of the software if interpreted broadly enough. You yourself appear to take a very broad view of this --- with one exception: you paradoxically do not regard drawing a salary as a teacher as "commercial". But a salary supported partly by the use of software is one of the more clearcut ways to commercially benefit --- much more direct than supporting advertising revenues, which you *do* regard as commercial. This is a contradiction, which just goes to show how poorly defined the idea of "commercial use" is, and therefore why it is a bad thing to try to control in a license. > I admit that my view is a bit idealistic which leads me to believe that > maybe I should reconsider the whole decision altogether. Actually, I think you're being hypocritical in thinking that it is idealistic to regard your salary as a teacher as somehow "non-commercial". You have succombed to the "higher profession" delusion. Sure, you might love your work, but do you really want someone to *force* you to do it for free? How are you going to pay for your supper, then? Do you feel that you should have to take up another job to support your teaching habit? Do you think that society would benefit from forcing teachers to do that? I certainly don't. That's what I think you should be reconsidering. You have somehow tricked yourself into thinking that you are not an economic being just because you work in academia, and then you are going on to scoff at other people for being economic --- putting you into the realm of hypocrisy. Now, it might be perfectly realistic (and indeed, idealistic) to imagine that such commercial concerns should not effect what you teach, or how you teach it. But that *can* be true in any form of human endeavor --- teaching is not unique in this respect. Even a farmer may farm more out of love of the vocation than because it is particularly profitable (which, as with teaching, it often is not). Should a farmer be regarded as some dirty capitalist because he uses Gnumeric to tally his accounts? That is commercial use of the software. I think you will actually get what you want by just using a copyleft free-license like the GPL. This will prevent the software from being absorbed into a commercial proprietary product, which is what I consider the reasonable part of what you are asking for. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From jan.danielsson at gmail.com Thu Jun 9 16:58:17 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Thu, 09 Jun 2005 22:58:17 +0200 Subject: A question about time Message-ID: <42a8ac25@griseus.its.uu.se> Hello all, I have a list of servers which an application connects to. If the connection fails, the application should mark the server as temporarily unavailable, and should try to use the server again after x units of time. In C, I would do this: server.invalidUntil = time(NULL) + 5*60; // five minute delay ..and the check: if(time(NULL) > server.invalidUtil) { // use server } So the whole thing very simple... But how do I do that in Python? I have found datetime.datetime.now(), but I don't understand what "format" it returns the time in. I assume it's an object of some sort.. But how do I do if I want the current time as an integer (unix timestamp) in Python? From iano at quirkster.com Wed Jun 29 14:48:25 2005 From: iano at quirkster.com (Ian Osgood) Date: 29 Jun 2005 11:48:25 -0700 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <1120070905.550380.8960@z14g2000cwz.googlegroups.com> Forth clarifications below... Rocco Moretti wrote: > > So for Math you'd do something like: > > y = b + mx + cx^2 > > IIRC, for Forth it would be something like (please excuse the mistakes > in operator notation): > > x 2 ^ c * m x * + b + 'y' setvar Assuming these are all VALUEs: x DUP * c * m x * + b + TO y > [Portability] Much Forth code you find on the net is written to the ANS standard, and is thus portable. Free standard Forth systems are available for all platforms. > There are ANS and IEEE standards for Forth, but official standards tend > to leave things implementation dependent, especially in platform > specific things like file access. Standard I/O and file I/O are part of the ANS standard. > To further compound the issue, a Forth > system tends to be self contained and insular - interaction with the > surrounding environment may be minimal at best. Python, where possible, > tries to shield the user from platform specifics, while still allowing > full access to the environment. There are a number of Python bindings to > C libraries which give near complete control to the desktop/screen/sound > system, etc. Forth-bound libraries will likely be rarer, and again, > interpreter specific. That is unfortunately true. There are FFI (foreign function iterfaces) available for the most popular Forth systems, but how they work is not standardized. Forth has nothing like the module libraries of Python. Graphics, object-orientation, and data-types are all available or easily implemented in a particular Forth, but those batteries are not included as they are in Python. Ian From tjreedy at udel.edu Thu Jun 23 13:22:58 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 23 Jun 2005 13:22:58 -0400 Subject: don't understand MRO References: Message-ID: "Uwe Mayer" wrote in message news:d9eluf$ojc$1 at news2.rz.uni-karlsruhe.de... > I have a subclassed PyQt class: > > class Node(object): > def move(self, x,y): pass > > class CRhomb(QCanvasPolygon, Node): pass > > $ python > v2.4.1 >>>> CRhomb.mro() > [, , 'qtcanvas.QCanvasPolygonalItem'>, , 'qt.Qt'>, , , ] For those who don't know, 'mro' stands for 'method resolution order'. The method returns a list of classes (all except the first are base or super classes of the first) in the order in which their dictionaries are searched for method (or other attribute) names. > >>>> a = CRhomb() >>>> a.move(1,2) > > This executes also Node.move(a, 1,2) > Why? In the absence of other information, I would presume that none of the other classes have a move() method. > Because even QCanvasItem.move delegates the call to the derived object? > But > qt.Qt does not have a move() method... how does it get passed on to Node? Are you sure that QCanvasItem has a move method? What results from >>> print qtcanvas.QCanvasItem.move # ? If so, I would need to see its code to try to answer. Terry J. Reedy From deetsNOSPAM at web.de Fri Jun 24 14:34:05 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 24 Jun 2005 20:34:05 +0200 Subject: Getting binary data out of a postgre database References: <1119636233.488038.170240@z14g2000cwz.googlegroups.com> Message-ID: <3i320qFjktsjU2@uni-berlin.de> > So, rec[0] is an instance, but an instance of what? Since I needed to > use the PgSQL.PgBytea method on the image before inserting it into the > database, do I need to use a similar method to undo what PgBytea did to > it, or am I incorrectly writing this binary data? I tried > PgSQL.PgUnQuoteBytea(rec[0]), but that didn't work. What does print rec[0] give you? -- Regards, Diez B. Roggisch From sjmachin at lexicon.net Fri Jun 24 19:54:43 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 25 Jun 2005 09:54:43 +1000 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <42BC9D43.4020509@lexicon.net> James Stroud wrote: > On Friday 24 June 2005 05:58 am, Steven D'Aprano wrote: > >>with colour do begin >>red := 0; blue := 255; green := 0; >>end; >> >>instead of: >> >>colour.red := 0; colour.blue := 255; colour.green := 0; >> >>Okay, so maybe it is more of a feature than a trick, but I miss it and it >>would be nice to have in Python. > > > class color: # americanized > red = 0 > blue = 255 > green = 0 colour = color centre = center # etc etc > > Less typing than pascal. Also avoids those stupid little colons. > From roccomoretti at hotpop.com Fri Jun 10 10:50:56 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 10 Jun 2005 09:50:56 -0500 Subject: Annoying behaviour of the != operator In-Reply-To: References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: Dan Sommers wrote: > On Thu, 09 Jun 2005 15:50:42 +1200, > Greg Ewing wrote: > > >>Rocco Moretti wrote: >> >>>The main problem is that Python is trying to stick at least three >>>different concepts onto the same set of operators: equivalence (are >>>these two objects the same?), ordering (in a sorted list, which comes >>>first?), and mathematical "size". > >>>This gives the wacky world where >>>"[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't. > > > Python inherits that wackiness directly from (often wacky) world of > Mathematics. > > IMO, the true wackiness is that > > [ AssertionError, (vars, unicode), __name__, apply ].sort( ) > > "works," too. Python refusing to sort my list of complex numbers is a > Good Thing. The "wackyness" I refered to wasn't that a list of complex numbers isn't sortable, but the inconsistent behaviour of list sorting. As you mentioned, an arbitraty collection of objects in a list is sortable, but as soon as you throw a complex number in there, you get an exception. One way to handle that is to refuse to sort anything that doesn't have a "natural" order. But as I understand it, Guido decided that being able to sort arbitrary lists is a feature, not a bug. But you can't sort ones with complex numbers in them, because you also want '1+3j<3+1j' to raise an error. > Four separate classes of __comparison__ methods in a language that > doesn't (and can't and shouldn't) preclude or warn about rules regarding > which methods "conflict" with which other methods? I do not claim to be > an expert, but that doesn't seem very Pythonic to me. What "conflict"? Where are you getting the doesn't/can't/shouldn't prescription from? Which method you use depends on what you want to achieve: (Hypothetical Scheme) Object Identity? - use 'is' Mathematical Ordering? - use '__eq__' & friends Object Equivalence? - use '__equiv__' Arbitrary Ordering? (e.g. for list sorting) - use '__order__' The only caveat is to define sensible defaults for the cases where one fuction is not defined. But that shouldn't be too hard. __eqiv__ -> __eq__ -> is __order__ -> __lt__/__cmp__ > AIUI, __cmp__ exists for backwards compatibility, and __eq__ and friends > are flexible enough to cover any possible comparison scheme. Except if you want the situation where "[1+2j, 3+4j].sort()" works, and '1+3j < 3+1j' fails. I think the issue is you thinking along the lines of Mathematical numbers, where the four different comparisons colapse to one. Object identity? There is only one 'two' - heck, in pure mathematics, there isn't even a 'float two'/'int two' difference. Equivalence *is* mathematical equality, and the "arbitrary ordering" is easily defined as "true" ordering. It's only when you break away from mathematics do you see the divergance in behavior. From roy at panix.com Thu Jun 23 08:35:42 2005 From: roy at panix.com (Roy Smith) Date: Thu, 23 Jun 2005 08:35:42 -0400 Subject: Does a function like isset() exist in Python? References: Message-ID: In article , Patrick Fitzsimmons wrote: > Hi, > > I'm sure I should know this, but I can't find it in the manual. > > Is there a function in Python like the function in PHP isset()? It > should take a variable name and return True or False depending on > whether the variable is initialized. > > Thanks for any help, > Patrick The straight-forward thing would be to simply access the variable and catch any resulting NameError exception that's raised if it's not defined: try: x print "x is defined" except NameError: print "no it's not" Next question, why do you want to do this? I suspect for most idioms where you would something like this, the more pythonic way would be to set the variable to None at some point, then test to see if it's still None later on: x = None while foo: if blah: x = baz if x != None: print "x was assigned a value" From darkpaladin79 at hotmail.com Wed Jun 15 22:04:18 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Wed, 15 Jun 2005 22:04:18 -0400 Subject: help with sending mail in Program In-Reply-To: <000401c56f93$f4cd0640$ccbefea9@twilliams> Message-ID: Well everything was working in this mail sending script until. . .this: Traceback (most recent call last): File "mailvar.py", line 27, in ? sendToMe(subject, body) File "mailvar.py", line 8, in sendToMe send(me, me, subject, body) File "mailvar.py", line 16, in send msg = MIMEText(body) File "C:\Python24\lib\email\MIMEText.py", line 28, in __init__ self.set_payload(_text, _charset) File "C:\Python24\lib\email\Message.py", line 218, in set_payload self.set_charset(charset) File "C:\Python24\lib\email\Message.py", line 256, in set_charset cte(self) File "C:\Python24\lib\email\Encoders.py", line 63, in encode_7or8bit orig.encode('ascii') AttributeError: 'tuple' object has no attribute 'encode' heres my code(just made to test using the variables): from email.MIMEText import MIMEText from smtplib import SMTP x = 'python' y = 'python2' def sendToMe(subject, body): me = '"Ivan Shevanski" ' send(me, me, subject, body) def send(frm, to, subject, body): s = SMTP() s.set_debuglevel(1) s.connect('D421LN41') # s.ehlo('69.137.27.32') msg = MIMEText(body) msg['To'] = to msg['Subject'] = subject msg['From'] = frm s.sendmail(frm2, [to2], msg.as_string()) s.quit() if __name__ == '__main__': body = 'x is',x,'y is',y,'.Lets hope that works!' subject = 'Python3' sendToMe(subject, body) I really have no idea whats going on. . .help? -Ivan _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From cocklecowrie at yahoo.com Sat Jun 18 12:53:32 2005 From: cocklecowrie at yahoo.com (Cockle Cowrie) Date: Sat, 18 Jun 2005 09:53:32 -0700 (PDT) Subject: ANN: Concurrence 0.0.5.2 Alpha Message-ID: <20050618165332.34811.qmail@web31201.mail.mud.yahoo.com> On 6/17/05, Daniel Bickett wrote: > Concurrence is a networked file editing program that enables multiple > people to modify a document simultaneously. It is written entirely in > python, and uses the wxPython library for the GUI and the Twisted > library for networking. > > This marks the release of Concurrence 0.0.5.2 Alpha, and it can be > found at the following link: > > http://sourceforge.net/projects/concurrence/ > > It has been in development for just under three weeks now, and for > it's age it has quite a large feature set, including: > > * All modifications that occur in every client are sent to the server > (then to the other clients) real time and on a first-come, first-serve > basis > * The lines on which the carets of the other users in a given file > rest are highlighted > * A chat feature is included in each document window to eliminate the > necessity of a third party messenger client, while improving the > coordination of document editing > * All of the features expected of one's day-to-day text editor have > been implemented > * Python files are automatically detected and the syntax is > highlighted (in the near future this feature may be toggled at will) > > The project can be discussed on the #concurrence channel at > irc.freenode.net, or on the mailing list > concurrence-devel at lists.sourceforge.net. > -- > Daniel Bickett > dbickett at gmail.com > http://heureusement.org/ > __________________________________ Yahoo! Mail Stay connected, organized, and protected. Take the tour: http://tour.mail.yahoo.com/mailtour.html From correiajREMOVECAPS at hotmail.com Tue Jun 7 16:39:55 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Tue, 07 Jun 2005 20:39:55 GMT Subject: separate IE instances? References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> <1118165668.863841.291290@z14g2000cwz.googlegroups.com> Message-ID: > "Chris Curvey" wrote in message > news:1118165668.863841.291290 at z14g2000cwz.googlegroups.com... > > I would have given up on this a long time ago, but I can create two > > IEXPLORE processes simultaneously (and get the behavior I want) by just > > manually launching them from the Start menu. (Of course, that doesn't > > mean that I can launch them programmatically, but I'm hoping that > > someone can give me a definitive answer.) > > "J Correia" wrote in message news:LYlpe.38956$HI.25521 at edtnps84... > Right, I hadn't quite understood your problem when I posted my reply. The code > posted does work and allow navigation, etc. but you do have the problem with it > sharing the same session cookies (I'm also on Win2k). And to answer Martin, you > can definitely create as many iexplore.exe instances as you like in Windows. > > How to get Python to launch several instances with COM... not sure, although I'm > 99% certain it is doable. I'll hunt around and see if I can find a solution > which I'll post back. A very quick and very, very dirty method which might work is to start up the instances as follows: import win32api a = win32api.ShellExecute(0,None,"iexplore.exe",None,None,1) b = win32api.ShellExecute(0,None,"iexplore.exe",None,None,1) This creates the 2 instances of iexplore.exe in Windows you're looking for. Then use code like this to attach to the already running instances: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/269345 Haven't tried it because I'm certain there's a much more elegant solution, but depending on how quickly you need to get going it might be a possible short term work around until someone posts the better way. Perhaps you can also post some more info on what you're actually trying to achieve... make it easier for someone to help or even suggest alternatives. JC From cowie.rob at gmail.com Tue Jun 7 11:04:14 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 7 Jun 2005 08:04:14 -0700 Subject: Create our own python source repository In-Reply-To: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> Message-ID: <1118156654.634103.186390@o13g2000cwo.googlegroups.com> I'm not entirely sure what the point of your exercise is - if you have access to the net, ,why do you want to collate code examples? They are frequently updated in the cookbook so an offline repository would quickly become out of date. However.... you've aroused my interest in something related. We all know Python is significantly easier for novice programmers to grasp than, say, Java - I too am a newbie who started at uni with java and wished I hadn't. Tutorials are great, self paced learning is great, BUT, for the complete beginner a well structured, offline course with examples, exercises, tips etc. would be a brilliant resource. Python would fit the bill as a demonstration language to teach Object Orientation, flow control statements, other common constructs etc. A quick canvas of some IT teachers I know indicates support for such a thing - perhaps even in secondary shools (pre-uni). What does everyone think it would take to start such a project, and distribute it? or has it been done already? From p at ulmcnett.com Wed Jun 1 01:07:17 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 31 May 2005 22:07:17 -0700 Subject: Beginner question: Python types In-Reply-To: References: Message-ID: <429D4285.9050106@ulmcnett.com> Uppal, Deepali wrote: > Hello, Hello, and welcome to the world of Python. Don't take anything we say too personally, it is meant to help. > I am facing a bit of a problem due to python implicitly > attaching a type to an object. Ooh. In general, don't say 'implicit'. For the most part, Python only does things explicitly. See the Zen of Python by opening a Python interpreter and typing "import this". > I will briefly tell you the problem that > I am facing. I am trying to print the docstring of a test case in > my pyUnit base test class. I accept the name of the test class as > a command line option. So instead of printing the docstring of > the test case, it prints the docString of a string object. Which is expected, because all command line options are strings. I assume you are getting the command line option using the idiom: import sys options = sys.argv[1:] > I would like to give an example here > import test_script > > gettatr( test_script.test_class.test_case, ?__doc__?) I think you meant: print getattr(test_script.test_class.test_case, '__doc__') > With this simple code, I am able to print the docstring > of the test case. Yep, Python is simple and expressive. > However, since I accept the test case information as a command line > option. So instead of printing the docstring of the test case it > prints the docstring of a string object. Right, because all command line options are strings, since that is all the shell can really hand off to Python. > Is there someway, I can tell the script to change the type of > the object from string to an instancetype of a test case? In your first example, you import the test_script, and then do a getattr() on the test_class inside test_script.py. If you are trying to mimic that, and sending one or more test_script's, your code would look something like: import sys for test_module in sys.argv[1:] try: _module = __import__(test_module) _class = _module.test_class _case = _class.test_case print _case.__doc__ except ImportError: print "Couldn't import module '%s'. Skipping..." % test_module > I am quite a newbie in python so I would appreciate any help on this. The above should get you started, even though it won't satisfy your exact needs. -- Paul McNett http://paulmcnett.com From rkern at ucsd.edu Tue Jun 21 04:26:55 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 21 Jun 2005 01:26:55 -0700 Subject: A tool for Python - request for some advice In-Reply-To: <42B7C93B.4030306@po-box.mcgill.ca> References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> <42B7C93B.4030306@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote: > That suggests implementing the custom installation work in Python, and > having a bash script that will > > 1) determine if there is an existing Python install, > 2) if there is not, install Python in the standard way, > 3) using the now guaranteed to be there installation of Python, run > your Python script that does all of your custom installation, and > 4) if step (2) added a Python installation other than the one added by > step (3), perhaps remove it. Allow me to second that advice and also point out some work that should make step 3 easier in the, hopefully near, future: http://peak.telecommunity.com/DevCenter/EasyInstall -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From dan at nospam.com Thu Jun 23 11:48:43 2005 From: dan at nospam.com (Dan) Date: Thu, 23 Jun 2005 10:48:43 -0500 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <42b9d01e$0$2588$da0feed9@news.zen.co.uk> Message-ID: On 6/22/2005 9:51 PM, Peter Hansen wrote: > Will McGugan wrote: > >> Thanks for the replies. I think I'm going to go with sqllite for now. > > > Your list didn't mention a few things that might be critical. > Referential integrity? Type checking? SQLite currently supports > neither. Just make sure you check the list of supported features to see > that it really does what you need. > > -Peter So in SQLLite, what happens of you try to store XYZ in an integer field? From sjmachin at lexicon.net Mon Jun 20 04:54:59 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 20 Jun 2005 18:54:59 +1000 Subject: catch argc-argv In-Reply-To: References: Message-ID: <42B68463.90501@lexicon.net> mg wrote: > Hello, > > I am writting bindings for a FEM application. In one of my function > 'initModulename', called when the module is imported, I would like to > get the argc and argv arguments used in the main function of Python. This is an "interesting" way of writing bindings. Most people would provide an interface in terms of either a library of functions or a class or two. I don't recall ever seeing a module or package that did what you say you want to do. Consider that your module should NOT be tied to command-line arguments. Abstract out what are the essential inputs to whatever a "FEM application" is. Then the caller of your module can parse those inputs off the command line using e.g. optparse and/or can collect them via a GUI and/or hard code them in a test module and/or read them from a test data file or database. > So, my question is: does the Python API containe fonctions like > 'get_argc()' and 'get_argv()' ? > If you can't see them in the documentation, they aren't there. If they aren't there, that's probably for a good reason -- no demand, no use case. From rrr at ronadam.com Sat Jun 18 22:22:50 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 19 Jun 2005 02:22:50 GMT Subject: Loop until condition is true In-Reply-To: References: <1119074614.700809@yasure> Message-ID: <_F4te.143662$w15.114640@tornado.tampabay.rr.com> Joseph Garvin wrote: > Peter Otten wrote: > >> I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of >> "for >> (" in the Python 2.4 source, so using these rough estimates do-while >> still >> qualifies as "rarely used". >> >> Peter >> >> >> > That's 136 times you'd have to use an ugly hack instead. I definitely > wouldn't mind an until or do/while. I would happy with just having while: without a 1 or True to indicate a continuous loop. Having a if-break at the end doesn't bother me at all. while: if : break Being able to move the break point to where it's needed or have more than one is a feature and not a problem. IMHO of course. It also has the benefit that you have the option to do an extra bit of cleanup between the if and the break if you need to. The until or do-while doesn't give you that option. I suppose if an until : , could be made to be more efficient and faster than an if : ; break, then I'd be for that. while: until [: suite] # optional suite or block But I doubt it would be significantly faster than an if statement with a break. So the only benefit I see is you don't have to use the break keyword, and the exit conditions will stand out in blocks with a lot of if statements in them. Regards, Ron From __peter__ at web.de Thu Jun 2 02:43:52 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Jun 2005 08:43:52 +0200 Subject: creating a hex value References: <1285743.rKB6TKaXDy@teancum> <7xbr6pzzs6.fsf@ruckus.brouhaha.com> <429e2675@news.eftel.com> Message-ID: John Machin wrote: >> delim = chr(0x15) > > Ooooh -- a function with a constant arg; I wonder what that evaluates to? > > >>> chr(0x15) > '\x15' > > Sheeeesh. OK, let's double-check that: >>> chr(0x15) 'The argument is constant -- but not necessarily the /function/.' >>> Sheeeesh :-) Peter From hammer at maxwell.com Thu Jun 16 12:14:58 2005 From: hammer at maxwell.com (Maxwell Hammer) Date: Thu, 16 Jun 2005 12:14:58 -0400 Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') Message-ID: Hi all, This is related to an earlier post 'Help with thread related tracebacks'...for which I have had no feedback yet :-( How should a thread complete i.e. how should it exit? Reading the python online docs one gets the idea that simply returning is OK - but I'm not sure. Is it ok to do a sys.ext()? Use 'return' or just let them run out with no 'return' ??? thanks. From hancock at anansispaceworks.com Mon Jun 27 00:57:08 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 26 Jun 2005 23:57:08 -0500 Subject: Photo layout In-Reply-To: References: Message-ID: <200506262357.08230.hancock@anansispaceworks.com> On Sunday 26 June 2005 10:57 pm, Stephen Boulet wrote: > Is there a python solution that someone could recommend for the following: > > I'd like to take a directory of photos and create a pdf document with > four photos sized to fit on each (landscape) page. Probably you could do this with PIL + reportlab. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From erchamion.beren at gmail.com Fri Jun 10 10:34:09 2005 From: erchamion.beren at gmail.com (sinan ,) Date: Fri, 10 Jun 2005 17:34:09 +0300 Subject: about accessing mysql Message-ID: <59dfa145050610073423d742d1@mail.gmail.com> hi everybody, i have a small mysql connection code >>> import MySQLdb >>> db=MySQLdb.Connection(host="localhost",user="root",db="nux") Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/site-packages/MySQLdb/__init__.py", line 66, in Connect return Connection(*args, **kwargs) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 156, in __init__ self.autocommit(0) _mysql_exceptions.OperationalError: (1193, "Unknown system variable 'AUTOCOMMIT'") >>> these command works at my computer but when i want to do in my server, i get these messages as you seen, my both computer and server have same python, same MySQLdb module and same database with same priviliges.also how can i connect to remote database? is that work ? db=MySQLdb.Connection(host="192.168.0.120",user="root",db="nux") thank you. From cam.ac.uk at mh391.invalid Wed Jun 15 10:49:27 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 15 Jun 2005 15:49:27 +0100 Subject: non OO behaviour of file In-Reply-To: References: Message-ID: Robin Becker wrote: > I recently tried to create a line flushing version of sys.stdout using > > class LineFlusherFile(file): > def write(self,s): > file.write(self,s) > if '\n' in s: > self.flush() > > but it seems that an 'optimization' prevents the overriden write method > from being used. I had thought python was more regular than it appears > to be. > > Is there a better way to accomplish the intention of the above than > > class LineFlusherFile: > def __init__(self,*args): > self._f = open(*args) > def __getattr__(self,a): > return getattr(self._f,a) > def write(self,s): > self._f.write(s) > if '\n' in s: > self._f.flush() Well, you could use python -u: """-u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.""" Within pure Python there's not a better way that I know of. I keep a slightly-more generalized Surrogate class around to deal with this pattern, and then my LineFlusherFile would be a subclass of that. But it's the same thing, really. -- Michael Hoffman From steve at holdenweb.com Sat Jun 4 08:04:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 04 Jun 2005 08:04:05 -0400 Subject: Software licenses and releasing Python programs for review In-Reply-To: <20050602150655.GA30964@heaven.kostyrka.org> References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> Message-ID: Andreas Kostyrka wrote: > On Thu, Jun 02, 2005 at 01:57:25AM -0700, Robert Kern wrote: > >>And for thoroughness, allow me to add "even if they have no intention or >>desire to profit monetarily." I can't explain exactly why this is the >>case, but it seems to be true in the overwhelming majority of cases. >>Academic projects with non-commercial clauses languish in obscurity >>while academic Open Source projects thrive. The contributors to the Open > > Well, it's easily explained. (Well at least my motivation in this case) > I do not touch things that I cannot use "generally" and being a > "commercial" IT consultant this basically means: > *) opensource is better than commercial payware. > (because "for free" (as in beer) is usable in more contexts) > *) GPL is acceptable for much stuff, because I can install GPL'ed > stuff for a customer. > *) GPL is not acceptable for "library" stuff, because as a software > developer I'm sometimes forced to do "closed" stuff. > (Yep, even nowadays there are place where it's basically a legal > requirement.) > > Implications: > > *) qt is a bordercase: GPL for free, or commercial for pay. Not perfect but > good enough. > *) A number of O-R mappers for Python are of no relevance to me, > because they are GPL. O-R mappers are development libraries. > But this would only be a restriction if the code were to be redistributed, of course. It's stil perfectly legal to use it internaly without making the modified source available. > The idea is that I'm mostly not interested in learning tools that are > not of general use. > > So basically, stuff not meeting this criteria, is only interesting if > it's unique: > > *) commercial stuff is only interesting if there is no competing > open-source project. > *) GPL'ed "building blocks" are only interesting when there is no > competing LGPL version. Example: OCR on Linux/Unix. There are no > perfect solutions there so a GPL'ed solution might be > ok. (Especially because one can use OCR without linking with a lib > *grin*) > > Andreas regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From listserver at tdw.net Thu Jun 16 09:20:58 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 16 Jun 2005 14:20:58 +0100 Subject: Python & firewall control (Win32) Message-ID: <00f501c57276$3bcf35b0$ccbefea9@twilliams> Does anyone know of (personal/desktop) firewall that can be controlled via Python, or a Python Firewall package, or even something like DAXFi but not dormant ? The XP native firewall appears to have an API, but I'm not convinced I want to go that route unless it is relatively simple. Google is not my friend in this instance. TIA Tim From littlejohn.75 at news.free.fr Mon Jun 27 12:56:34 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 27 Jun 2005 16:56:34 GMT Subject: turn text lines into a list References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> <11c036grkf1d4d1@corp.supernews.com> Message-ID: <42c02fc2$0$20805$636a15ce@news.free.fr> [En-t?te "Followup-To:" positionn? ? comp.lang.python.] Le Mon, 27 Jun 2005 14:27:28 -0000, Grant Edwards a ?crit : > On 2005-06-27, Xah Lee wrote: >> i have a large number of lines i want to turn into a list. >> In perl, i can do >> >> @corenames=qw( >> rb_basic_islamic >> sq1_pentagonTile >> sq_arc501Tile >> sq_arc503Tile >> ); >> >> use Data::Dumper; >> print Dumper(\@corenames); >> >> ---------- >> is there some shortcut to turn lines into list in Python? > > corenames = [ "rb_basic_islamic", > "sq1_pentagonTile", > "sq_arc501Tile", > "sq_arc503Tile"] > Another way : (less typing of quotes) all_names = """ rb_basic_islamic sq1_pentagonTile sq_arc501Tile sq_arc503Tile """ corenames = all_names.split() Regards. From simon.brunning at gmail.com Mon Jun 20 04:42:36 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 20 Jun 2005 09:42:36 +0100 Subject: how to operate the excel by python? In-Reply-To: <42C7E766869C42408F0360B7BF0CBD9B014B619B@pnlmse27.pnl.gov> References: <42C7E766869C42408F0360B7BF0CBD9B014B619B@pnlmse27.pnl.gov> Message-ID: <8c7f10c60506200142423e28d1@mail.gmail.com> On 6/17/05, Hughes, Chad O wrote: > > I have posed a more complete answer to your question, however, it is quite a > large and It is awaiting approval. For now, xlRight = -4152. You can find > this out by opening up Excel and typing the ALT-F11 combination. From there > use the ObjectBrowser. For example if you type in the word "xlRight" you > will see that it is equal to -4152. I've had problems with these constants differing between versions before, so I don't recommend hard coding them. (This was in Word rather than Excel, AFAICR, but if Bill can do it to us once, he can do it to us twice.) Luckily, you can use the constants by name: PythonWin 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> import win32com.client >>> excel = win32com.client.gencache.EnsureDispatch("Excel.Application") >>> win32com.client.constants.xlRight -4152 -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From sjmachin at lexicon.net Thu Jun 2 19:07:47 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 09:07:47 +1000 Subject: Formatting Time In-Reply-To: References: Message-ID: <429f9142$1@news.eftel.com> rochoa at cimex.com.cu top-posted: > May be > > >>>>sec = 2472 >>>>"%d:%02d:%02d" % (int(sec/360), int(sec % 360 /60), int(sec % 60)) > > '6:05:12' > Could you possibly have meant 3600 instead of 360? From philippe at philippecmartin.com Tue Jun 28 18:37:45 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 22:37:45 GMT Subject: Embedding python in C - newbie References: <3Qfwe.519$Ox3.92@newssvr12.news.prodigy.com> Message-ID: Sorry, it is still not clear when I reread it: 1) I have a bunch of Python working modules 2) I need to compile "something" so external C applications can access 1) Thanks, Philippe Philippe C. Martin wrote: > Just to make sure i'm clear as I've been told about swig and pyrex: I > don't want to eventually have a python script call C modules, but rather a > main.c make calls to python functionnalities. > > I did add newbie in the title :-) > > Regards, > > Philippe > > > > Philippe C. Martin wrote: > >> Hi, >> >> Is there a program out there that would generate the C code to >> instantiate objects and call them: >> >> ex: miracle.exe -i mymodule.py -o module_internface.c ? >> >> I seem to recall a _yes_ to that but I got a memory overflow :-) >> >> Thanks, >> >> Philippe From ian at excess.org Tue Jun 14 09:16:56 2005 From: ian at excess.org (Ian Ward) Date: Tue, 14 Jun 2005 09:16:56 -0400 Subject: ANN: Urwid 0.8.8 with web_display Message-ID: <20050614131655.GA573@paintedblack> Announcing Urwid 0.8.8 ---------------------- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.8.8.tar.gz or: https://excess.org/urwid/urwid-0.8.8.tar.gz Summary: ======== This release adds a new web_display module that can emulate a console display within a web browser window, as well as other enhancements. Live demo of the web_display module: http://live.excess.org/ New in this release: ==================== - New web_display module that emulates a console display within a web browser window. Application must be run as a CGI script under Apache. Supports font/window resizing, keepalive for long-lived connections, limiting maximum concurrent connections, polling and connected update methods. Tested with Mozilla Firefox and Internet Explorer. - New BoxAdapter class for using box widgets in places that usually expect flow widgets. - New curses_display input handling with better ESC key detection and broader escape code support. - Shortened resize timeout on gradual resize to improve responsiveness. About Urwid =========== Urwid is a curses-based UI library for Python. It features fluid interface resizing, CJK support, multiple text layouts, simple attribute markup, powerful scrolling list boxes, flexible edit boxes and HTML screen shots. Urwid is released under the GNU LGPL. From rkern at ucsd.edu Wed Jun 15 21:43:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 15 Jun 2005 18:43:16 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118697529.173406.134460@g44g2000cwa.googlegroups.com> Message-ID: Robert Kern wrote: > Marc 'BlackJack' Rintsch wrote: >>It's fast enough to open the file and read the meta-data. The OP wants to >>decode the actual pixels. > > Okay. > > In [12]: %time d = img.getdata() > CPU times: user 0.31 s, sys: 1.43 s, total: 1.73 s > Wall time: 6.19 And for comparison: In [2]: f = open('foo.tiff') In [3]: %time s = f.read() CPU times: user 0.04 s, sys: 0.28 s, total: 0.32 s Wall time: 2.40 Of course, it's all a moot point since the OP actually has a different problem with PIL, not its speed. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From python at rcn.com Mon Jun 27 19:45:56 2005 From: python at rcn.com (Raymond Hettinger) Date: 27 Jun 2005 16:45:56 -0700 Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: <1119915956.776107.305040@g43g2000cwa.googlegroups.com> [Roy Smith] > I also think the published description is needlessly confusing. Why does > it use > > {'one': 2, 'two': 3} > > as the example mapping when > > {'one': 1, 'two': 2} > > would illustrate exactly the same point but be easier to comprehend. The > mapping given is the kind of thing I would expect to see in an obfuscated > programming contest. > > Also, what's the point of the last example: > > dict([(['one', 'two'][i-2], i) for i in (2, 3)]) > > It boils down to passing a list of tuples as an argument, which is already > illustrated by other examples. This is just a complicated and obtuse way > to construct the list of tuples. What does it add to the understanding of > how the dict() constructor works? If you can switch from indignation to constructive criticism, then consider sending a note to Andrew Kuchling suggesting ways to improve the examples. Raymond From piet at cs.uu.nl Thu Jun 16 11:45:12 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 16 Jun 2005 17:45:12 +0200 Subject: Set of Dictionary References: Message-ID: >>>>> Vibha Tripathi (VT) wrote: >VT> Hi Folks, >VT> I know sets have been implemented using dictionary but >VT> I absolutely need to have a set of dictionaries...any >VT> ideas how to do that? A set cannot contain duplicates. What happens when one of the dictionaries in the set is modified in such a way that it becomes equal to another element? Maybe you just need a list of dictionaries? Or maybe you want immutable dictionaries to put in the set. In that case you can define your own immutable dictionary class that defines a hash function. Ideally you would redefine the dictionary modification methods to make them generate error messages. For safety in the following code a copy is made of the dict. The values in the dict must be hashable, which usually means immutable. class immdict(dict): def __init__(self, somedict): self.data = somedict.copy() def __hash__(self): result = 0 for elt in self.data: result ^= hash(elt) ^ hash(self.data[elt]) return result def __repr__(self): return repr(self.data) __str__ = __repr__ d = immdict({1:0, 2:3}) s = Set() s.add(d) -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From mg.mailing-list at laposte.net Mon Jun 6 03:01:43 2005 From: mg.mailing-list at laposte.net (mg) Date: Mon, 06 Jun 2005 09:01:43 +0200 Subject: Help with pythonpath In-Reply-To: <8s65a1lbfrns7g6ecrqghtvkfh1lps30vg@4ax.com> References: <8s65a1lbfrns7g6ecrqghtvkfh1lps30vg@4ax.com> Message-ID: <42A3F4D7.4060209@laposte.net> Tim Roberts wrote: >Observer wrote: > > >>Hi, im a newbie both to python and this list. >>I hope someone can help me whith this: >> >>I have a directory structure like this: >>. >>|-- src >>| `-- pkg >>| |-- __init__.py >>| |-- main.py >>| `-- spkg1 >>| |-- __init__.py >>| `-- config.py >>`-- src2 >> `-- pkg >> |-- __init__.py >> `-- spkg2 >> |-- __init__.py >> `-- config2.py >> >>and main.py is a python script that contains this imports: >> >> >> >>from pkg.spkg1 import config >>from pkg.spkg2 import config2 > > >>executed in linux whith this: >> >>env PYTHONPATH=src:src2 src/pkg/main.py >>Traceback (most recent call last): >> File "src/pkg/main.py", line 4, in ? >> from pkg.spkg2 import config2 >>ImportError: No module named spkg2 >> >>changing the order of the python path only inverts the problem, is there >>any way to solve this without changing the directory structure? >> >> > >Nope. When Python goes to look for a package called "pkg", it starts at >the beginning of PYTHONPATH and stops as soon as it finds one. You either >need to use different names for the two packages (pkg1, pkg2), or use a >symbolic link to link spkg2 into the src directory. > > If I remember, I think you need to add an __init__.py file just in your directories src & src2. Moreover, you can add the path of src and src2 to the variable sys.path at the beginning of your main script (in that case, it not necessary to define PYTHONPATH) I hope I help you Mathieu From philippe at philippecmartin.com Fri Jun 24 13:14:30 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 24 Jun 2005 17:14:30 GMT Subject: Running Python interpreter in Emacs References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> Message-ID: Hi, Since I'm a Linux user, I went through the following procedure: I installed emacs 20.7.1 and Python 2.4 I installed python-mode 1.0A into site-lisp I added c:\python24 to my path I put this .emacs on c:\ (see further down - I'm sure you don't need half of it) And everyhing is working fine: python mode is recognized and Ctr-C-C opens a *Python Output* buffer with the results from my script: print 1 ==> 1 Hope that helps, Regards, Philippe ***************************************************************************** (custom-set-variables ;; custom-set-variables was added by Custom -- don't edit or cut/paste it! ;; Your init file should contain only one such instance. '(auto-compression-mode t nil (jka-compr)) '(case-fold-search t) '(current-language-environment "UTF-8") '(default-input-method "rfc1345") '(global-font-lock-mode t nil (font-lock)) '(nil nil t) '(outline-minor-mode t) '(pc-select-meta-moves-sexps t) '(pc-select-selection-keys-only t) '(pc-selection-mode t t) '(save-place t nil (saveplace)) '(show-paren-mode t nil (paren)) '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))) '(transient-mark-mode t)) ;(mouse-wheel-mode t) (setq indent-tabs-mode nil) ;;(speedbar) (custom-set-faces ;; custom-set-faces was added by Custom -- don't edit or cut/paste it! ;; Your init file should contain only one such instance. ) ;(setq any mode-customization variables you want here) (autoload 'visual-basic-mode "visual-basic-mode" "Visual Basic mode." t) (autoload 'python-mode "python-mode" "Python mode." t) (setq auto-mode-alist (append '(("\\.\\(py\\)$" . python-mode)) auto-mode-alist)) (setq auto-mode-alist (append '(("\\.\\(frm\\|bas\\|cls\\)$" . visual-basic-mode)) auto-mode-alist)) ***************************************************************************** Rex Eastbourne wrote: > Hi Skip and Philippe. I added the path for Python to PATH, but I still > get the same message (when I try executing the current buffer, I get > the message: "The system cannot find the path specified." > > Philippe, I have the above lines of code in my .emacs file. > > As for my environment, I'm running Emacs 21.4 on Windows XP. > > Thanks a lot! From philippe at philippecmartin.com Sat Jun 11 17:00:22 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 11 Jun 2005 21:00:22 GMT Subject: What is different with Python ? References: Message-ID: Thanks , I have gotten many answers already, some not posted. 1) Typing is not the issue - even with RT-Kernels, people use C++ 2) Yes I find dynamic binding very nice 3) "... you didn't give many examples of what you did for the last 18 years (except that that also included RT kernels). ...." assembly (losts) , basic, cobol, lisp, JAVA, c, c++, perl, Tcl, Java, JavaCard ..... I know the "interactive" aspect helps also, the runtime error/exception checking, the many libraries/tools, the responsiveness of the people on this newsgroup, the "introspectiveness" of the system, the cross-platform it deals with, the way it "pushes" people to code in a clean way, the GUI support, the stability, the extensibility (in and out) .... I'm sure you'll agree none of that can explain why after 1 week of playing with, I was more productive in Python than C/C++ just as I know my product (I will not describe it here as I am not marketing) would not exist today were it not for Python. 4) Yes I agree a mix ("... well spiced soup ...") seems to be the answer but my brain somehow wants to formalize it. Regards, Philippe Philippe C. Martin wrote: > I apologize in advance for launching this post but I might get enlightment > somehow (PS: I am _very_ agnostic ;-). > > - 1) I do not consider my intelligence/education above average > - 2) I am very pragmatic > - 3) I usually move forward when I get the gut feeling I am correct > - 4) Most likely because of 1), I usually do not manage to fully explain > 3) when it comes true. > - 5) I have developed for many years (>18) in many different environments, > languages, and O/S's (including realtime kernels) . > > > Yet for the first time I get (most) of my questions answered by a language > I did not know 1 year ago. > > As I do try to understand concepts when I'm able to, I wish to try and > find out why Python seems different. > > Having followed this newsgroup for sometimes, I now have the gut feeling > (see 3)) other people have that feeling too. > > > Quid ? > > Regards, > > Philippe From christoph.rackwitz at gmail.com Wed Jun 15 19:17:44 2005 From: christoph.rackwitz at gmail.com (Christoph Rackwitz) Date: 15 Jun 2005 16:17:44 -0700 Subject: splitting delimited strings In-Reply-To: References: Message-ID: <1118877463.931890.303530@z14g2000cwz.googlegroups.com> You could use regular expressions... it's an FSM of some kind but it's faster *g* check this snippet out: def mysplit(s): pattern = '((?:"[^"]*")|(?:[^ ]+))' tmp = re.split(pattern, s) res = [ifelse(i[0] in ('"',"'"), lambda:i[1:-1], lambda:i) for i in tmp if i.strip()] return res >>> mysplit('foo bar "baz foo" bar "baz"') ['foo', 'bar', 'baz foo', 'bar', 'baz'] From guettli at thomas-guettler.de Tue Jun 14 10:31:44 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 14 Jun 2005 16:31:44 +0200 Subject: ZCatalog for standalone Zodb? References: Message-ID: Am Tue, 14 Jun 2005 11:45:30 +0200 schrieb Almad: > Hello, > > is ZCatalog available for standalone zodb? As far as I read tutorial, the > relation to zope is obvious. > > I knew there is IndexedCatalog, but its not developed any more...and without > indexing, oodbms are unusable for cms, imo. Hi, There was someone who said that he has ported ZCatalog to "standalone" ZODB. Look in the archive of zodb-dev.AFAIK IndexedCatalog is still in development. Maybe the mailing list is calm, but I think it is not orphaned. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From duncan.booth at invalid.invalid Mon Jun 20 11:51:07 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jun 2005 15:51:07 GMT Subject: Couple functions I need, assuming they exist? References: Message-ID: Peter Hansen wrote: >> The target of the problems (my daughter) would prefer that the thousands >> be delimited. Is there a string function that does this? > > You refer to something like putting a comma between groups of three > digits, as in 1,000? This is locale-specific, and there's a "locale" > module that should have what you need. >>> import locale >>> locale.setlocale(locale.LC_ALL, '') 'English_United Kingdom.1252' >>> print locale.format("%d", 1000000, True) 1,000,000 >>> print locale.format("%.2f", 1000000, True) 1,000,000.00 >>> locale.setlocale(locale.LC_ALL, 'fr') 'French_France.1252' >>> print locale.format("%d", 1000000, True) 1?000?000 >>> print locale.format("%.2f", 1000000, True) 1?000?000,00 From roy at panix.com Fri Jun 24 12:14:39 2005 From: roy at panix.com (Roy Smith) Date: 24 Jun 2005 12:14:39 -0400 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Tom Anderson wrote: > The one thing i really do miss is method overloading by parameter > type. I used this all the time in java You do things like that in type-bondage languages like Java and C++ because you have to. Can you give an example of where you miss it in Python? If you want to do something different based on the type of an argument, it's easy enough to do: def foo (bar): if type(bar) == whatever: do stuff else: do other stuff replace type() with isistance() if you prefer. > No, it's not really possible in a typeless language, Python is not typeless. It's just that the types are bound to the objects, not to the containers that hold the objects. From simon.brunning at gmail.com Wed Jun 1 05:15:54 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 1 Jun 2005 10:15:54 +0100 Subject: Newbee question : List of packages In-Reply-To: References: Message-ID: <8c7f10c605060102155bc9d267@mail.gmail.com> On 6/1/05, S?bastien V. wrote: > I'm quite new in Python and I discover every day very interesting new > packages in this newsgroup : Is there somewhere on the web a list (as > complete as possible) in which main features of external packages are listed Try , or the (older) . That said, these days I usually just google for whatever I'm looking for. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rkern at ucsd.edu Thu Jun 2 00:14:08 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 01 Jun 2005 21:14:08 -0700 Subject: Beginner question: Logs? In-Reply-To: <1117685058.142351.123660@g47g2000cwa.googlegroups.com> References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: Svens wrote: > Hey thanks... > > Still getting an error message though. Here's what i'm doing: > ------ > import math > log10(15625) > ------ > -It says that log10 is not defined, but it is since the module is > imported, right? No, read the tutorial. import math math.log10(15625) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jabel at plus.net Tue Jun 7 11:17:20 2005 From: jabel at plus.net (John Abel) Date: Tue, 07 Jun 2005 16:17:20 +0100 Subject: ANN: ActivePython 2.4.1 for Mac OS X is now available! In-Reply-To: <20050607150658.GB5985@ActiveState.com> References: <20050607150658.GB5985@ActiveState.com> Message-ID: <42A5BA80.9080909@plus.net> Trent Mick wrote: >Today ActiveState is announcing support for Mac OS X. I'm happy to >announce that ActivePython 2.4.1 for Mac OS X is now available for free >download from: > > http://www.ActiveState.com/Products/ActivePython/ > >This brings the number of free ActivePython platforms to four -- with >the existing Linux, Solaris and Windows free downloads. > >Meanwhile, some of you may be interested to know that we are busily >working on bringing Komodo to Mac OS X. We expect to offer a beta in >August and release later this year. > >To keep up-to-date with our Mac OS X progress, betas and announcements, >we invite you to join our new mailing list: > osx-announce at ActiveState.com >You can join the OS X announce list on the ActiveState Programmer >Network (ASPN): > http://listserv.activestate.com/mailman/listinfo/osx-announce > > >What is ActivePython? >--------------------- > >ActivePython is ActiveState's quality-assured binary distribution of >Python. Builds for Linux, Mac OS X, Solaris and Windows are made freely >available. > >ActivePython includes the Python core and core extensions (zlib 1.2.1, >bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4) and is fully >compatible with other Python distributions of the same version. > >ActivePython also includes a wealth of Python documentation, including: >- the core Python docs; >- Andrew Kuchling's "What's New in Python" series; >- the Non-Programmer's Tutorial for Python; >- Mark Pilgrim's excellent "Dive into Python"; and >- a snapshot of the Python FAQs, HOWTOs and PEPs. > >Once installed on the Mac, you can find the ActivePython documentation >here: > /Library/Documentation/Help/ActivePython 2.4 Help/index.html >An online version of the docs can be found here: > http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html > >Thanks, and enjoy! > >Trent, Python Tech Lead > > > Komodo for OSX? Now that's something I would be interested in purchasing. J From derek.perriero at gmail.com Fri Jun 10 23:12:22 2005 From: derek.perriero at gmail.com (Derek Perriero) Date: Fri, 10 Jun 2005 23:12:22 -0400 Subject: Remove duplicates from list In-Reply-To: References: <17fc2016050609114439ad3fb0@mail.gmail.com> <17fc2016050609125328857d82@mail.gmail.com> Message-ID: <17fc201605061020127ee950c9@mail.gmail.com> This is just a follow up from your help Chris. Everything worked out beautifully. The method you suggested really cut down on the script time and allowed me to reduce a lot of redundant areas. Thanks again. -Derek On 6/9/05, Chris Lambacher wrote: > > You are probably going about solving the problem from the wrong direction: > > Try something like this, overly verbose variable names used on purpose: > > regHours = context.getMainPrint(); > > #let a dictionary do the grouping for us > hours_to_libraries_dic = {} > for lib in regHours: > key = lib.Monday + lib.Tuesday + lib.Wednesday + lib.Thursday + > lib.Friday + lib.Saturday + lib.Sunday > try: > # if the key already exists add to the list of libraries > hours_to_libraries_dic[key].append(lib) > except KeyError: > # if the key does not exists, create a new library list > hours_to_libraries_dic[key] = [lib] > > > #print out the timetable > for lib_group in hours_to_libraries_dic.values(): > print " and ".join([lib.libraryName for lib in lib_group]) > a_lib = lib_group[0] > print " Monday", a_lib.Monday > print " Tuesday", a_lib.Tuesday > print " Wednesday", a_lib.Wednesday > ....(you get the idea) > print " Sunday", a_lib.Sunday > print > > > > > -Chris > > On 6/9/05, Derek Perriero wrote: > > Sorry for not being more clear. I'm using Zope to store the hours of > each > > library on the campus. The hours of each library will be set on a basis > of > > Monday - Friday. i.e. Monday for a specific library, let's say Downtown > > Campus Library will stored as an attribute of 8am - 9pm, in Zope, and > each > > day till Friday will be stored as the hours dictate. I'm generating a > > print-out based on these hours and info for the general public. The goal > of > > mine is to group all the libraries under one heading if they have the > exact > > same hours, to cut back on redundancy when a user looks at it. > > So when I say: collect = item.Monday + item.Tuesday + item.Wednesday + > > item.Thursday + item.Friday + item.Saturday + item.Sunday, the order is > > already this preset configuration. I want 'collect' to be static so it > can > > compare it against another libraries hours and group it if necessary. > The > > libraries that fail to be duplicates of other libraries will be > generated as > > usual under the grouped libraries. They will have a single heading. > > > > An example can be seen here of what I am trying to achieve: > > http://www.libraries.wvu.edu/hours/summer.pdf > > These are the outputs I failed to mention last time. > > What I want: > > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', > '8am - > > 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - > > 8pm9am - 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - > 5pm9am - > > 5pm9am - 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am > - > > 5pm10am - 5pm10am - 5pmClosed'] > > > > What I am getting now: > > > > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', > '8am - > > 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am > - > > 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - > > 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - > 5pm9am - > > 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am > - > > 5pm10am - 5pmClosed'] > > > > Thanks, > > -Derek > > > > > > On 6/9/05, Chris Lambacher wrote: > > > It is very unclear what you are trying to do. Why not explain what > > > you want the output to be. You will get better answers. > > > > > > As a first stab at what you are doing wrong: > > > collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday > > > + item.Friday + item.Saturday + item.Sunday > > > > > > The above is string addition and the result is a string. The ouput > > > you provide is in fact a list with no duplicates, i.e. there are no > > > two strings the same. > > > > > > If order is not important to you a structure that will give you an > > > 'unordered list with no duplicates' is a set (available in the std > > > library in Python 2.3 and 2.4, see the cookbook for recipies for > > > earlier versions of Python). Note that sets are unordered, i.e. no > > > guarentee is made about what order the elements are accessed in when > > > you iterate over them. > > > > > > -Chris > > > > > > On 6/9/05, Derek Perriero < derek.perriero at gmail.com> wrote: > > > > I've been un-triumphantly trying to get a list of mine to have no > > repeats in > > > > it. First, I'm pulling attributes from Zope and forming a list. > Next, > > I'm > > > > pulling those same values and comparing them against the same list > and > > if > > > > the values equal each other and are not already in the list, they > append > > to > > > > my 'nodupes' list. My current result is showing what I put in I am > > getting > > > > out. Below the code is my output of 'nodupes' list. Here's the > > snippet. > > > > > > > > regHours = context.getMainPrint(); <---attributes from Zope > > > > > > > > libslist = [] > > > > nodupes = [] > > > > > > > > #collect libraries > > > > for libs in regHours: > > > > cache = libs.Monday + libs.Tuesday + libs.Wednesday + libs.Thursday+ > > > > libs.Friday + libs.Saturday + libs.Sunday > > > > libslist.append (cache) > > > > > > > > #pull repeated values > > > > for item in regHours: > > > > collect = item.Monday + item.Tuesday + item.Wednesday + > item.Thursday > > + > > > > item.Friday + item.Saturday + item.Sunday > > > > libName = item.libraryName > > > > > > > > for libs in libslist: > > > > if collect == libs and libs not in nodupes: > > > > nodupes.append(libs) > > > > > > > > My Current Output: > > > > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', > > '8am - > > > > 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - > 9pm8am > > - > > > > 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - > 8pm9am - > > > > 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - > > 5pm9am - > > > > 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - > 5pm10am > > - > > > > 5pm10am - 5pmClosed'] > > > > > > > > Thanks > > > > > > > > > > > > > > > > > > > > > > > > -- > > > > Perriero, Derek > > > > derek.perriero at gmail.com > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > > > > > > -- > > > Christopher Lambacher > > > lambacck at computer.org > > > > > > > > > > > -- > > Perriero, Derek > > derek.perriero at gmail.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > Christopher Lambacher > lambacck at computer.org > -- Perriero, Derek derek.perriero at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Jun 15 19:35:11 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Jun 2005 09:35:11 +1000 Subject: splitting delimited strings In-Reply-To: References: Message-ID: <42B0BB2F.404@lexicon.net> Mark Harrison wrote: > What is the best way to process a text file of delimited strings? > I've got a file where strings are quoted with at-signs, @like this at . > At-signs in the string are represented as doubled @@. > > What's the most efficient way to process this? Failing all > else I will split the string into characters and use a FSM, > but it seems that's not very pythonesqe. > > @rv@ 2 @db.locks@ @//depot/hello.txt@ @mh@ @mh@ 1 1 44 > @pv@ 0 @db.changex@ 44 44 @mh@ @mh@ 1118875308 0 @ :@@: :@@@@: @ > >>> import csv >>> list(csv.reader(file('at_quotes.txt', 'rb'), delimiter=' ', quotechar='@')) [['rv', '2', 'db.locks', '//depot/hello.txt', 'mh', 'mh', '1', '1', '44'], ['pv' , '0', 'db.changex', '44', '44', 'mh', 'mh', '1118875308', '0', ' :@: :@@: ']] >>> From skip at pobox.com Wed Jun 22 19:01:51 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 22 Jun 2005 18:01:51 -0500 Subject: PEP 304 - is anyone really interested? Message-ID: <17081.60895.24439.92843@montanaro.dyndns.org> I wrote PEP 304, "Controlling Generation of Bytecode Files": http://www.python.org/peps/pep-0304.html quite awhile ago. The first version appeared in January 2003 in response to questions from people about controlling/suppressing bytecode generation in certain situations. It sat idle for a long while, though from time-to-time people would ask about the functionality and I'd respond or update the PEP. In response to another recent question about this topic: http://mail.python.org/pipermail/python-list/2005-June/284775.html and a wave of recommendations by Raymond Hettinger regarding several other PEPs, I updated the patch to work with current CVS. Aside from one response by Thomas Heller noting that my patch upload failed (and which has been corrected since), I've seen no response either on python-dev or comp.lang.python. I really have no personal use for this functionality. I control all the computers on which I use Python and don't use any exotic hardware (which includes Windows as far with its multi-rooted file system as far as I'm concerned), don't run from read-only media or think that in-memory file systems are much of an advantage over OS caching. The best I will ever do with it is respond to people's inputs. I'd hate to see it sit for another two years. If someone out there is interested in this functionality and would benefit more from its incorporation into the core, I'd be happy to hand it off to you. So speak up folks, otherwise my recommendation is that it be put out of its misery. Skip From devlai at gmail.com Thu Jun 30 23:09:02 2005 From: devlai at gmail.com (Devan L) Date: 30 Jun 2005 20:09:02 -0700 Subject: How to run commands in command line from a script In-Reply-To: References: Message-ID: <1120187342.545767.225650@g43g2000cwa.googlegroups.com> The code module, perhaps? http://www.python.org/doc/2.4.1/lib/module-code.html From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Jun 4 07:16:02 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 04 Jun 2005 11:16:02 +0000 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: <42a176d0$1_2@newspeer2.tds.net> References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> <42A1715F.5060101@jessikat.fsnet.co.uk> <42a176d0$1_2@newspeer2.tds.net> Message-ID: <42A18D72.5000808@jessikat.fsnet.co.uk> Kent Johnson wrote: > Robin Becker wrote: > >> Ilpo Nyyss?nen wrote: >> >>> >>> with locking(mutex), opening(readfile) as input: >>> ... >> >> >> with EXPR as x: >> BLOCK >> >> EXPR can be a tuple so the above would be ambiguous. > > > I don't think EXPR can be a tuple; the result of evaluating EXPR must > have __enter__() and __exit__() methods. *x* can be a tuple. > > Kent Well perhaps this would fly then. I reread the PEP and it says EXPR is arbitrary, but cannot be an expression list so maybe this was already considered and rejected. -- Robin Becker From rkern at ucsd.edu Wed Jun 29 15:26:03 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 29 Jun 2005 12:26:03 -0700 Subject: Graphs/statistics using wxPython In-Reply-To: <42c2f21a$1@griseus.its.uu.se> References: <42c2df8b$1@griseus.its.uu.se> <42c2e859$1@griseus.its.uu.se> <42c2f21a$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Robert Kern wrote: > [---] > >>It's okay. Just about every Pythonista in the sciences has, at one time >>or another, started a plotting library. It's a rite of passage. Welcome >>to the club. :-) > > Question: I need to install SciPy in order to use matplotlib, No you don't. > but on > the download page I see that there are versions for Python 2.2.x and > 2.3.x. I use 2.4.1 -- will bad things happen if I try to use the build > for 2.3.x? Yes. Scipy has many extension modules; such modules built for 2.3.x won't work for 2.4.x, etc. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From bruce+usenet at cenderis.demon.co.uk Sun Jun 5 16:43:16 2005 From: bruce+usenet at cenderis.demon.co.uk (Bruce Stephens) Date: Sun, 05 Jun 2005 21:43:16 +0100 Subject: GUI builders considered harmful References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> <86fyvwa91z.fsf_-_@guru.mired.org> Message-ID: <87acm48rh7.fsf@cenderis.demon.co.uk> Mike Meyer writes: [...] > The first, and most obvious, thing that GUI builders do is force the > developer to specify an exact position - if not size - for the > graphical elements of the UI. They do? I don't remember them doing that. I just downloaded SpecTcl (a oldish example) just to check, and that doesn't. I presume more recent ones work no less well? I seem to remember that the GUI builder in Visual Studio didn't seem to be particularly sane (I couldn't seem to work out how to get a dialog to resize appropriately to accommodate different font sizes, for example), but I assumed that was just me failing to understand something. [...] From cf_1957 at hotmail.com Fri Jun 3 06:08:39 2005 From: cf_1957 at hotmail.com (chris) Date: Fri, 03 Jun 2005 10:08:39 GMT Subject: decimal and trunkating References: <429f0656$0$32668$626a14ce@news.free.fr> <3g8fcjFarp9dU1@individual.net> <8f-dnecR35jVkwLfRVn-tw@powergate.ca> <3g8kk4Fb5v3dU1@individual.net> Message-ID: "Reinhold Birkenfeld" wrote in message news:3g8kk4Fb5v3dU1 at individual.net... > Peter Hansen wrote: > > Reinhold Birkenfeld wrote: > >> He is speaking of Decimals... > >> > >> d = Decimal("199.999") > >> d._round(5, decimal.ROUND_DOWN) > > > > Is one really supposed to call the underscore methods like that? > > Umm... no, I think not ;) But I couldn't find something better. > > Reinhold I'm new to Python ... and I've used decimal._round() as above. What's the deal with using underscore methods? (A link will do if that'll save you some typing). From guettli at thomas-guettler.de Thu Jun 2 03:40:52 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Thu, 02 Jun 2005 09:40:52 +0200 Subject: ConfigParser, mapping one key to multiple values References: Message-ID: Am Wed, 01 Jun 2005 17:18:42 -0500 schrieb Larry Bates: > I accomplish this by using the following construct > with ConfigParser: > > [sync files] > ignore_001=.*/foodir/.*\.pyc > ignore_002=.*/foodir/.*~ Hi, I found out, that you can have newlines in the value: ignore_regex = .*/CVS(/.*)?$ .*/\.cvsignore$ .*\.pyc$ .*/\.# If you call split() on the value, you get the list you need. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From chad.hughes at pnl.gov Wed Jun 15 20:26:43 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Wed, 15 Jun 2005 17:26:43 -0700 Subject: Finding Word and switch focus to it Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6185@pnlmse27.pnl.gov> Consider reading this post. It highlights how to do what you want: http://mail.python.org/pipermail/python-win32/2002-April/000322.html Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of John Henry Sent: Wednesday, June 15, 2005 3:21 PM To: python-list at python.org Subject: Finding Word and switch focus to it Does anybody know how to find an opened copy of Word and switch focus to it, wait until Word is closed, before continuing my Python script? I tried to search for the answer from Google and nothing stands out. Running under Windows XP. Thanks, -- John -- http://mail.python.org/mailman/listinfo/python-list From agriff at tin.it Wed Jun 1 16:38:58 2005 From: agriff at tin.it (Andrea Griffini) Date: Wed, 01 Jun 2005 20:38:58 GMT Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <9SXme.22456$Is4.3402@attbi_s21> <3g5tlqFaq4meU1@news.dfncis.de> Message-ID: <927s915p5t5l302u8vcbpmvrokdm64hb39@4ax.com> On Wed, 01 Jun 2005 16:07:58 +0200, Matthias Buelow wrote: >With a few relaxations and extensions, you can get a surprisingly useful >language out of the rigid Pascal, as evidenced by Turbo Pascal, one of >the most popular (and practical) programming languages in the late 80ies >/ start of the 90ies. It was not a language. It was a product in the hand of a single company. The difference is that a product can die at the snaps of a marketroid, no matter how nice or how diffuse it is. Andrea From rrosa at usp.br Wed Jun 8 12:30:38 2005 From: rrosa at usp.br (rrosa at usp.br) Date: Wed, 08 Jun 2005 13:30:38 -0300 Subject: two labels in the window but in diferent time Message-ID: <1118248238.42a71d2e0c6e0@webmail.usp.br> Hi there, I am trying to create a window that appears one label1="First Message" and after of 3,4 seconds I would like to append another label in the same window label2="Second Message" bellow of the first label, but I can only show both labels in the same time, and not in diferent time in the same window, someone knows something about??? Gratefully! ----> my code: from anygui import * import win32api # Make components here app = Application() # Add components to the Window w = Window() w.set(title='Hello, again', size=(300,200)) lab = Label(text='Hello, again!', position=(10,10)) lab1 = Label(text='Hello, again!', position=(10,40)) app.add(w) w.add(lab) win32api.Sleep(2000) w.add(lab1) app.run() From lee at example.com Tue Jun 28 18:23:40 2005 From: lee at example.com (Lee Harr) Date: Tue, 28 Jun 2005 22:23:40 GMT Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119988656.668457.202660@g43g2000cwa.googlegroups.com> Message-ID: > make something that will work for him, am I correct? The other > alternative is to install console mode linux on it and hope that the > ncurses library can be used by python. The system could be as low as a > 486 dx2 66 with maybe 16 megs of ram. Well, I just thought I'd give you > people more info on the situation. > That's almost exactly what I was given about 5 years ago. The system I created uses a postgresql database and a python/ncurses frontend. Over the years, the system has become quite a bit more complex and I have moved to pentium systems with as much ram as I can scrounge up. They work quite well. We get pentium machines for free all the time. People are having a hard time getting rid of them. We use them for my database app or as thin terminals in our computer lab. From devrim.erdem at gmail.com Thu Jun 9 09:58:26 2005 From: devrim.erdem at gmail.com (DE) Date: 9 Jun 2005 06:58:26 -0700 Subject: Windows Installer with Debug Dlls and Libs Message-ID: <1118325506.087132.64400@g44g2000cwa.googlegroups.com> Hello, I have a problem with python builds since some time. On windows, it is not a good idea to link your debug build to release builds of libs and dlls. But python installer gives you only release builds. So I need to build python myself, no problem, but .... I have never managed to setup python like the way installer does. (I guess it does some registry and env var tricks.) For example, - it is not possible to install extensions like wxPython, because the wxPython installer doesn't like my custom installation - WinCVS never gets my custom python installation and so on. Can you give me any hints on this nasty problem ? Thanks, DE From der.rudi at planet-dot-nl.no-spam.invalid Thu Jun 30 03:41:06 2005 From: der.rudi at planet-dot-nl.no-spam.invalid (DeRRudi) Date: Thu, 30 Jun 2005 07:41:06 +0000 (UTC) Subject: Open running processes References: Message-ID: Well i want a external app to maximize and minimize my app. And later on i want the external one to send some data. Thought this would be the most easy (and fast) way! Greetz From cantabile.03 at wanadoo.fr Tue Jun 14 07:21:45 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Tue, 14 Jun 2005 13:21:45 +0200 Subject: Get drives and partitions list (Linux) In-Reply-To: <566dnbxCE-OAuTPfRVn-hg@powergate.ca> References: <42accf62$0$11720$8fcfb975@news.wanadoo.fr> <42ae0810$0$11707$8fcfb975@news.wanadoo.fr> <566dnbxCE-OAuTPfRVn-hg@powergate.ca> Message-ID: <42aebdca$0$1218$8fcfb975@news.wanadoo.fr> Thanks for the answer and help. Cheers :) Peter Hansen wrote: > cantabile wrote: > >> Hi, Peter >> Thanks for the reply. I'll check popen(). >> But you said I should not rely on fdisk... Why ? And should I prefer >> sfdisk ? Why ? > > > I was under the impression that fdisk was older and more primitive, but > a quick check shows I'm probably not only wrong, but had it backwards! > (The man page for fdisk says "try parted, then fdisk, then sfdisk" > basically...) > > Also, as you saw in Jeff's reply, there's a commands.getoutput() > function that does basically what popen() would do, so just use whatever > seems simplest. > > -Peter From bvande at po-box.mcgill.ca Sat Jun 18 04:16:10 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 18 Jun 2005 04:16:10 -0400 Subject: Python documentation problem In-Reply-To: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Message-ID: <42B3D84A.9050406@po-box.mcgill.ca> Xah Lee said unto the world upon 18/06/2005 03:49: > Python documentation, > http://python.org/doc/2.4.1/lib/typesfunctions.html > > ----------------- > 2.3.10.3 Functions > > Function objects are created by function definitions. The only > operation on a function object is to call it: func(argument-list). > > There are really two flavors of function objects: built-in functions > and user-defined functions. Both support the same operation (to call > the function), but the implementation is different, hence the different > object types. > > See the Python Reference Manual for more information. > ----------------- > > Fuck the python doc wasted my time. Fuck python coders. > Each time i tried to use python doc and got frustrated because it being > grossly incompetent, i'll post a message like this, no more frequent > than once a week. This will go on as long the python community does > nothing to fix it or that i remain coding in python. > For reference, see > http://xahlee.org/perl-python/re-write_notes.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ I'm sure I will regret this in the morning . . . . Xah, since the docs are a community effort, you surely can (and have) pointed to genuine blemishes in them. I am however at a loss to understand just what the perceived problem is here. 5 short sentences, one defining a term, 1 stipulating the interface, two pointing out and clearing up a potential cause of confusion, and a reference. All are clear, and score quite well on the content:words measure to boot. (Certainly it is clearer and more informative than the words either you or I have here added.) What's your complaint? Not enough cursing? Best, Brian vdB From rkern at ucsd.edu Mon Jun 13 16:36:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 13 Jun 2005 13:36:51 -0700 Subject: Tiff Image Reader/writer In-Reply-To: <1118694007.688607.124530@z14g2000cwz.googlegroups.com> References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> Message-ID: PyPK wrote: > nothing fancy. I just want to be able to read a tiff image, get pixel > values, write back to a tiff file. [An aside: please quote the message you are replying to.] Why doesn't the PIL satisfy this need? Or are you just collecting a list of packages with this capability? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From iny+news at iki.fi Sat Jun 4 01:11:08 2005 From: iny+news at iki.fi (Ilpo =?iso-8859-1?Q?Nyyss=F6nen?=) Date: Sat, 04 Jun 2005 08:11:08 +0300 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Nicolas Fleury writes: > What about making the ':' optional (and end implicitly at end of current > block) to avoid over-indentation? > > def foo(): > with locking(someMutex) > with opening(readFilename) as input > with opening(writeFilename) as output > ... How about this instead: with locking(mutex), opening(readfile) as input: ... So there could be more than one expression in one with. > would be equivalent to: > > def foo(): > with locking(someMutex) > with opening(readFilename) as input > with opening(writeFilename) as output > ... The thing is that with normal try-finally block, you can add more things to it easily. This kind of with thing does not allow adding more stuff to it in any other way than adding more indentation. Anyway, I like the idea of the PEP too. -- Ilpo Nyyss?nen # biny # /* :-) */ From gsakkis at rutgers.edu Tue Jun 28 12:56:41 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 28 Jun 2005 09:56:41 -0700 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> <42c1662d$0$26260$626a14ce@news.free.fr> Message-ID: <1119977801.449923.128330@o13g2000cwo.googlegroups.com> > "bruno modulix" wrote: > George Sakkis wrote: > > I'd love to see IPython replace the standard interpreter. > I dont. Care to say why ? George From tprimke at interia.pl Fri Jun 24 05:44:44 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jun 2005 02:44:44 -0700 Subject: A tool for Python - request for some advice In-Reply-To: References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> <42B7C93B.4030306@po-box.mcgill.ca> Message-ID: <1119606284.258828.233250@g14g2000cwa.googlegroups.com> I've heard about this "EasyInstall" and I like this idea. If EI becomes a part of Python's standard library, my script will use it. From wirtz at dfn.de Tue Jun 21 10:01:42 2005 From: wirtz at dfn.de (Holger Wirtz) Date: Tue, 21 Jun 2005 16:01:42 +0200 Subject: How do I access avariable named "return"? Message-ID: Hi, I have a small problem: I have a WSDL file where different functions are described. It worked perfectly until I have a function which has a return-value named "return": Here is my program: --- cut here --- from SOAPpy import WSDL wsdlFile = 'mypbx.wsdl' server = WSDL.Proxy(wsdlFile) version=server.Version() #print version.GatekeeperID # Works fine #print version.FirmwareVersion # Works also resp=server.Initialize(user="Wirtz, Holger - DFN-Verein",appl="PySOAP") print resp print resp.return --- cut here --- When the line "print resp.return" is comented out I got: : {'return': '221', 'key': '1424926643'} But with the "print resp.return" I got: File "pywsdl.py", line 10 print resp.return ^ SyntaxError: invalid syntax I think this seems to be a problem due to the use of a forbidden word. But I have no chance to change the WSDL definition, so: How can I get the variable resp.return? Any suggestions? Thanks, Holger From siyer at Princeton.EDU Fri Jun 10 17:04:09 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Fri, 10 Jun 2005 17:04:09 -0400 Subject: bind in Tkinter Message-ID: <25a1dee62fbce.42a9c809@Princeton.EDU> I believe the quit function is built in. Anyway, I get the same type of error if I substitute a function that I have defined. Shankar ----- Original Message ----- From: VK Date: Friday, June 10, 2005 4:53 pm Subject: Re: bind in Tkinter > Shankar Iyer (siyer at Princeton.EDU) wrote: > > I have been trying to learn how to associate keyboard events with > actions taken by a Python program using Tkinter. From what I've > read online, it seems that this is done with the bind methods. In > one of my programs, I have included the following: > > > > self.enternumber = Entry(self) > > self.enternumber.bind("",self.quit) > > self.enternumber.pack({"side":"top"}) > > > > It seems to me that, as a result of this code, if the enternumber > Entry widget is selected and then the key is pressed, then > the program should quit. Indeed, it seems that the program does > attempt to quit, but instead an error message appears claiming that > quit() takes 1 argument but 2 are given. I get the same type of > error if I replace self.quit with some function that I have > written. I am not sure how to fix this problem and hope that > someone here can spot my error. Thanks for your help. > > > > Shankar > > > > > Have you defined quit function? > -- > http://mail.python.org/mailman/listinfo/python-list > From simon.brunning at gmail.com Wed Jun 29 05:55:58 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 29 Jun 2005 10:55:58 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: <11c343ho6i6hv17@news.supernews.com> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> Message-ID: <8c7f10c605062902556b1ed5af@mail.gmail.com> On 6/28/05, John Roth wrote: > I'd definitely like to see ctypes. I can agree with the segfault > issue, but I think that some design work would eliminate that. I'm not sure that it would. Ctypes allows you, as one colleague memorably put it, to "poke the operating system with a stick". You are always going to be able to use ctypes to provoke spectacular crashes of the kind that you can never get with 'ordinary' Python. Having said that, I'd like to see ctypes in the standard library anyway, with a suitably intimidating warning in the docs about the trouble you can get yourself into with it. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From timothy.williams at nvl.army.mil Wed Jun 8 13:01:44 2005 From: timothy.williams at nvl.army.mil (timothy.williams at nvl.army.mil) Date: 8 Jun 2005 10:01:44 -0700 Subject: running distutils installer without admin on windows References: <1118241029.833151.252720@g47g2000cwa.googlegroups.com> <1118241612.999333.224880@f14g2000cwb.googlegroups.com> Message-ID: <1118247598.432934.169860@g14g2000cwa.googlegroups.com> I didn't build the installer, someone else did. I did get the source and installed cygwin to see if I could recreate it; at least build the library, but when I tried to do a build_ext I got a message saying I needed to have the .NET SDK installed. From danricofer at gmail.com Thu Jun 9 14:09:27 2005 From: danricofer at gmail.com (Daniel) Date: 9 Jun 2005 11:09:27 -0700 Subject: Changing entities In-Reply-To: <42a6ed6e$1_1@newspeer2.tds.net> References: <1118235783.224018.281490@g44g2000cwa.googlegroups.com> <42a6ed6e$1_1@newspeer2.tds.net> Message-ID: <1118340567.897351.259050@z14g2000cwz.googlegroups.com> Hi Kent Thanks for your help, it worked sucessfully. I have another question, I think it is a stupid and simple but... I need match a regular expression, change it erasing the other strings after this. Just like: a = "I'm going send to out of space, find another race" And I want to match "space" instance, and erase the other. Thank you From rkern at ucsd.edu Tue Jun 28 11:37:24 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 28 Jun 2005 08:37:24 -0700 Subject: Dictionary to tuple In-Reply-To: References: <42c169d0$0$23811$626a14ce@news.free.fr> Message-ID: Erik Max Francis wrote: > bruno modulix wrote: > >>Err... don't you spot any useless code here ?-) >> >>(tip: dict.items() already returns a list of (k,v) tuples...) > > But it doesn't return a tuple of them. Which is what the tuple call > there does. The useless code referred to was the list comprehension. >>> t = tuple([(k,v) for k,v in d.iteritems()]) versus >>> t = tuple(d.items()) or even >>> t = tuple(d.iteritems()) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kveretennicov at gmail.com Tue Jun 21 17:59:34 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 23:59:34 +0200 Subject: utf8 silly question In-Reply-To: <20050621183502.GC13744@unpythonic.net> References: <1374382022.20050621191607@bounce-software.com> <20050621183502.GC13744@unpythonic.net> Message-ID: <4660fe300506211459700a3b1d@mail.gmail.com> On 6/21/05, Jeff Epler wrote: > If you want to work with unicode, then write > us = u"\N{COPYRIGHT SIGN} some text" ...and you can get unicode character names like that from unicodedata module: >>> import unicodedata >>> unicodedata.name(unichr(169)) 'COPYRIGHT SIGN' See also http://www.unicode.org/charts/charindex.html - kv From steven.bethard at gmail.com Sun Jun 5 01:40:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 23:40:45 -0600 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Nicolas Fleury wrote: > I prefer the optional-indentation syntax. The reason is simple (see my > discussion with Andrew), most of the time the indentation is useless, > even if you don't have multiple with-statements. So in my day-to-day > work, I would prefer to write: > > def getFirstLine(filename): > with opening(filename) as file > return file.readline() > > than: > > def getFirstLine(filename): > with opening(filename) as file: > return file.readline() One of the beauties of PEP 343 is that it can be explained simply in terms of current Python syntax. The expression: with EXPR as VAR: BLOCK is equivalent to: abc = EXPR exc = (None, None, None) VAR = abc.__enter__() try: try: BLOCK except: exc = sys.exc_info() raise finally: abc.__exit__(*exc) Can you do the same thing for your proposal? As I understand it you want some sort of implicitly-defined BLOCK that starts the line after the with statement and runs to the end of the current block... Do you think the benefit of less indentation outweighs the added complexity of explaining the construct? I still can't think of a good way of explaining the semantics you want. If you could provide an explanation that's simple and as explicit as Guido's explanation in PEP 343, I think that would help your case a lot. STeVe P.S. I think it's a great sign that people are mainly squabbling about syntax here. More likely than not, Guido's already made his mind up about the syntax. So, since no one seems to have any real problems with the semantics, I'm hopeful that we'll get a direct implementation of PEP 343 in the next Python release. =) From jan.danielsson at gmail.com Thu Jun 2 08:43:40 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Thu, 02 Jun 2005 14:43:40 +0200 Subject: Newbie question: Allocation vs references Message-ID: <429efdbf$1@griseus.its.uu.se> Hello all, Behold: ---------- a = [ 'Foo', 'Bar' ] b = [ 'Boo', 'Far' ] q = [ a, b ] print q[0][0] print q[1][1] a[0] = 'Snoo' b[1] = 'Gnuu' print q[0][0] print q[1][1] ---------- This will output: Foo Far Snoo Gnuu I assume it does so because q stores _references_ to a and b. How would do I do if I want to copy the list? I.e. I want the output from the code above to be: Foo Far Foo Far ..even if a[0] = 'Snoo' and b[1] = 'Gnuu' remain where they are. Or, better yet, how do I store a and b in q, and then tell Python that I want a and b to point to new lists, without touching the contents in q? C equivalent of what I want to do: ----------- a = calloc(n, size); prepare(a) q[0] = a; a = calloc(n, size); // new list; 'q' is unaffected if I change 'a' ----------- From fredrik at pythonware.com Tue Jun 21 05:38:26 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Jun 2005 11:38:26 +0200 Subject: regarding cache clearing header in python cgi References: <20050621062643.74244.qmail@web8402.mail.in.yahoo.com> Message-ID: "praba kar" wrote: > In Php the following headers base we can clean > the cache in the url "header('Cache-Control: > no-store, no-cache, must-revalidate'); " > I want to know Php equivalent headers in Python-cgi > If anybody know regarding this kindly mail me. did you try print 'Cache-Control: no-store, no-cache, must-revalidate' ? From bretthoerner at gmail.com Tue Jun 28 00:01:56 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 27 Jun 2005 21:01:56 -0700 Subject: Better console for Windows? In-Reply-To: References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: <1119931315.996979.176610@f14g2000cwb.googlegroups.com> Philippe C. Martin wrote: > You might want to check out ipyhton. I use it. :) I love it. When I meant console I meant the shell app that runs any text-based programs. The windows console was giving me loud beeps, etc, which I've now fixed. Thanks for your reply though, Brett From fredrik at pythonware.com Thu Jun 23 03:47:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Jun 2005 09:47:57 +0200 Subject: Does a function like isset() exist in Python? References: <1119506168.356745.207790@g47g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > There are no unitialized variables in python; if you try to access an > undefined name, a NameError exception is raised: > > try: > print "foo is", foo > except NameError: > print "foo is undefined" note the order of evaluation: >>> try: ... print "foo is", foo ... except NameError: ... print "foo is undefined" ... foo is foo is undefined >>> From kirk at jobsluder.net Sat Jun 11 00:33:07 2005 From: kirk at jobsluder.net (Kirk Job Sluder) Date: Sat, 11 Jun 2005 04:33:07 GMT Subject: Is pyton for me? References: <867jh16d3s.fsf@guru.mired.org> Message-ID: <87is0lpl5h.fsf@debian.kirkjobsluder.is-a-geek.net> Mike Meyer writes: > "Mark de+la+Fuente" writes: > > > I need to write simple scripts for executing command line functions. > > Up till now I've used C-Shell scripts for this, but I'm looking for > > a better alternative. And I keep reading about how ?easy? it is to > > program with python. > > As others pointed out, Python isn't a shell, or even a shell scripting > language, so it doesn't handle what you're doing in a "natural" > way. Because of that, it may not be the language for you. Python has > features that work well for building large systems, but those tend to > cause extra work when you want to do things that other languages make > simple. I agree with this approach. For me, there has to be a certain level of complexity before I reach for python as a tool. This usually involves one or more of the following: 1: text processing involving multiple files. For example, running statistics on file A, looking up values stored in file B. 2: cases where the overhead of repeatedly opening processes and pipes becomes unacceptable. For example: for f in file/*; do cp $f $f.bak sed -e 'something' < $f.bak > $f done This works well with small numbers of files. But even though sed is quicker than python, starting a new sed process with every iteration quickly stacks up. Rewriting the entire thing to run as a single process can dramatically improve performance. Although this might be a case of premature optimization. 3: cases where figuring out how to do something using one of the POSIX shell utilities makes my head hurt. Personally, I hate popen and avoid using it when possible. There is nothing wrong with sh as a glue language when all you need is something like: grep text file | filter | filter > output_file. > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- Kirk Job-Sluder "The square-jawed homunculi of Tommy Hilfinger ads make every day an existential holocaust." --Scary Go Round From cdkrug at worldnet.att.net Mon Jun 20 11:04:19 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Mon, 20 Jun 2005 15:04:19 GMT Subject: Couple functions I need, assuming they exist? Message-ID: List: First, I'm reading that aString.split() is depreciated. What's the current best practice for this? Or am I mistaking that: myWords = split(aString, aChar) is depreciated but myWords = aString.split(aChgar) is not? Second question, I've written a script that generates a LaTeX source containing randomly generated arithmetic problems of various types. The target of the problems (my daughter) would prefer that the thousands be delimited. Is there a string function that does this? Thanks Charles From tdelaney at avaya.com Thu Jun 30 18:10:42 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 1 Jul 2005 08:10:42 +1000 Subject: When someone from Britain speaks, Americans hear a "Britishaccent"... Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CB0B@au3010avexu1.global.avaya.com> Tom Anderson wrote: > How about carrier? Ends in an "a" (Australian ;) Tim Delaney From siyer at Princeton.EDU Fri Jun 10 17:15:20 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Fri, 10 Jun 2005 17:15:20 -0400 Subject: bind in Tkinter Message-ID: <272ef0392a43f.42a9caa8@Princeton.EDU> Thanks! Your message guided me to the solution to my problem. Shankar ----- Original Message ----- From: Markus Weihs Date: Friday, June 10, 2005 5:01 pm Subject: Re: bind in Tkinter > Hi! > > If you press a key, a key-event is passed to the function, here to > self.quit. This is the misterious second argument, which can be > useful if you e.g. want to check which key was pressed. Here is > a snippet to show how you can do it: > > > from Tkinter import * > > def quit_program(event): > print event.keysym # which key was pressed? > root.quit() > > root = Tk() > e = Entry() > e.bind("", quit_program) > e.pack() > root.mainloop() > > > Regards, mawe > -- > http://mail.python.org/mailman/listinfo/python-list > From gandalf at geochemsource.com Mon Jun 6 13:42:49 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 06 Jun 2005 19:42:49 +0200 Subject: About size of Unicode string In-Reply-To: <20050606171706.8E22C3181AA@newton.cujae.edu.cu> References: <20050606171706.8E22C3181AA@newton.cujae.edu.cu> Message-ID: <42A48B19.5030201@geochemsource.com> Frank Abel Cancio Bello wrote: >Hi all! > >I need know the size of string object independently of its encoding. For >example: > > len('123') == len('123'.encode('utf_8')) > >while the size of '123' object is different of the size of >'123'.encode('utf_8') > >More: >I need send in HTTP request a string. Then I need know the length of the >string to set the header "content-length" independently of its encoding. > >Any idea? > > This is from the RFC: > > The Content-Length entity-header field indicates the size of the > entity-body, in decimal number of OCTETs, sent to the recipient or, in > the case of the HEAD method, the size of the entity-body that would > have been sent had the request been a GET. > > Content-Length = "Content-Length" ":" 1*DIGIT > > > An example is > > Content-Length: 3495 > > > Applications SHOULD use this field to indicate the transfer-length of > the message-body, unless this is prohibited by the rules in section > 4.4 . > > Any Content-Length greater than or equal to zero is a valid value. > Section 4.4 describes how to determine the length of a message-body if > a Content-Length is not given. > Looks to me that the Content-Length header has nothing to do with the encoding. It is a very low levet stuff. The content length is given in OCTETs and it represents the size of the body. Clearly, it has nothing to do with MIME/encoding etc. It is about the number of bits transferred in the body. Try to write your unicode strings into a StringIO and take its length.... Laci From steve at REMOVETHIScyber.com.au Sat Jun 18 22:12:53 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 19 Jun 2005 12:12:53 +1000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> Message-ID: On Sat, 18 Jun 2005 15:43:24 -0400, Chinook wrote: > Steven, > > Your weigh-in on semantics is misleading, How is it misleading? > but your elaboration of the aspect is very well put. > > As to semantics, piracy is to the originator what freedom fighter is to those > that perceive themselves as oppressed. Very little modern piracy is politically motivated, unlike the glory days when terrorist nations like Great Britain and Spain supported "privateers" to attach each other's ships and raid other nations. These days modern pirates are generally petty criminals in small boats with crews of less than a dozen people. http://www.oceannavigator.com/article.php?a=5418 http://www.noonsite.com/Members/webmaster/R2002-06-10-2 http://www.icc-ccs.org/prc/piracyreport.php > On the other hand, your elaboration is a very good example of the altered > consciousness of human nature. That is, the acceptance of shades of > complicity divorced from shades of guilt. Of course, one can see (if they so > chose) many more obvious examples in business, let alone government and > religion :~) I don't understand your point. But for the record, I never excused copyright infringement. I simply pointed out that for organisations who are not monopolies in their business niche, they gain more benefit from turning a blind eye to most copyright infringement than they lose. Or, to put it another way, those developers who face competition in their market niche and put up barriers to casual copying (eg anti-copying technology, dongles, serial numbers, licence enforcement, etc) almost always lose out against competitors who turn a blind eye to that copying. Copyright infringement may be illegal. It may even be immoral. But for developers who face competition, ignoring it may be the best strategy. That's not an issue of human consciousness, altered or not. It is an economic issue. -- Steven. From mrmaple at gmail.com Tue Jun 14 09:45:31 2005 From: mrmaple at gmail.com (James Carroll) Date: Tue, 14 Jun 2005 09:45:31 -0400 Subject: Tiff Image Reader/writer In-Reply-To: <1118751946.686069.295910@g44g2000cwa.googlegroups.com> References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118751946.686069.295910@g44g2000cwa.googlegroups.com> Message-ID: Hmm... that's unfortunate. What platform are you on? If Windows, then I believe that PIL is statically linked against LibTIFF and that particular libtiff wasn't compiled with certain options (CCITT formats or something.) (in 1999 that was true, I found a post from Fred here: http://mail.python.org/pipermail/image-sig/1999-June/000755.html) If it's a one-time thing, there are ways of converting the TIFF to a different encoding. I use the libtiff tifftools command tiffcp: tiffcp -c none infile.tif out file.tif which will decode into a non-compressed tiff. Otherwise, you might be out of luck (or have to change some of the libtiff options.) If you put your tiff file somewhere where I can download it, I'll try reading it with the alternatives that I have on my system and let you know what works... -Jim On 14 Jun 2005 05:25:46 -0700, PyPK wrote: > I get a decoder error when i do a get pixel on the Image > > >>> im.getpixel((12,34)) > > Traceback (most recent call last): > File "", line 1, in ? > File "Image.py", line 858, in getpixel > self.load() > File "/usr/local/lib/python2.4/site-packages/PIL/ImageFile.py", line > 180, in load > d = Image._getdecoder(self.mode, d, a, self.decoderconfig) > File "Image.py", line 328, in _getdecoder > raise IOError("decoder %s not available" % decoder_name) > IOError: decoder group4 not available > > -- > http://mail.python.org/mailman/listinfo/python-list > > From __peter__ at web.de Thu Jun 23 07:46:24 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Jun 2005 13:46:24 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: Konstantin Veretennicov wrote: > On 6/22/05, Riccardo Galli wrote: > >> I propose to add an 'abs' keyword which would make os.listdir return the >> absolute path of files instead of a relative path. > > What about os.listdir(dir='relative/path', abs=True)? Should listdir > call abspath on results? Should we add another keyword rel? Would it > complicate listdir unnecessarily? > > - kv I'm in favour of Riccardo's suggestion, but I think he's got the name of the keyword wrong. The signature should be listdir(path, with_path=False) and cater absolute and relative paths alike. The need for such an enhancement is not particularly pressing, as workarounds abound. Here's another one: >>> glob.glob("/usr/lib/games/../games/*") ['/usr/lib/games/../games/schwarzerpeter'] Peter From Scott.Daniels at Acm.Org Wed Jun 29 13:36:29 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 29 Jun 2005 10:36:29 -0700 Subject: importing packages from a zip file In-Reply-To: References: Message-ID: <42c2d483$1@nntp0.pdx.net> Peter Tillotson wrote: > ... With the file system > > base/ > __init__.py > branch1/ > __init__.py > myModule.py > > At the same time its possible to store modules in a flat zip-file and > import modules with the following. > > from myZip.zip import myModule.py Does this work for you? It gives me a syntax error. Typically, put the zip file on the sys.path list, and import modules and packages inside it. If you zip up the above structure, you can use: sys.path.insert(0, 'myZip.zip') import base.branch1.myModule --Scott David Daniels Scott.Daniels at Acm.Org From bdesth.quelquechose at free.quelquepart.fr Thu Jun 30 17:09:03 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 30 Jun 2005 23:09:03 +0200 Subject: Seeking IDE In-Reply-To: References: Message-ID: <42c4592d$0$7668$636a15ce@news.free.fr> Nick Mountford a ?crit : > Hi, > > Complete newb to Python and programming, looking for an open source > IDE to download. Any suggestions? Use something simple. Start with Idle (it comes with Python, and has all the basic features you may need to learn Python). When you'll have learn the bases, it will be time to move to something else. From twic at urchin.earth.li Mon Jun 13 14:56:19 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 13 Jun 2005 19:56:19 +0100 Subject: implicit variable declaration and access In-Reply-To: References: Message-ID: On Mon, 13 Jun 2005, Ali Razavi wrote: > Is there any reflective facility in python that I can use to define a > variable with a name stored in another variable ? > > like I have : > x = "myVarName" > > what can I do to declare a new variable with the name of the string > stored in x. And how can I access that implicitly later ? Are you absolutely sure you want to do this? tom -- The MAtrix had evarything in it: guns, a juimping off teh walls, flying guns, a bullet tiem, evil computar machenes, numbers that flew, flying gun bullets in slowar motian, juimping into a gun, dead police men, computar hackeing, Kevin Mitnick, oven trailers, a old womans kitchen, stairs, mature women in clotheing, head spark plugs, mechaanical squids, Japaneseses assasins, tiem traval, volcanos, a monstar, slow time at fastar speed, magic, wizzards, some dirty place, Kung Few, fighting, a lot of mess explodsians EVARYWHERE, and just about anything else yuo can names! From l.serwatka at gazeta-dot-pl.no-spam.invalid Wed Jun 8 03:36:00 2005 From: l.serwatka at gazeta-dot-pl.no-spam.invalid (ls) Date: Wed, 8 Jun 2005 07:36:00 +0000 (UTC) Subject: how to export data from ZODB to text files References: Message-ID: > Why are you doing this in the first place? Trying to escape from > Zope-land? Exporting data on a regular basis, for use in another app? Hi Jonh, Thank you for your reply. Yes, I'm traing to escape from Zope-land, to be more clarify I want to migrate from Plone to PHP Application, which uses MySQL database engine, so I have to move all data from ZODB to MySQL. I suppose that python script shouldn`t be so complex. I need just iterate ZODB and write attributes like "Intro", "Body" of article to file for example. I need export Plone content hierarchy like Home | | - - - Folder 1 (Title, Intro, Body) | | - - - Article (Title, Intro, Body) | | - - - Folder 2 (Title, Intro, Body) Now after your answer, I see that I will be not able to finish this taks by myself ... I'm experienced mostly in C, PHP, also with some backgrounds of CPP and Java, but I'm totaly new in Python ... What do you suggest in this case? -- Lukasz From poisondart985 at gmail.com Mon Jun 6 22:11:51 2005 From: poisondart985 at gmail.com (poisondart) Date: 6 Jun 2005 19:11:51 -0700 Subject: PSP / mod_python ... how to get POST vars on .psp ? In-Reply-To: References: Message-ID: <1118110311.349370.218880@g49g2000cwa.googlegroups.com> Would something like cgi.FieldStorage() be what you're looking for? form = cgi.FieldStorage() form[ ] = http://www.python.org/doc/2.3.5/lib/node406.html From thorsten at thorstenkampe.de Tue Jun 28 09:53:23 2005 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 28 Jun 2005 14:53:23 +0100 Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: <2v8iu8aka0r8.1i9t23v23oglg.dlg@40tude.net> * Brett Hoerner (2005-06-28 03:44 +0100) > Is there a different shell I can use (other than cmd.com) to run Python > in [...] Holy snake, are you running command.com?! Throw away your Windows 3.11 computer and start using cmd.exe. > Another problem with cmd.com is when I run IPython, if I have an error, > or tab or anything, I get the speaker beep (ala linux) but I can't find > a way to turn it off. Use rxvt (Cygwin). Thorsten From jheasly at guardnet.com Tue Jun 14 17:30:23 2005 From: jheasly at guardnet.com (John Heasly) Date: Tue, 14 Jun 2005 14:30:23 -0700 Subject: Cause for using objects? Message-ID: <1e71b37dbd3c61060246fa2630a0d2ae@guardnet.com> Given: [{"mugshot": "nw_gradspeaker4_0608", "width": 67.0, "height": 96.0}, \ {"mugshot": "nw_gradspeaker2_0608", "width": 67.0, "height": 96.0}, \ {"freehand": "b1.developreport.0614", "width": 154.0, "height": 210.0}, \ {"graphic": "bz_cafeparadiso_0613", "width": 493.0, "height": 341.0}] Return: {"mugshot1": "nw_gradspeaker4_0608", "mugshot1.width": 67.0, "mugshot1.height": 96.0,\ "mugshot2": "nw_gradspeaker2_0608", "mugshot2.width": 67.0, "mugshot2.height": 96.0, \ "freehand1": "b1.developreport.0614", "freehand1.width": 154.0, "freehand1.width": 210.0, \ "graphic1": "bz_cafeparadiso_0613", "graphic1.width": 493.0, "graphic1.height": 341.0} I'm trying to teach myself some OOP. Does grinding the Given above into the Return seem like a good candidate? John H. Eugene, Ore. jheasly at guardnet dot com From gregpinero at gmail.com Tue Jun 14 14:20:29 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 14 Jun 2005 14:20:29 -0400 Subject: MySQLDBAPI In-Reply-To: <312cfe2b05061408481a3e7de0@mail.gmail.com> References: <2tqln2-6c3.ln1@news.interplanet.it> <312cfe2b05061408481a3e7de0@mail.gmail.com> Message-ID: <312cfe2b05061411202aeb81c3@mail.gmail.com> While waiting for answers to the above questions, I went ahead and tried the following: 1. Downloaded the RPM for the server's version of MySql: http://downloads.mysql.com/archives/mysql-3.23/MySQL-devel-3.23.57-1.i386.rpm 2. Copy file to server, and extract to a new folder i made called rpmmysql: [gpinero at intel1 gpinero]$ cd rpmmysql/ [gpinero at intel1 rpmmysql]$ rpm2cpio /home/gpinero/MySQL-devel-3.23.56-1.i386.rpm | cpio -d -i 3936 blocks [gpinero at intel1 rpmmysql]$ ls usr [gpinero at intel1 rpmmysql]$ cd usr [gpinero at intel1 usr]$ ls bin include lib [gpinero at intel1 usr]$ cd include/ [gpinero at intel1 include]$ ls mysql [gpinero at intel1 include]$ cd mysql [gpinero at intel1 mysql]$ ls chardefs.h m_ctype.h my_net.h mysql.h sslopt-case.h dbug.h m_string.h my_no_pthread.h mysql_version.h sslopt-longopts.h errmsg.h my_config.h my_pthread.h my_sys.h sslopt-usage.h history.h my_global.h mysql_com.h raid.h sslopt-vars.h keymaps.h my_list.h mysqld_error.h readline.h tilde.h [gpinero at intel1 mysql]$ 3. Edited setup.py to include the new directory. Here's my whole file just in case you need it: #!/usr/bin/env python """\ ========================= Python interface to MySQL ========================= MySQLdb is an interface to the popular MySQL_ database server for Python. The design goals are: - Compliance with Python database API version 2.0 [PEP-0249]_ - Thread-safety - Thread-friendliness (threads will not block each other) MySQL-3.22 through 4.1 and Python-2.3 through 2.4 are currently supported. MySQLdb is `Free Software`_. .. _MySQL: http://www.mysql.com/ .. _`Free Software`: http://www.gnu.org/ .. [PEP-0249] http://www.python.org/peps/pep-0249.html """ import os import sys from distutils.core import setup from distutils.extension import Extension mysqlclient = os.getenv('mysqlclient', 'mysqlclient_r') mysqlstatic = eval(os.getenv('mysqlstatic', 'False')) embedded_server = (mysqlclient == 'mysqld') name = "MySQL-%s" % os.path.basename(sys.executable) if embedded_server: name = name + "-embedded" version = "1.2.1c3" extra_objects = [] if sys.platform == "win32": mysqlroot = os.getenv('mysqlroot', None) if mysqlroot is None: print "You need to set the environment variable mysqlroot!" print "This should be the path to your MySQL installation." print "Probably C:\Program Files\MySQL 4.1\ or something like that." sys.exit(1) include_dirs = [os.path.join(mysqlroot, "include")] library_dirs = [os.path.join(mysqlroot, "libs")] libraries = ['zlib', 'msvcrt', 'libcmt', 'wsock32', 'advapi32'] if mysqlstatic: extra_objects.append(os.path.join( library_dirs[0], mysqlclient+'.lib')) else: libraries.append(mysqlclient) else: def config(what): from os import popen f = popen("mysql_config --%s" % what) data = f.read().strip().split() if f.close(): data = [] return data # This dequote() business is required for some older versions # of mysql_config def dequote(s): if (s[0] == "'" or s[0] == '"') and (s[0] == s[-1]): s = s[1:-1] return s include_dirs = [ dequote(i[2:]) for i in config('include') if i.startswith('-i') ] #include_dirs.append('/usr/local/mysql/include/mysql') #include_dirs=['/usr/local/mysql/include/mysql'] if mysqlclient == "mysqlclient": libs = config("libs") elif mysqlclient == "mysqlclient_r": libs = config("libs_r") elif mysqlclient == "mysqld": libs = config("embedded") library_dirs = [ dequote(i[2:]) for i in libs if i.startswith("-L") ] libraries = [ dequote(i[2:]) for i in libs if i.startswith("-l") ] # Workaround for a pre-4.1.9 bug if "z" not in libraries: libraries.append("z") extra_compile_args = config("cflags") if mysqlstatic: extra_objects.append(os.path.join( library_dirs[0],'lib%s.a' % mysqlclient)) else: libraries.append(mysqlclient) classifiers = """ Development Status :: 5 - Production/Stable Environment :: Other Environment License :: OSI Approved :: GNU General Public License (GPL) Operating System :: MacOS :: MacOS X Operating System :: Microsoft :: Windows :: Windows NT/2000 Operating System :: OS Independent Operating System :: POSIX Operating System :: POSIX :: Linux Operating System :: Unix Programming Language :: C Programming Language :: Python Topic :: Database Topic :: Database :: Database Engines/Servers """ metadata = { 'name': name, 'version': version, 'description': "Python interface to MySQL", 'long_description': __doc__, 'author': "Andy Dustman", 'author_email': "andy at dustman.net", 'license': "GPL", 'platforms': "ALL", 'url': "http://sourceforge.net/projects/mysql-python", 'download_url': "http://prdownloads.sourceforge.net/mysql-python/" \ "MySQL-python-%s.tar.gz" % version, 'classifiers': [ c for c in classifiers.split('\n') if c ], 'py_modules': [ "_mysql_exceptions", "MySQLdb.converters", "MySQLdb.connections", "MySQLdb.cursors", "MySQLdb.sets", "MySQLdb.times", "MySQLdb.stringtimes", "MySQLdb.mxdatetimes", "MySQLdb.pytimes", "MySQLdb.constants.CR", "MySQLdb.constants.FIELD_TYPE", "MySQLdb.constants.ER", "MySQLdb.constants.FLAG", "MySQLdb.constants.REFRESH", "MySQLdb.constants.CLIENT", ], 'ext_modules': [ Extension( name='_mysql', sources=['_mysql.c'], include_dirs=include_dirs, library_dirs=library_dirs, libraries=libraries, extra_compile_args=extra_compile_args, extra_objects=extra_objects, ), ], } #include_dirs.append('/usr/local/mysql/include/mysql') include_dirs.append('/home/gpinero/rpmmysql/usr/include/mysql') setup(**metadata) 4. Tried building again: [gpinero at intel1 MySQL-python-1.2.1c3]$ python2.4 setup.py build running build running build_py running build_ext building '_mysql' extension gcc -pthread -shared build/temp.linux-i686-2.4/_mysql.o -lz -lmysqlclient_r -o build/lib.linux-i686-2.4/_mysql.so /usr/bin/ld: cannot find -lmysqlclient_r collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 From philippe at philippecmartin.com Sat Jun 25 15:18:04 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 19:18:04 GMT Subject: Big problem fetching members from dynamically loaded module References: Message-ID: Hi, I found the solution to my problem: Besides the fact I still have no clue as to how the Python name spacing works, the code I though did stuff (the __EXEC_LIST loop) did not do as I expected as I had already imported all of the modules in an explicit manner. So now I can rephrase my problem: 1) I have a program (XYZ) which displays class members in menus 2) At the time I write my program, I do not know what class members should be in thos menus 3) So I have the class names in external files so that I can send new modules to the 'customer' without having to release a new version of 'XYZ' What puzzles me furher is that the 'exec' of commands such as 'sc_bc = BC()' do work as I use them further in 'XYZ' whereas the exec of 'from xxxxxxx import *' does not _seem_ to do anything. Grrr! I feel more stupid every day ! Any insight ? Thanks, Philippe Philippe C. Martin wrote: > Hi, > > I'm getting pretty desperate here: > > The code below crashes on the last line (but works from a shell). > > The class 'BC' exists and the loop on self.__BC_EXEC_LIST passes fine. > > It's got to be something really stupid but I've been looking at it too > long I guess. > > Any clue would be quite welcome. > > Regards, > > Philippe > > > > > > > __EXEC_LIST = [ \ > 'import os', \ > 'import sys', \ > 'from SC.pilot.SC_Script_Processor import *', \ > 'from SC.utils.SC_Convert import *', \ > 'import string ', \ > 'from SC.iso.SC_Dec_ISO import *', \ > 'from SC.iso.SC_Enc_ISO import *', \ > 'from SC.iso.SC_Analysis import *', \ > 'sc_sp = SC_Script_Processor ()', \ > 'sc_enc = SC_Enc_ISO ()', \ > 'sc_dec = SC_Dec_ISO ()', \ > 'sc_a = SC_Analysis ()', \ > 'sc_conv = SC_Convert()' ] > > __BC_EXEC_LIST = ['from SC.CARDS.BC import *','from > SC.Solutions.SCF.BCInterface import *','sc_bc = BC_Interface()'] > > > for l_s in self.__BC_EXEC_LIST: #this loop works fine > try: > exec (l_s, self.m_process_global,self.m_process_local) > > except: > traceback.print_exc() > > for l_s in self.__EXEC_LIST: #this loop works fine > try: > exec (l_s, self.m_process_global,self.m_process_local) > > except: > print >> sys.stderr, 'FATAL INIT ERROR - PLEASE CHECK YOUR > CONFIGURATION' > > l = inspect.getmembers(eval('SC_Dec_ISO')) #THIS WORKS - the class > exists > l = inspect.getmembers(eval('BC')) #THIS CRASHES - the class > exists From simonwittber at gmail.com Sun Jun 19 09:01:23 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 19 Jun 2005 06:01:23 -0700 Subject: pickle alternative In-Reply-To: <1119166730.350374.178510@o13g2000cwo.googlegroups.com> References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> <1119161205.327572.136150@g44g2000cwa.googlegroups.com> <7xd5qi3ldp.fsf@ruckus.brouhaha.com> <1119166730.350374.178510@o13g2000cwo.googlegroups.com> Message-ID: <1119186083.791376.172730@o13g2000cwo.googlegroups.com> If anyone is interested, I've implemented a faster and more space efficient gherkin with a few bug fixes. http://developer.berlios.de/project/showfiles.php?group_id=2847 From darkpaladin79 at hotmail.com Thu Jun 9 17:02:34 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 17:02:34 -0400 Subject: smtpd module Message-ID: So youre wondering how to send mail in python? I have a lot of examples if you want the smtp module. I don't have anything for anything other than the smtp module. -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From leo at greatbasin.com Thu Jun 2 23:40:57 2005 From: leo at greatbasin.com (Leonard Blaisdell) Date: Thu, 02 Jun 2005 20:40:57 -0700 Subject: Like a star, I burn bright, dissipating into the night. References: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> <429e7155.6739473@news.alphalink.com.au> Message-ID: In article , Jeff_Relf wrote: > #include Unless clc has changed dramatically and rapidly, you won't be welcomed with this. What were you thinking? Embrace the flames if they deign to reply at all. Posted from csma leo -- References: Message-ID: flupke wrote: Thanks for the good ideas people. Regards, Benedict From pmaupin at gmail.com Sat Jun 25 01:20:55 2005 From: pmaupin at gmail.com (Patrick Maupin) Date: 24 Jun 2005 22:20:55 -0700 Subject: formatted xml output from ElementTree inconsistency References: <1119646423.324518.220710@o13g2000cwo.googlegroups.com> <4cmpb1hnu62j7gkk8qanl6a7a9d40gi3v1@4ax.com> Message-ID: <1119676855.035495.182190@f14g2000cwb.googlegroups.com> Dennis Bieber wrote: > Off hand, I'd consider the non-binary nature to be because the > internet protocols are mostly designed for text, not binary. A document at http://www.w3.org/TR/REC-xml/ lists "the design goals for XML". One of the listed goals is "XML documents should be human-legible and reasonably clear". To your point, the very _first_ listed goal (if order means anything in this list) is "XML shall be straightforwardly usable over the Internet", so it's reasonable to assume "the non-binary nature to be because the internet protocols are mostly designed for text, not binary." But this assumption turns cause and effect on its head. It is perfectly feasible to pass binary data through every known internet protocol (with a little simplistic encoding), and is done all the time. The real next question is: why ARE the internet protocols "mostly designed for text, not binary"? SMTP, for example, was designed at a time when memory, bandwidth, and CPU cycles were all at a premium, and MTAs were coded using fairly low-level constructs in C where parsing was a pain in the rear. Even so, the developers decided to use relatively free-formatted ASCII in the protocol. To follow your theory to its logical conclusion, they must have wasted all that bandwith, all those CPU cycles, all that memory, all that disk space, and all that effort writing parsing code because of yet another underlying mechanism which was "designed for text." On that account, your theory is correct, but only when you realize the underlying mechanism which is "designed for text" is the human brain, which has to try to make sense of all this mess when things aren't quite interoperating properly. Regards, Pat From __peter__ at web.de Thu Jun 2 03:47:57 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Jun 2005 09:47:57 +0200 Subject: How to restrict lenght of entry widget to certain number of character References: <1117396149.334908.238580@g14g2000cwa.googlegroups.com> Message-ID: Michael Onfrek wrote: > I'm playing with entry again and trying to restrict length of entry > widget to certain number of character, so users cannot enter more > character into it. Any ideas? import Tkinter as tk root = tk.Tk() var = tk.StringVar() max_len = 5 def on_write(*args): s = var.get() if len(s) > max_len: var.set(s[:max_len]) var.trace_variable("w", on_write) entry = tk.Entry(root, textvariable=var) entry.pack() root.mainloop() Not very elegant, but better than nothing. Peter From roy at panix.com Thu Jun 23 13:57:18 2005 From: roy at panix.com (Roy Smith) Date: 23 Jun 2005 13:57:18 -0400 Subject: Loop until condition is true References: <86u0jpytg7.fsf@guru.mired.org> Message-ID: Michael Hoffman wrote: > I count at least 4 different modules in the Python 2.4 standard > library that assign to True or False, mainly as a compatibility > measure for the days before they were built-ins. Hopefully, none of them as creative as http://thedailywtf.com/forums/36067/ShowPost.aspx From kveretennicov at gmail.com Tue Jun 21 05:29:08 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 12:29:08 +0300 Subject: .dll files In-Reply-To: <1119337010.540555.226800@g43g2000cwa.googlegroups.com> References: <1119265966.661838.186320@g44g2000cwa.googlegroups.com> <42B6CA2B.3030909@syscononline.com> <1119337010.540555.226800@g43g2000cwa.googlegroups.com> Message-ID: <4660fe30050621022920aa1c67@mail.gmail.com> On 20 Jun 2005 23:56:50 -0700, Sabin.A.K wrote: > > Will the COM Object be a total solution for my problems? I just try to > make a dll to encapsulate some 'icon and text' files for my > application. Are you trying to create a windows resource dll? I believe Python isn't the tool for this job. What is your main application created with? How do you plan to extract 'icons and text' from this dll? - kv From greg at cosc.canterbury.ac.nz Wed Jun 8 23:11:34 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 15:11:34 +1200 Subject: __init__.py in packages In-Reply-To: References: Message-ID: <42A7B366.2090909@cosc.canterbury.ac.nz> Gary Wilson Jr wrote: > I would really like to see an example or situation that makes good > use of the __init__.py file. I've attached a non-trivial example, from my PyGUI package. It uses some trickery to switch in one of a number of subdirectories of platform specific code, and then imports a bunch of names from submodules into the top-level package, so the user can pretend he's just using a single top-level module, e.g. from GUI import Window even though Window is actually defined in some submodule. This is a rather extreme example, though -- most __init__.py files are much simpler! -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: __init__.py URL: From cam.ac.uk at mh391.invalid Sat Jun 25 10:23:36 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 25 Jun 2005 15:23:36 +0100 Subject: super problem In-Reply-To: References: Message-ID: Uwe Mayer wrote: > I have a diamond-shaped multiple inheritanc chain with new style classes, > but super() does not call the parent class correctly: > > -- snip -- > from qtcanvas import * I don't have qtcanvas installed, and I couldn't reproduce the undesirable behavior using a dummy class. If you try to create a self-contained testcase, you will have an easier time figuring where the problem is. -- Michael Hoffman From ptmcg at austin.rr.com Thu Jun 16 09:40:59 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Jun 2005 06:40:59 -0700 Subject: Regex for repeated character? References: <5J9se.136$Q75.39412@newshog.newsread.com> Message-ID: <1118929259.330317.52610@g14g2000cwa.googlegroups.com> A brute-force pyparsing approach - define an alternation of all possible Words made up of the same letter. Plus an alternate version that just picks out the repeats, and gives their location in the input string: from pyparsing import ZeroOrMore, MatchFirst, Word, alphas print "group string by character repeats" repeats = ZeroOrMore( MatchFirst( [ Word(a) for a in alphas ] ) ) test = "foo ooobaaazZZ" print repeats.parseString(test) print print "find just the repeated characters" repeats = MatchFirst( [ Word(a,min=2) for a in alphas ] ) test = "foo ooobaaazZZ" for toks,loc,endloc in repeats.scanString(test): print toks,loc Gives: group string by character repeats ['f', 'oo', 'ooo', 'b', 'aaa', 'z', 'ZZ'] find just the repeated characters ['oo'] 1 ['ooo'] 4 ['aaa'] 8 ['ZZ'] 12 (pyparsing implicitly ignores whitespace, that's why there is no ' ' entry in the first list) Download pyparsing at http://pyparsing.sourceforge.net. -- Paul From skip at pobox.com Tue Jun 7 10:37:47 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 7 Jun 2005 09:37:47 -0500 Subject: reloading my own modules In-Reply-To: References: Message-ID: <17061.45371.482623.695405@montanaro.dyndns.org> Lowell> import dbtest, util Lowell> for module in ['dbtest', 'util']: Lowell> if module in sys.modules.keys(): Lowell> reload(sys.modules[module]) Lowell> Is this the best way to do it? It seems a bit verbose, but not Lowell> really all that bad. I was just wondering if there is a more Lowell> standard way to do it? Not that I'm aware of. You don't need to request the keys() of a dict in recent versions of Python: import dbtest, util for module in ['dbtest', 'util']: if module in sys.modules: reload(sys.modules[module]) Also, since it's clear you have already imported dbtest and util, there's no need to check in sys.modules: import dbtest, util reload(dbtest) reload(util) Skip From renato.ramonda at gmail.com Thu Jun 9 00:47:24 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Thu, 09 Jun 2005 06:47:24 +0200 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: Tim Roberts ha scritto: > Renato Ramonda wrote: > >>wxWidgets apps look ALMOST native on windows (combobox and similar >>widgets are emulated, and look really bad), > > > That just isn't true. They use the standard combo box. Then it has changed recently. Mind that most stable apps still use wx2.4 > wx uses "sizers" to do the same thing. Same purpose, different philosophy. > I find sizers more natural, but people should certainly stick to whatever > makes them comfortable. I like sizers too, but in my experience wx apps do not use them. Are they by chance something that came with the 2.5/2.6 development cycle? That version is still pretty rare in real world applications. >>And that's not even starting to consider the version mess: try to >>install xCHM, Boa Constructor, aMule, VLC and some other app together... >>instant madness. > > > They why would you do it? gvim and wxPython do the job for me. No mess. Because i USE a chm reader. And I USE aMule, and I USE a multimedia player. I'm not talking about developing (don't get confused by my mention of Boa), I'm talking about using. Only very recently wx introduced a mechanism to keep different versions in parallel. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From reinhold-birkenfeld-nospam at wolke7.net Fri Jun 10 15:56:30 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 10 Jun 2005 21:56:30 +0200 Subject: without shell In-Reply-To: References: <11aj9d3fga9or8b@corp.supernews.com> <11ajkap3isrmndf@corp.supernews.com> Message-ID: <3gu9jeFdlbb8U1@individual.net> Donn Cave wrote: >> Not according the the docs: >> >> Also, for each of these variants, on Unix, cmd may be a >> sequence, in which case arguments will be passed directly to >> the program without shell intervention (as with os.spawnv()). >> If cmd is a string it will be passed to the shell (as with >> os.system()). >> >> It's not exactly clear what "these variants" refer to, but I >> read it as referring to all of the the os.popen functions. >> >> Perhaps it only refers to os.popen[234]? > > Right. The paragraphs seem a little scrambled. Note > the use of "cmd" instead of "command" as the parameter > is named for popen(). Also note "These methods do not > make it possible to retrieve the return code from the > child processes", after the popen() paragraph above tells > you how to do it (using the better term "exit status".) > > Or one may look at the source. FYI, I checked in a little fix to the docs which makes clear what functions the paragraphs pertain to. Also, I changed "return code" to "exit status". Reinhold From gdamjan at gmail.com Wed Jun 22 14:08:03 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 22 Jun 2005 20:08:03 +0200 Subject: importing a package References: <42b968a8_1@x-privat.org> <7ofue.127090$E62.7014438@phobos.telenet-ops.be> Message-ID: <42b9a8e3_2@x-privat.org> > Indeed, when i do this, then it works > import sys > sys.path.append('package') > > However, why is it that package isn't added automatically to the pad? When you execute a python program the directory where the program is is automatically added to sys.path. No other directory is added to the default builtin sys.path. In you case (the second case), you can import package.dir2.file2. -- damjan From guy.lateur at b-b.be Fri Jun 10 05:20:38 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Fri, 10 Jun 2005 09:20:38 GMT Subject: Start application & continue after app exits References: <9G3qe.15862$TR5.692@news.edisontel.com> Message-ID: This may be getting somewhat OT, but I'd like to dig a little deeper into this. First of all, security (as in some other proces reading/disclosing the data) is not an issue in this case. The thing is, though, a user could run the script twice, not having closed Word after the first time. So I guess I need unique filenames. Am I right in assuming "tmpFile = tempfile.NamedTemporaryFile()" does that automatically? More generally speaking, I'm not sure it's a question of windows vs linux. I often have files open in UltraEdit, which I can then change in some other proces. When I reactivate UEdit, it updates (or closes) the file. So maybe it loads the file in memory and then closes it, and then opens it again for writing. Or something.. To be honest, I don't really understand what it means to have the same file open for writing by several processes. You don't want to modify data which is already being modified by someone else, do you? I mean, how do you determine what changes to apply first, and to what version? Or is the file just constantly being overwritten on a first-come-first-served basis? I may well be completely braindead, here.. g > All this without having "the file is in use" errors, because well... only > windows has those :-) > > Oh, and btw: you'll notice that gVim is smart enough to notice that the > file is no longer there, or that it is there but is more recent than his > working copy (if you re-edited with gedit, for example). > > -- > Renato > -------------------------------- > Usi Fedora? Fai un salto da noi: > http://www.fedoraitalia.org From rrr at ronadam.com Wed Jun 22 17:50:43 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 22 Jun 2005 21:50:43 GMT Subject: PEP 343, second look In-Reply-To: <7xhdfq2lww.fsf@ruckus.brouhaha.com> References: <7xhdfq2lww.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Ron Adam writes: > >>>A new statement is proposed with the syntax: >>> with EXPR as VAR: >>> BLOCK >>> Here, 'with' and 'as' are new keywords; EXPR is an arbitrary >>> expression (but not an expression-list)... >> >>How is EXPR arbitrary? Doesn't it need to be or return an object that >>the 'with' statement can use? (a "with" object with an __enter__ and >>__exit__ method?) > > > That's not a syntactic issue. "x / y" is a syntactically valid > expression even though y==0 results in in a runtime error. The term 'arbitrary' may be overly broad. Take for example the description used in the 2.41 documents for the 'for' statement. "The expression list is evaluated once; it should yield an iterable object." If the same style is used for the with statement it would read. "The expression, (but not an expression-list), is evaluated once; it should yield an object suitable for use with the 'with' statement. ... " Or some variation of this. Regards, Ron From rossnixon at gmail.com Fri Jun 17 20:37:01 2005 From: rossnixon at gmail.com (ross) Date: 17 Jun 2005 17:37:01 -0700 Subject: What language to manipulate text files In-Reply-To: References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: <1119055021.570014.6590@z14g2000cwz.googlegroups.com> I tried Bash on Cygwin, but did not know enough about setting up the environment to get it working. Instead I got an excellent answer from alt.msdos.batch which used the FOR IN DO command. My next job is to learn Python. Ross From fredrik at pythonware.com Tue Jun 14 04:03:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 10:03:15 +0200 Subject: "also" to balance "else" ? References: <200506140232.59605.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > Personally, though, "for-finally" would make a lot more sense > to me than "for-else" (and I don't have enough "for-else" code > to worry about it breaking). "finally" means "run this piece of code no matter what happens in the previous block". that's not how "else" works in today's Python. From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 1 18:21:57 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 02 Jun 2005 00:21:57 +0200 Subject: pickle alternative In-Reply-To: <1117615222.581838.226820@g49g2000cwa.googlegroups.com> References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <1117524878.988878.181820@g44g2000cwa.googlegroups.com> <1117527950.319411.193030@g44g2000cwa.googlegroups.com> <1117606128.506536.234690@g14g2000cwa.googlegroups.com> <1117615222.581838.226820@g49g2000cwa.googlegroups.com> Message-ID: <3g6ql1FatsshU1@individual.net> simonwittber at gmail.com wrote: > Andrew Dalke wrote: >> This is with Python 2.3; the stock one provided by Apple >> for my Mac. > > Ahh that is the difference. I'm running Python 2.4. I've checked my > benchmarks on a friends machine, also in Python 2.4, and received the > same results as my machine. > >> I expected the numbers to be like this because the marshal >> code is used to make and read the .pyc files and is supposed >> to be pretty fast. > > It would appear that the new version 1 format introduced in Python 2.4 > is much slower than version 0, when using the dumps function. Not so for me. My benchmarks suggest no change between 2.3 and 2.4. Reinhold From kveretennicov at gmail.com Sat Jun 25 06:49:15 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 25 Jun 2005 12:49:15 +0200 Subject: Office COM automatisation - calling python from VBA In-Reply-To: References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <4660fe3005062503493864e9e8@mail.gmail.com> On 6/25/05, Stephen Prinster wrote: > guy lateur wrote: > > If you are new to Python and want to use it with COM, definitely get > yourself a copy of _Python Programming on Win32_ by Mark Hammond and > Andy Robinson. ...or at least read the chapter available online: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html It has an example of VBA / PythonCOM interaction. - kv From ronpro at cox.net Wed Jun 29 10:00:49 2005 From: ronpro at cox.net (ronpro at cox.net) Date: Wed, 29 Jun 2005 10:00:49 -0400 Subject: python broadcast socket Message-ID: <20050629140049.MNYQ28809.lakermmtao07.cox.net@smtp.east.cox.net> I'm sort of new to both Python and socket programming so I appologize ahead of time if this is a dumb question. I have found that the following code works on windows but on linux I get an exception. import socket s = socket.socket( socket.AF_INET, socket.SOCK_DGRAM ) s.connect( ( '', 1617 ) ) The exception I get is: socket.error: (13, 'permission denied') I have tried this on three Linux machines. All firewall software is disabled. Thanks for you time and patience. Ron From robert at reeves.net Wed Jun 29 03:59:13 2005 From: robert at reeves.net (rjreeves) Date: 29 Jun 2005 00:59:13 -0700 Subject: Newbie: Explain My Problem In-Reply-To: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> References: <1120029076.990374.243050@g44g2000cwa.googlegroups.com> Message-ID: <1120031953.527823.148790@z14g2000cwz.googlegroups.com> Hi Chuck 1. Missing an int(.. on one of the guess= print "You have", counter, " chances left to guess the number." guess = int(raw_input("Your guess is ")) Thus ensuring guess is consistent with it content type 2. Need a break when the guess=num if guess == num: print "You guessed the number, ", num, " in ", counter-6, " guesses!" break To stop from looping in the while when counter is NOT zero but the number has been found. From zathras at thwackety.com Sat Jun 11 17:44:19 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 11 Jun 2005 22:44:19 +0100 Subject: BBC R&D White Paper on Kamaelia Published (Essentially a framework using communicating python generators) Message-ID: <42ab5b17$0$2046$ed2e19e4@ptn-nntp-reader04.plus.net> Hi, I'm posting a link to this since I hope it's of interest to people here :) I've written up the talk I gave at ACCU Python UK on the Kamaelia Framework, and it's been published as a BBC R&D White Paper and is available here: * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml Essentially it provides a means of a) communicating to python generators b) linking these communications between generators (the result is calling these components), c) building interesting systems using it. (Next release will include some interesting things like a shell, introspection tool, and pygame related components) Essentially the key tenet of the project is that of trying to make scalable concurrent and network systems easy to build and reuse. We're using it for network research purposes, but the system should be sufficiently general to be of use for all sorts of uses. (Though for production systems I'd probably recommend Twisted over Kamaelia for now, just for perspective :) Any comments, criticisms/etc very welcome! Michael. -- http://kamaelia.sourceforge.net/ From lycka at carmen.se Tue Jun 14 05:05:58 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 14 Jun 2005 11:05:58 +0200 Subject: circular import Module In-Reply-To: <3h739uFfd4fmU1@individual.net> References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> <3h739uFfd4fmU1@individual.net> Message-ID: <42AE9DF6.9050101@carmen.se> Greg Ewing wrote: > Magnus Lycka wrote: > >> Due to the cycle, you can never use file1 without >> file2 or vice versa. Why do you then want it to be >> two different modules instead of one? > > Perhaps because it would then be too big and > unwieldy to maintain? > > Sometimes there are legitimate reasons for > mutually-dependent modules. Agreed, but I think it's important to think about the design if a chunk of code gets that big. Most of the time, things can be organized differently, and there will be maintenance gains from this. If you have mutual dependenices between two modules, they still have to be maintained as a unit. You can't disregard one when you modify the other. To achieve looser (and prefereably not mutual) dependencies between separate modules both makes it easier to maintain the modules and more likely that we will be able to reuse them in other contexts. Sure, there simple are tricks you can use to get away with mutual import dependencies, but if I ran into a mutual dependency between two Python modules, I would first think about their design and try to resolve this dependency issue. I probably wouldn't use a trick such as import in a local scope unless I was in a hurry and needed a quick fix while I was considering a proper design. (I might then be lazy and not resolve the design problem, but it would continue to disturb me...) Composition and inheritance might be used to break out parts of code that doesn't have dependencies to the rest of the code. There are all sorts of design pattern that can resolve mutual dependencies. I often use callbacks to get away from mutual dependencies. E.g. class Adder: def __init__(self, x, y, callback): self.x = x self.y = y self.callback = callback def calc(self): result = self.x + self.y self.callback(result) class Manager: def add(self, x, y): b = B(x, y, self.show) b.calc() def show(self, value): print value This is a silly example of course. Adder.calc could simply have returned the result, but I don't have time to construct anything elaborate now. The point I want to show is that by passing in a callable from Manager to Adder, Adder instances can call certain methods in particular Manager instanes without any dependencies to the module where Manager lives. It just needs to know what kind of parameters it should supply to the callable it was passed. Martin Fowler's book Refactoring shows a lot of examples that are useful when code grows and needs to be divided into smaller chunks. His examples and ideas revolve around Java and C++ though, and it's often much simpler in Python. From cpl.19.ghum at spamgourmet.com Fri Jun 10 13:08:33 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Fri, 10 Jun 2005 17:08:33 +0000 (UTC) Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: > They want a > "scalable, enterprise solution" (though they don't really know what > that means) and are going crazy throwing around the Java buzzwords > (not to mention XML). > There is a very cheap solution: Ryan Tomayko debunkes all these myths. You can google it up, "astronaut architects" There is a cheap solution: on this years EuroPython (www.europython.org) there will be a special Slot in Social Skills track dealing with "Selling Python", giving you a Python Sales Pitch and two more excellent seminars about persuading people. More than that, in Python in Business Track we will do slots about using Python for real worthy enterprise apps which scale and are FULLY buzzword-compatible. Join us! Harald Armin Massa GHUM Harald Massa perusasion. python. postgresql. From dvanvliet at 3dna.net Thu Jun 30 16:54:35 2005 From: dvanvliet at 3dna.net (Derek van Vliet) Date: 30 Jun 2005 13:54:35 -0700 Subject: saving pre-compiled scripts In-Reply-To: <1120163393.140445.311130@g47g2000cwa.googlegroups.com> References: <1120161509.096169.166730@o13g2000cwo.googlegroups.com> <1120163393.140445.311130@g47g2000cwa.googlegroups.com> Message-ID: <1120164875.172674.278250@g47g2000cwa.googlegroups.com> I probably should have also mentioned that my application is written in C++ and using the Python/C API. From benji at benjiyork.com Wed Jun 8 08:03:37 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 08 Jun 2005 08:03:37 -0400 Subject: test In-Reply-To: References: Message-ID: <42A6DE99.1010709@benjiyork.com> Nader Emami wrote: > File "/usr/lib/python2.3/unittest.py", line 657, in run > startTime = time.time() > AttributeError: 'module' object has no attribute 'time' I suspect that you have a module named "time.py" that is being imported instead of the standard library's time module. Do this to see where the module is coming from: >>> import time >>> time.time() # make sure you still get the exception >>> time.__file__ '/usr/lib/python2.3/lib-dynload/time.so' Be sure to do this in exactly the same way (same path, same Python, same user, etc.) that you are running your tests. Your file name may not match mine, but if it points to something other than the standard library, you've found the problem. -- Benji York From michele.simionato at gmail.com Mon Jun 6 09:15:41 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Jun 2005 06:15:41 -0700 Subject: Destructive Windows Script In-Reply-To: References: Message-ID: <1118063741.854716.183560@g14g2000cwa.googlegroups.com> BTW, since this is a bit off-topic anyway, how do I recover files accidentally removed? Is there a free tool that works on FAT/NTFS and ext2/ext3? Thanks, Michele Simionato From tjreedy at udel.edu Sat Jun 25 21:40:25 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Jun 2005 21:40:25 -0400 Subject: A strange and annoying restriction, possibly a bug. A glance by amore experienced would be nice. References: <42BDD500.4060303@jippii.fi> Message-ID: "Terry Reedy" wrote in message news:d9kuv9$msb$1 at sea.gmane.org... > > "Elmo M?ntynen" wrote in message > news:42BDD500.4060303 at jippii.fi... >>>>> n=(100,) tuple(*n) > > As posted, this gives a syntax error. What is missing? Actually, I should have said 'as received'. From fredrik at pythonware.com Mon Jun 13 05:48:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Jun 2005 11:48:14 +0200 Subject: os.system References: Message-ID: Austin wrote: >>> My code is " os.system("NET SEND computer hihi") " >>> i use this funtion on Windows server 2003. >>> it's ok. >>> >>> But the same code running on Windows XP SP2, it shows the command window >>> twice. >>> How do i remove the command window? >> >> Hi, >> >> You can remove the command window which comes >> from python if you use ".pyw" as extension. >> This is not an answer why the system method >> opens a second window, but maybe it helps, too. >> >> Thomas >> > Hi, but my program is complied from py2exe. > All extension is 'pyd'. > Hm... is there any way to do? no time to test, but the "subprocess" module might be what you need: http://www.python.org/dev/doc/devel/lib/module-subprocess.html http://www.effbot.org/downloads/#subprocess (for 2.2 and 2.3) (I assume you're already using the "windows" py2exe option for your own program) From nospam at here.com Thu Jun 9 15:07:00 2005 From: nospam at here.com (Matt Feinstein) Date: Thu, 09 Jun 2005 15:07:00 -0400 Subject: PIL and GeoTIFF References: Message-ID: <4j4ha1lfvqckn4n5ule701ggs7oneksgbr@4ax.com> On Thu, 09 Jun 2005 14:19:21 -0400, Khalid Zuberi wrote: >If you are willing to go in a bit of a different direction, GDAL >supports GeoTIFF and includes python bindings: > > http://www.remotesensing.org/gdal/ Looks interesting, but kinda heavy-duty for my purposes. If a couple of lines of Python added to what I've already got will do the job, I'd rather do that then compile and learn yet another API. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From __peter__ at web.de Sat Jun 25 16:55:42 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 25 Jun 2005 22:55:42 +0200 Subject: Big problem fetching members from dynamically loaded module References: Message-ID: Philippe C. Martin wrote: > OK Peter, first of all thanks. > > You seem to be German and although I leave in the states, I'm French and > your english is clearly far more advanced than mine: I have yet to > understand a few of your comments ;-) My French is mostly read-only, so let me rephrase: from module import *, try ... except, eval(), exec all work together to make your program harder to understand and more likely to fail in obscure ways. >> Care to provide the traceback? > > Traceback (most recent call last): > File "SC_Shell.py", line 1095, in ? > l_d = SC_Shell() > File "SC_Shell.py", line 326, in __init__ > self.__Make_Menu_Area() > File "SC_Shell.py", line 828, in __Make_Menu_Area > l = inspect.getmembers(eval(c)) > File "", line 0, in ? > NameError: name 'BC' is not defined That traceback and the code you posted do not fit together. So back to square one. Staring at the code you posted, I think one thing you could try would be to modify the eval() to eval("BC",?self.m_process_global, self.m_process_local) to ensure that eval() and exec share the same namespace. Generally speaking, I would prefer (I hope I got that right) module = __import__("package.module", globals(), locals(), ["module"]) members = inspect.getmembers(module) Members of the module would then be accessed via getattr(): member = getattr(module, member_name) Peter From peter at engcorp.com Thu Jun 2 12:57:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 12:57:24 -0400 Subject: Easy way to detect hard drives and partitions in Linux In-Reply-To: <1117730941.946683.88840@g44g2000cwa.googlegroups.com> References: <1117730941.946683.88840@g44g2000cwa.googlegroups.com> Message-ID: RunLevelZero wrote: > I need a way to detect hard drives and their partitions... labels would > be nice too... I did some googling but did not find anything all too > useful. This will strictly be on Linux / Unix so any help would be > greatly appreciated. os.popen('/sbin/sfdisk -l /dev/hda') etc... ? Or reading from /proc/ide and friends? From wuwei23 at gmail.com Thu Jun 2 23:32:11 2005 From: wuwei23 at gmail.com (alex23) Date: 2 Jun 2005 20:32:11 -0700 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <1117769531.351670.39530@g14g2000cwa.googlegroups.com> Sorry to continue with the thread hijack... Steven D'Aprano wrote: > (3) You have create an incredibly valuable piece of code that will be > worth millions, but only if nobody can see the source code. Yeah right. An interesting corollay that comes from source code transparency is that it generally makes it a lot easier to see who has stolen from you. -alex23 From jepler at unpythonic.net Sun Jun 12 21:40:37 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 12 Jun 2005 20:40:37 -0500 Subject: count string replace occurances In-Reply-To: <1118620538.711624.237680@z14g2000cwz.googlegroups.com> References: <1118620538.711624.237680@z14g2000cwz.googlegroups.com> Message-ID: <20050613014034.GA2945@unpythonic.net> On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote: > if i have > mytext.replace(a,b) > how to find out many many occurances has been replaced? The count isn't returned by the replace method. You'll have to count and then replace. def count_replace(a, b, c): count = a.count(b) return count, s.replace(b, c) >>> count_replace("a car and a carriage", "car", "bat") (2, 'a bat and a batriage') -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ukc902591034 at btconnect.com Mon Jun 27 03:14:07 2005 From: ukc902591034 at btconnect.com (Alan Gauld) Date: Mon, 27 Jun 2005 07:14:07 +0000 (UTC) Subject: noob question References: Message-ID: "Matt Hollingsworth" wrote in message news:mailman.911.1119762374.10512.python-list at python.org... > Very new to python, so a noob question. When I've written stuff in > JavaScript or MEL in the past, I've always adopted the variable naming > convention of using a $ as the first character (no, I don't use perl, Can I ask why you did that? Did someone tell you to or did you hit on the idea yourself? Do you really find it useful? I mean do you often in your Python coding find a problem with identifying your variables? I'm curious because one of the things I like most about Python is the fact I don't need to mess up my programs with spurious characters like $ etc. And I never have any problem identifying variables etc in my code. (The same is true of Object Pascal in Delphi, my other favourite language). The only place I've ever found Hungarian notation useful was in C which is a weird mix of static typing and no-typing, and there the prefix code gives a clue as to what kind of value you might expect to find. But when I moved to C++ I dropped the prefixes because they added no value. In Python Hungarian notation is meaningless since variables aren't typed anyway. So I am curious as to why anyone would feel the need to introduce these kinds of notational features into Python. What is the problem that you are trying to solve? -- Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From daniel.dittmar at sap.corp Fri Jun 10 10:50:24 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Fri, 10 Jun 2005 16:50:24 +0200 Subject: MySQLDBAPI In-Reply-To: References: <2tqln2-6c3.ln1@news.interplanet.it> Message-ID: Gregory Pi?ero wrote: > Is that something I can install all to my home directory? If you have a similar Linux distribution at home, simply build the mysql extension on that machine and then copy it to the web server. Otherwise: You don't have to actually install it. Just make sure that Setup.py finds the headers and libs 1a) get the rpm and extract the files or 1b) compile (but don't install) mysql from sources 2) specify the locations of the header files and the libs to Setup.py or patch the module such that the defaults point to your directories. From your error message, the current default for the includes seems to be /usr/local/mysql/include/mysql 3) You can then delete the directories created in 1a or 1b Daniel From guy.lateur at b-b.be Tue Jun 14 05:43:54 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 14 Jun 2005 09:43:54 GMT Subject: Where is Word? Message-ID: Hi all, I need a way to get the path where MS Word/Office has been installed. I need to start Word from a script (see earlier post), but it doesn't work if I don't know its path. So "os.system("winword.exe %s" % fileName)" doesn't always work; I need to say "os.system("C:\Program Files\Microsoft Office\Office10\winword.exe %s" % fileName)". Any ideas? TIA, g From dsa at unilestemg.br Thu Jun 9 14:24:48 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Thu, 9 Jun 2005 18:24:48 +0000 Subject: smtpd module In-Reply-To: <42C7E766869C42408F0360B7BF0CBD9B014B6156@pnlmse27.pnl.gov> References: <42C7E766869C42408F0360B7BF0CBD9B014B6156@pnlmse27.pnl.gov> Message-ID: <200506091824.48693.dsa@unilestemg.br> Hi Chad ! I dont know how to use smtpd, but... why not use Twisted ? See ya ! Em Quinta 09 Junho 2005 21:13, Hughes, Chad O escreveu: > No, I know how to use the smtplib module and I can send email through > that. However what I want is a the ability to set up a very simple mail > server with python, for some tests that I need to run that just prints > out the message to the standard out and disregards the message. The > smtpd module seems to provide this ability via the DebuggingServer. > According to the documentation that is provided with python the: > > class DebuggingServer( localaddr, remoteaddr) > Create a new debugging server. > Arguments are as per SMTPServer. > Messages will be discarded, and printed on stdout. > > Unfortunately, this does not tell me how to use it. I cannot find any > examples on the web. For that matter, I cannot find any other > documentation anywhere. Has anyone ever used ether the SMTPServer > object or the DebuggingServer object? If so, I would appreciate very > much an example use case. > > Thanks, > Chad > > -----Original Message----- > From: Ivan Shevanski [mailto:darkpaladin79 at hotmail.com] > Sent: Thursday, June 09, 2005 2:03 PM > To: python-list at python.org > Cc: Hughes, Chad O > Subject: RE: smtpd module > > > So youre wondering how to send mail in python? I have a lot of examples > if > you want the smtp module. I don't have anything for anything other than > the > smtp module. > > -Ivan > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today - it's > FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From k04jg02 at kzoo.edu Fri Jun 24 05:59:23 2005 From: k04jg02 at kzoo.edu (Joseph Garvin) Date: Fri, 24 Jun 2005 03:59:23 -0600 Subject: Favorite non-python language trick? In-Reply-To: <3i232vFj0b57U1@individual.net> References: <3i232vFj0b57U1@individual.net> Message-ID: <42BBD97B.5090001@kzoo.edu> Claudio Grondi wrote: >>And you can do block comments with --[[ and ---]]. >> >> > >I am very happy not to have such "tricks" in Python. > >Any other (useful) suggestions? > >Claudio > > I'm glad and all that not everyone shares my enthusiasm over Lua's trick, and I'm glad that C/C++ can do it, but the original issue was non-python language tricks in general. Lets keep the thread on track. So far we've got lisp macros and a thousand response's to the lua trick. Anyone else have any actual non-python language tricks they like? Yeesh. >"Joseph Garvin" schrieb im Newsbeitrag >news:mailman.837.1119596150.10512.python-list at python.org... > > >>As someone who learned C first, when I came to Python everytime I read >>about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), >>getattr/setattr, the % operator, all of this was very different from C. >> >>I'm curious -- what is everyone's favorite trick from a non-python >>language? And -- why isn't it in Python? >> >>Here's my current candidate: >> >>So the other day I was looking at the language Lua. In Lua, you make a >>line a comment with two dashes: >> >>-- hey, this is a comment. >> >>And you can do block comments with --[[ and ---]]. >> >>--[[ >>hey >>this >>is >>a >>big >>comment >>--]] >> >>This syntax lets you do a nifty trick, where you can add or subtract a >>third dash to change whether or not code runs: >> >>--This code won't run because it's in a comment block >>--[[ >>print(10) >>--]] >> >>--This code will, because the first two dashes make the rest a comment, >>breaking the block >>---[[ >>print(10) >>--]] >> >>So you can change whether or not code is commented out just by adding a >>dash. This is much nicer than in C or Python having to get rid of """ or >>/* and */. Of course, the IDE can compensate. But it's still neat :) >> >> > > > > From bretthoerner at gmail.com Mon Jun 27 22:44:20 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 27 Jun 2005 19:44:20 -0700 Subject: Better console for Windows? Message-ID: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> This is a pretty basic, mostly un-python-related question, although I'm asking because of Python. Is there a different shell I can use (other than cmd.com) to run Python in, where I can full-screen the window (if I pleased), etc? As it is, things that would run far off the right have to be word wrapped after very few characters. Another problem with cmd.com is when I run IPython, if I have an error, or tab or anything, I get the speaker beep (ala linux) but I can't find a way to turn it off. This is a huge problem because I cannot disable my system speaker on my laptop (not even in BIOS like my old one, and it's an "error", it bypasses the fact that all my sound is muted in Windows) and I get incredibly loud beeps all the time (because I suck) which would not be acceptable while I'm coding on the sly in boring class. Ideas? The only thing I can think of now is using Putty to SSH into a machine, no beeps there, and I can resize... but I don't have a machine to SSH into, much less one with all the stuff I want on it. Thanks in advance. Brett From mwm at mired.org Tue Jun 28 23:22:14 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 28 Jun 2005 23:22:14 -0400 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <861x6ldezd.fsf@bhuda.mired.org> Ivan Van Laningham writes: > In which case, you should start with PostScript;-) I learned it by > plugging a glass tty into the serial port on one of the very first > AppleWriters and typing away. None of this fancy-shmancy '>>>' > business;-) But what a great reward, having graphics come out the > printer when you typed 'show'. This is why Logo came with "turtle graphics". Something very simple, but very powerfull - and the kids could get immediate results from it. I'm surprised the OP missed Logo in his search. It's one of the few languages designed to teach computing to children. There are free implementations for most popular platforms. Someone has already provided a link to pylogo. That might be a good starting place. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From kkylheku at gmail.com Tue Jun 21 01:50:57 2005 From: kkylheku at gmail.com (Kaz Kylheku) Date: 20 Jun 2005 22:50:57 -0700 Subject: references/addrresses in imperative languages In-Reply-To: <11bf5ln27f0qf6f@corp.supernews.com> References: <1119323217.670985.68250@o13g2000cwo.googlegroups.com> <11bf5ln27f0qf6f@corp.supernews.com> Message-ID: <1119333057.616703.24210@z14g2000cwz.googlegroups.com> SM Ryan wrote: > "Kaz Kylheku" wrote: > # SM Ryan wrote: > # > # easy way to see this, is to ask yourself: how come in mathematics > # > # there's no such thing as "addresses/pointers/references". > # > > # > The whole point of Goedelisation was to add to name/value references into > # > number theory. > # > # Is that so? That implies that there is some table where you can > # associate names (or whatever type of locators: call them pointers, > # whatever) with arbitrary values. But in fact that's not the case. > > Do you really believe the Goedel number of a statement is the statement > itself? Is everything named Kaz the same as you? The Goedel number is a representation of the statement in a way that the name Kaz isn't a representation of me. You cannot identify parts of the name Kaz with parts of me; there is no isomorphism there at all. I am not the translated image of the name Kaz, nor vice versa. A Goedel number isn't anything like a name or pointer. It's an encoding of the actual typographic ``source code'' of the expression. There is nothing external to refer to other than the encoding scheme, which isn't particular to any given Goedel number. The encoding scheme is shallow, like a record player; it doesn't contribute a significant amount of context. If I decode a Goedel number, I won't have the impression that the formula was hidden in the numbering scheme, and the Goedel number simply triggered it out like a pointer. No, it will be clear that each piece of the resulting formula is the direct image of some feature of the Goedel number. From rfquerin at gmail.com Mon Jun 6 13:13:58 2005 From: rfquerin at gmail.com (RFQ) Date: 6 Jun 2005 10:13:58 -0700 Subject: Reading a CSV file into a list of dictionaries Message-ID: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> Hi, I'm struggling here to do the following with any success: I have a comma delimited file where each line in the file is something like: PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... So each line is intended to be: key1,value1,key2,value2,key3,value3... and each line is to be variable in length (although it will have to be an even number of records so that each key has a value). I want to read in this csv file and parse it into a list of dictionaries. So each record in the list is a dictionary: {"PNumber":"3056","Contractor":"XYZ Contracting", ... } I have no problem reading in the CSV file to a list and splitting each line in the file into its comma separated values. But I can't figure out how to parse each resulting list into a dictionary. Any help on this? From harold.fellermann at upf.edu Mon Jun 13 13:36:48 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 13 Jun 2005 19:36:48 +0200 Subject: Controlling assignation In-Reply-To: References: <73cd19a37027b3d16c44d04ea560ee3 2@upf.edu> Message-ID: <35b681263693df6a62b99837cfd2489c@upf.edu> On 13.06.2005, at 19:23, Terry Reedy wrote: > > "harold fellermann" wrote in message > news:73cd19a37027b3d16c44d04ea560ee32 at upf.edu... > >> if you write >>>>> a=A() >> an instance of class A is created and bound to the local identifier >> 'a'. > > I think it perhaps better to think of the label 'a' being bound to the > object rather than vice versa. For one, a label can only be bound > (stuck > to, like a stick note) to one object at a time while one object can > have > many labels (and other references) stuck to it. > >> If you later write >>>>> a=5 >> the object 5 is reassigned to the same identifier, > > Or one could say that the label 'a' is removed from the A() object and > reassigned to the 5 object. Since the 5 object may have numerous other > connections, and since those connections are unaffected by the new > connection to 'a', whereas the previous assignment of 'a' is broken, I > think it better to say that 'a' is being reassigned, not 5. yeah. I have never seen it this way, but you are right! Binding the identifier/label to the object is a much better perspective. thanks for the lesson :) - harold - -- Ceci n'est pas une signature. -- From kveretennicov at gmail.com Thu Jun 16 20:05:56 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Fri, 17 Jun 2005 02:05:56 +0200 Subject: thread.start_new_thread question Message-ID: <4660fe300506161705703767c6@mail.gmail.com> Hi, Just curious: >>> import thread >>> help(thread.start_new_thread) . . . start_new_thread(function, args[, kwargs]) . . . Second argument is mandatory. Is it incidental or for a reason? - kv From hancock at anansispaceworks.com Wed Jun 22 01:59:14 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 22 Jun 2005 00:59:14 -0500 Subject: *Python* Power Tools In-Reply-To: <42b8a85d$1@news.eftel.com> References: <42b8a85d$1@news.eftel.com> Message-ID: <200506220059.14800.hancock@anansispaceworks.com> On Tuesday 21 June 2005 06:53 pm, John Machin wrote: > Micah wrote: > > Anyone know if there is any organized effort underway to implement the > > Python equivalent of "Perl Power Tools" ? > > > > If not, would starting this be a waste of effort since: > > +1 WOFTAM-of-the-year [...] > > Or would people really like to claim a pure Python set of UNIX > > utilities? > > Sorry, can't parse that last sentence. In other words, it'd be a purely aesthetic goal. Which is only a waste if art is. But then, I know *I'm* not going to spend time on it. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From noreply at gcgroup.net Thu Jun 16 13:28:19 2005 From: noreply at gcgroup.net (William Gill) Date: Thu, 16 Jun 2005 17:28:19 GMT Subject: access properties of parent widget in Tkinter In-Reply-To: <42b17114$1_2@newspeer2.tds.net> References: <42b17114$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > William Gill wrote: > >> I am trying to get & set the properties of a widget's parent widget. >> What I have works, but seems like a long way around the block. First >> I get the widget name using w.winfo_parent(), then i convert the name >> to a reference using nametowidget(). >> >> self.nametowidget(event.widget.winfo_parent()).hasChanged= True > > > Personally I think it is bad design for a widget to assume anything > about its enclosing environment. What about passing a StringVar or > IntVar to the child widget and letting it work with that? > > Kent I stumbled across the widget.master attribute. so self.nametowidget(event.widget.winfo_parent()).hasChanged = True can be re-written as self.master.hasChanged = True I thought I was doing things the indirect way. Thanks everyone for your help. I'm still interested in if anyone thinks this is "bad practice", and why. Bill From claudio.grondi at freenet.de Fri Jun 24 10:59:06 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 24 Jun 2005 14:59:06 -0000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: <3i2eefFj7jhvU1@individual.net> I supose it will be very, very hard to find a trick which turns out useful in Python. The current set of features is from my point of view very well designed out of the experience with many other languages, so maybe you can use Python as reference telling you which tricks are really useful in programming and which are just bad, non-Pythonic style. At least I am myself out of ideas, else I had proposed a PEP already, to get it or have provided a module for it. So feel free to poke around with Python. if(not \ "--[[" == "--[["): # block of code # --]] as (already suggested) will also do the trick with the block comment. By the way, I personally find --[[ good style comment block ]]-- or [[-- good style comment block --]] much more intuitive than --[[ bad style comment block --]] Claudio "Joseph Garvin" schrieb im Newsbeitrag news:mailman.840.1119607153.10512.python-list at python.org... > Claudio Grondi wrote: > > >>And you can do block comments with --[[ and ---]]. > >> > >> > > > >I am very happy not to have such "tricks" in Python. > > > >Any other (useful) suggestions? > > > >Claudio > > > > > I'm glad and all that not everyone shares my enthusiasm over Lua's > trick, and I'm glad that C/C++ can do it, but the original issue was > non-python language tricks in general. Lets keep the thread on track. > > So far we've got lisp macros and a thousand response's to the lua trick. > Anyone else have any actual non-python language tricks they like? > > Yeesh. > > > >"Joseph Garvin" schrieb im Newsbeitrag > >news:mailman.837.1119596150.10512.python-list at python.org... > > > > > >>As someone who learned C first, when I came to Python everytime I read > >>about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > >>getattr/setattr, the % operator, all of this was very different from C. > >> > >>I'm curious -- what is everyone's favorite trick from a non-python > >>language? And -- why isn't it in Python? > >> > >>Here's my current candidate: > >> > >>So the other day I was looking at the language Lua. In Lua, you make a > >>line a comment with two dashes: > >> > >>-- hey, this is a comment. > >> > >>And you can do block comments with --[[ and ---]]. > >> > >>--[[ > >>hey > >>this > >>is > >>a > >>big > >>comment > >>--]] > >> > >>This syntax lets you do a nifty trick, where you can add or subtract a > >>third dash to change whether or not code runs: > >> > >>--This code won't run because it's in a comment block > >>--[[ > >>print(10) > >>--]] > >> > >>--This code will, because the first two dashes make the rest a comment, > >>breaking the block > >>---[[ > >>print(10) > >>--]] > >> > >>So you can change whether or not code is commented out just by adding a > >>dash. This is much nicer than in C or Python having to get rid of """ or > >>/* and */. Of course, the IDE can compensate. But it's still neat :) > >> > >> > > > > > > > > > From lycka at carmen.se Wed Jun 1 09:51:06 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 01 Jun 2005 15:51:06 +0200 Subject: xml processing In-Reply-To: References: Message-ID: Jeff Elkins wrote: > I've like to use python to maintain a small addressbook which lives on a Sharp > Zaurus. This list will never grow beyond 200 or so entries. I've installed > pyxml. > > Speaking generally, given a wxpython app to do data entry, > I'm planning to: > > 1. parse the addressbook file, loading its data into an array. > 2. Perform any edit operations within the array. > 3. Write out a finished xml file from the array when I'm done. > > Is this reasonable? Better, smarter ways to accomplish this? Why XML? I guess the simplest solution whould be to use pickle. Saving: >>> import pickle >>> l = [] >>> l.append(('Alan', '1st Street', 123456)) >>> l.append(('Ben', '2nd Street', 234567)) >>> l.append(('Clark', '3rd Street', 345678)) >>> f = open('phonebook','w') >>> pickle.dump(l, f) >>> f.close() Loading: >>> import pickle >>> f2 = open('phonebook') >>> l = pickle.load(f2) >>> f2.close() >>> for item in l: print item ('Alan', '1st Street', 123456) ('Ben', '2nd Street', 234567) ('Clark', '3rd Street', 345678) The file looks like this: >>> print open('phonebook').read() (lp0 (S'Alan' p1 S'1st Street' p2 I123456 tp3 a(S'Ben' p4 S'2nd Street' p5 I234567 tp6 a(S'Clark' p7 S'3rd Street' p8 I345678 tp9 a. >>> Ok, the file content might not seem completely obvious, but it's not really so difficult to parse it, and it's certainly less verbose than XML. Above all, much less code. BTW, cPickle is faster than pickle, but I suspect it doesn't matter with such a small amount of data. It's easy to replace "import pickle" with "import cPickle as pickle" to try it out. From philippe at philippecmartin.com Mon Jun 20 13:18:44 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 17:18:44 GMT Subject: Python choice of database References: <7xll55ynf5.fsf@ruckus.brouhaha.com> Message-ID: Correct, that's not a constraint right now. Paul Rubin wrote: > "Philippe C. Martin" writes: >> 1) speed is not an issue >> 2) I wish to store less than 5000 records >> 3) each record should not be larger than 16K > > You don't mention whether multiple running programs need to use it > concurrently. That's usually done with client/server db's but it can > be done standalone. From steve at REMOVEMEcyber.com.au Thu Jun 30 00:08:26 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 30 Jun 2005 14:08:26 +1000 Subject: Help please: How to assign an object name at runtime References: <1120092944.710361.309310@g44g2000cwa.googlegroups.com> <42C35CB2.1040204@lexicon.net> Message-ID: <42C3703A.3080305@REMOVEMEcyber.com.au> John Machin wrote: > BTW, don't use "l". Excellent advice. But since the original poster appears to be rather a newbie, perhaps a little bit of explanation would be useful. Variables like l and I should be avoided like the plague, because in many fonts and typefaces they are indistinguishable, or look like the digit 1. Yes, I'm sure you are using a fancy syntax-highlighting editor that colours them differently, but the day will come that you are reading the code on pieces of dead tree and then you'll be sorry that you can't tell the difference between l and 1. Another bit of advice: never use words like "list", "str", "int" etc as names for variables, because they conflict with Python functions: py> list("AB") ['A', 'B'] py> list = [] py> list("AB") Traceback (most recent call last): File "", line 1, in ? TypeError: object of type 'list' is not callable In general, I only use single letter variable names like a, b, L (for a list), s (for a string) in short function code, where the nature of the variable is obvious from the context: def stepsum(n, step=1): total = 0 for i in range(0, n, step): total + i return total def add_colon_str(s, t): return s + ": " + t It doesn't need much explanation to understand what s and t are. But for anything more complex, I always use descriptive names. -- Steven. From bokr at oz.net Sun Jun 26 15:18:35 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 19:18:35 GMT Subject: PEP 304 (was: Re: Any way to not create .pyc files?) References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <42befb50.271285618@news.oz.net> On Thu, 9 Jun 2005 18:12:35 -0500, Skip Montanaro wrote: > > >> PEP 304 would have helped, but it appears to be deceased. > >Just resting... > >FWIW, I reapplied it to my cvs sandbox the other day and plan to at least >generate a new patch from that. It's pretty much done, except... Once upon >a time, someone identified some problems for Windows with its multiple-root >file system. I've tried a couple times to dig it up, but have been >unsuccessful. If anyone can find it (or was the author, better yet), let me >know. At the very least I'd like to amend the PEP. Ideally, I'd like to >solve the problem and get PEP 304 going again. > Re multiple-root... IMO it would be nice to have an optional way of running python so that all file system paths would be normalized to Unix-style and platform-independent. On a windows system, the model used by msys/MinGW could be used, where you can mount subtrees per fstab and the "drives" wind up being /c/path for C:\path etc. And you could potentially mount different file systems also, including /proc and /dev synthetic things. On unix it could largely be pass-throughs, IWT, except for mountable file system objects written in pure python which would probably need some interfacing help. This would also be a potential way of feeding/logging tests of software that accesses the file system, using special mountable testing file systems. It also lets you switch I/O sources and sinks with mounts that are external to a particular python program being run. Don't know how factorable all that is in python, but I would think the bulk would be changes in os and hopefully pretty transparent elsewhere. Regards, Bengt Richter From bhoel at despammed.com Wed Jun 1 15:53:24 2005 From: bhoel at despammed.com (=?utf-8?q?Berthold_H=C3=B6llmann?=) Date: Wed, 01 Jun 2005 21:53:24 +0200 Subject: avl tree References: Message-ID: Zunbeltz Izaola writes: > On Tue, 31 May 2005 22:40:19 +0200, Berthold H?llmann wrote: > >> You can grab it from >> >> >> > > Thanks i will play with it. But i have realize that what i need was > exactly a binary tree. I haven't used tree yet and i don't know if i > can use the avl instaead an ordinary binary tree. > I have to construct a tree like this > > A > > B C > > A C A B > > B C A B B C A C > > > but i think i can construct a avl using left/right. Am I correct? The point with AVL trees is, that they are self balancing, If you want to 'define' the structure of the tree, you have to find another solution. Berthold -- berthold at xn--hllmanns-n4a.de / bhoel at web.de / From cal_2pac at yahoo.com Sun Jun 12 12:37:00 2005 From: cal_2pac at yahoo.com (cal_2pac at yahoo.com) Date: 12 Jun 2005 09:37:00 -0700 Subject: How to receve user events from IE on objects within frames Message-ID: <1118594220.223825.43350@g43g2000cwa.googlegroups.com> Resurrecting a month old thread.. (listed at http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2f4e50e1e316eef4/5924203f822f7f4b?q=cal_2pac&rnum=3#5924203f822f7f4b) Somehow - responses to that thread are not being brought up in chronological order. Thus the creation of another thread. The thread listed above proposed a solution to receive events from user events on the document in a webpage. However, it seems that this solution does not return events on objects within frames in webpages eg . if you go to www.andersondirect.com - the page is composed of three frames called as topFrame main and address. Now when I click on say 'Select a Vehicle' which is within main - I do not get any Onclick event. I also do not get an OnMousemove event if I move the mouse. However, I do get on Mousemove event on a tag called as frameset (which is part of the top page). How does one get events from the frames then? From littlejohn.75 at news.free.fr Wed Jun 22 15:18:07 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 22 Jun 2005 19:18:07 GMT Subject: Package organization References: Message-ID: <42b9b96f$0$32342$636a15ce@news.free.fr> Le Wed, 22 Jun 2005 20:42:24 +0200, Thomas Lotze a ?crit : > Hi, > > I've two questions concerning organizing and naming things when writing > a Python package. > > Assume I have a package called PDF. Should the classes then be called > simply File and Objects, as it is clear what they do as they are > imported from PDF? Or should they be called PDFFile and PDFObjects, as > the names would be too undescriptive otherwise? As you whish :-) if in the package ie in the __init__.py (not the best idea) from PDF import File as PDFFile # always possible if File is defined in a module Objects from PDF.Objects import File # as PDFFile is always possible. Have you installed the reportlab package ? It is full of from ... import .. and it generates PDF. From hancock at anansispaceworks.com Sun Jun 12 02:18:09 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 12 Jun 2005 01:18:09 -0500 Subject: What language to manipulate text files In-Reply-To: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> Message-ID: <200506120118.09810.hancock@anansispaceworks.com> On Saturday 11 June 2005 11:37 pm, ross wrote: > I want to do some tricky text file manipulation on many files, but have > only a little programming knowledge. [...] > Would Python be best, or would a macro-scripting thing like AutoHotKey > work? > I thought about Perl, but think I would learn bad habits and have hard > to read code. Both Perl and Python are *extremely* good at this kind of work. This is pretty much what inspired Perl, and Python implements most of the same toolset. You will solve many of these kinds of problems using "regular expressions" (built-in first-class object in Perl, created from strings in Python using the "re" module). No surprise of course that I would choose Python. Mainly because of what it provides beyond regular expressions. Many simple cases can be handled with string methods in Python (check the Sequence types information in the built-ins section of the Library Reference -- also look at the "string" module, though it's usually easier to use the string methods approach). You will probably end up with more readable code using Python and take less time to develop sufficient proficiency to do the job with it. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From tim.golden at viacom-outdoor.co.uk Wed Jun 29 08:54:18 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 13:54:18 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... Message-ID: <9A28C052FF32734DACB0A288A3533991EBB950@vogbs009.gb.vo.local> [A.M. Kuchling] | I think that backwoods American speech is more archaic, and | therefore is possibly closer to historical European speech. | Susan Cooper uses this as a minor plot point in her juvenile | novel "King of Shadows", which is about a 20th-century | Southern kid who goes back to Elizabethan times and ends up | acting with Shakespeare; his accent ensures that he doesn't | sound *too* strange in 16th-century London. Aha! Bit of North American parochialism there. The fact that he's a "Southern kid" doesn't say "from the southern states of North America" to everyone. All right, in fact it's clear from the context, but I just fancied having a jab. In fact, I rather like the fact that he can truthfully claim to come from Falmouth, which his hearers (including Queen Elizabeth!) understand to mean the town in the West Country [of England] whereas in fact he means the town in Carolina (apparently). TJG | | --amk | -- | http://mail.python.org/mailman/listinfo/python-list | | ______________________________________________________________ | __________ | This e-mail has been scanned for all viruses by Star. The | service is powered by MessageLabs. For more information on a proactive | anti-virus service working around the clock, around the globe, visit: | http://www.star.net.uk | ______________________________________________________________ | __________ | ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From simon.brunning at gmail.com Thu Jun 30 04:20:19 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 30 Jun 2005 09:20:19 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1120084451.475909.19390@o13g2000cwo.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> Message-ID: <8c7f10c605063001207fd379ec@mail.gmail.com> On 29 Jun 2005 15:34:11 -0700, Luis M. Gonzalez wrote: > What's exactly the "cockney" accent? > Is it related to some place or it's just a kind of slang? A cockney is a *real* Londoner, that is, someone born within the City of London, a.k.a The Square Mile. More specifically, it's someone born "within the sound of Bow Bells" - i.e. close to St Mary le Bow, London - . This is within the theoretical sound of Bow Bells, you understand - there have been frequent and lengthy periods during which Bow Bells have not been rung at all. There are in fact no longer any hospitals with maternity units within the sound of Bow Bells, so there will be vanishingly few cockneys born in future. Strangely enough, this makes *me* a cockney, though I've never lived in the square mile, and my accent is pretty close to received. I do *work* in the City, though! The cockney accent used to be pretty distinct, but these days it's pretty much merged into the "Estuary English" accent common throughout the South East of England. > I'm not sure, but I think that I read somewhere that it is common in > some parts of London, and that it is a sign of a particular social > class, more than a regionalism. Is that true? Cockney was London's working class accent, pretty much, thought it was frequently affected by members of the middle classes. Estuary English has taken over its position as the working class accent these days, but with a much wider regional distribution. How off topic is this? Marvellous! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tim.peters at gmail.com Thu Jun 30 14:55:08 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 30 Jun 2005 14:55:08 -0400 Subject: %g and fpformat.sci() In-Reply-To: <20050630182144.BFFBD37466@postoffice.hks.com> References: <20050630182144.BFFBD37466@postoffice.hks.com> Message-ID: <1f7befae050630115556ac6f44@mail.gmail.com> [Sivakumar Bhaskarapanditha] > How can I control the number of digits after the decimal point using the %g > format specifier. You cannot. See a C reference for details; in general, %g is required to truncate trailing zeroes, and in %.g the is the maximum number of significant digits displayed (the total number both before and after the decimal point). If you need to preserve trailing zeroes, then you need to write code to do that yourself, or use the %e format code (or maybe even %f). For example, >>> a = 1.234e-5 >>> print "%.6g" % a 1.234e-005 >>> print "%.60g" % a 1.234e-005 >>> print "%.6e" % a 1.234000e-005 >>> print "%.6f" % a 0.000012 From gsakkis at rutgers.edu Fri Jun 10 11:56:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jun 2005 08:56:50 -0700 Subject: Annoying behaviour of the != operator References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: <1118419010.114824.200580@g49g2000cwa.googlegroups.com> "Rocco Moretti" wrote: > One way to handle that is to refuse to sort anything that doesn't have a > "natural" order. But as I understand it, Guido decided that being able > to sort arbitrary lists is a feature, not a bug. He has changed his mind since then (http://mail.python.org/pipermail/python-dev/2004-June/045111.html) but it was already too late. Waiting-for-python-3K'ly yours George From gsakkis at rutgers.edu Sat Jun 18 09:10:25 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 18 Jun 2005 06:10:25 -0700 Subject: OO approach to decision sequence? References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> <42B3D2BC.3050406@po-box.mcgill.ca> Message-ID: <1119100225.438987.221850@f14g2000cwb.googlegroups.com> "Chinook" wrote: > I understand what you are saying. The point I'm messing up my head with > though, is when the entity (tree node in my case or variable record content > deconstructing in the aspect example I noted) is not an instance of a class > already - it is obtained from an external source and only decipherable by its > content. > > In practical terms that leaves me with some decision sequence regardless and > I was wondering (from what Chris Smith said) how that might be done in OOP. > The whole problem may be that I'm reading too much into what Chris said :~) > I will dig back through the Tutor archives as you suggested. What you are looking for is what is called the 'factory method pattern' (http://en.wikipedia.org/wiki/Factory_method_pattern) and it's one of the cases where OOP doesn't eliminate the if/elif/elif (or switch in C++/Java). That's ok though because, as you noticed, at some point you have to take a decision. What's important is the "once and only once" principle, that is all the decision logic is encapsulated in a single method (or in python in a single function) instead of being replicated every time you want to use an existing Node. Regards, George From dieter at handshake.de Sat Jun 18 14:48:11 2005 From: dieter at handshake.de (Dieter Maurer) Date: 18 Jun 2005 20:48:11 +0200 Subject: Unbound names in __del__ References: Message-ID: Peter Hansen writes on Fri, 17 Jun 2005 08:43:26 -0400: > ... > And I don't recall the last time I saw a __del__ in third-party code I > was examining. > > > What's your use case for del? I had to use one a few days ago: To call the "unlink" method of a "minidom" object when its "container" is destroyed. It would have been possible to let the cyclic garbage collector find and eliminate the cyclic "minidom" objects. But, DOMs may be large and I create lots of them in a short time (each in its own container)... Dieter From hancock at anansispaceworks.com Tue Jun 28 23:54:25 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 28 Jun 2005 22:54:25 -0500 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <861x6ldezd.fsf@bhuda.mired.org> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <861x6ldezd.fsf@bhuda.mired.org> Message-ID: <200506282254.25156.hancock@anansispaceworks.com> On Tuesday 28 June 2005 10:22 pm, Mike Meyer wrote: > Ivan Van Laningham writes: > > In which case, you should start with PostScript;-) I learned it by > > plugging a glass tty into the serial port on one of the very first > > AppleWriters and typing away. None of this fancy-shmancy '>>>' > > business;-) But what a great reward, having graphics come out the > > printer when you typed 'show'. > > This is why Logo came with "turtle graphics". Something very simple, > but very powerfull - and the kids could get immediate results from it. I suppose it's worth mentioning then, that Python has it's own implementation of turtle graphics? I think it's in the standard library, isn't it? The "Live Wires" graphics module is also a good start --- very similar to the kind of graphics interface that I had when I was learning on my TRS-80 Color Computer with BASIC. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From benji at benjiyork.com Sat Jun 25 09:01:51 2005 From: benji at benjiyork.com (Benji York) Date: Sat, 25 Jun 2005 09:01:51 -0400 Subject: Life of Python In-Reply-To: References: Message-ID: <42BD55BF.6000705@benjiyork.com> Uwe Mayer wrote: > con: If you are planning larger applications (for a reasonable value of > "large") you have to discipline yourself to write well structured code. This is definitely true, no matter the language you use. > Then you will want to specify interfaces, If you're really interested in interfaces you might want to check out Zope3. Even if you don't want to use the "web" parts, the component architecture parts (interfaces, adapters, etc.) might be interesting to you. In a related vein is PEAK (http://peak.telecommunity.com/). It also has some related ideas about interfaces, components, adapters, etc. > accessor functions with different read /write access, ... I don't quite follow here. Are you talking about using a method like "thing.getX" instead of just accessing the attribute directly like "thing.x"? If so, that kind of up-front design isn't necessary in Python. > Unless you have designed the software interactions completely bevorehand > (which never works out) this is the only way to incorporate changes without > refactoring your source all the time. Refactoring *is* the way you handle not being able to "[design] the software interactions completely bevorehand". -- Benji York From skromta at gmail.com Sun Jun 12 05:54:52 2005 From: skromta at gmail.com (Kalle Anke) Date: Sun, 12 Jun 2005 11:54:52 +0200 Subject: How to get/set class attributes in Python Message-ID: <0001HW.BED1D30C00222AB0F0407550@news.gmane.org> I'm coming to Python from other programming languages. I like to hide all attributes of a class and to only provide access to them via methods. Some of these languages allows me to write something similar to this int age( ) { return theAge } void age( x : int ) { theAge = x } (I usually do more than this in the methods). I would like to do something similar in Python, and I've come up with two ways to do it: The first one uses the ability to use a variable number of arguments ... not very nice. The other is better and uses __setattr__ and __getattr__ in this way: class SuperClass: def __setattr__( self, attrname, value ): if attrname == 'somevalue': self.__dict__['something'] = value else: raise AttributeError, attrname def __str__( self ): return str(self.something) class Child( SuperClass ): def __setattr__( self, attrname, value ): if attrname == 'funky': self.__dict__['fun'] = value else: SuperClass.__setattr__( self, attrname, value ) def __str__( self ): return SuperClass.__str__( self ) + ', ' + str(self.fun) Is this the "Pythonic" way of doing it or should I do it in a different way or do I have to use setX/getX (shudder) From maxm at mxm.dk Wed Jun 1 17:31:21 2005 From: maxm at mxm.dk (Max M) Date: Wed, 01 Jun 2005 23:31:21 +0200 Subject: The need to put "self" in every method In-Reply-To: References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: <429e28c4$0$213$edfadb0f@dread12.news.tele.dk> Terry Hancock wrote: > def __add__(a,b): > return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z)) > > or something like that. I still have twinges of guilt about it, > though, and I had to write a long note in the comments, apologizing > and rationalizing a lot. ;-) Assigning self to a could have made it obvious: def __add__(self, b): a = self return Vector((a.x+b.x), (a.y+b.y), (a.z+b.z)) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From kveretennicov at gmail.com Mon Jun 20 19:45:09 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 01:45:09 +0200 Subject: Question about HTMLgen In-Reply-To: References: Message-ID: <4660fe300506201645e17c2c9@mail.gmail.com> On 6/20/05, Sebastian Bassi wrote: > Hello, > > I am using HTMLgen. It is very nice. But I can't make it to > generate an arbitrary command. > For example I want to output this: > > type="image/svg+xml" name="wmap" wmode="transparent"> Works for me... >>> d = HTMLgen.BasicDocument() >>> d.append('') >>> print d - kv From kkylheku at gmail.com Mon Jun 20 23:06:57 2005 From: kkylheku at gmail.com (Kaz Kylheku) Date: 20 Jun 2005 20:06:57 -0700 Subject: references/addrresses in imperative languages In-Reply-To: <11bdd99imhpus06@corp.supernews.com> References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> <11bdd99imhpus06@corp.supernews.com> Message-ID: <1119323217.670985.68250@o13g2000cwo.googlegroups.com> SM Ryan wrote: > # easy way to see this, is to ask yourself: how come in mathematics > # there's no such thing as "addresses/pointers/references". > > The whole point of Goedelisation was to add to name/value references into > number theory. Is that so? That implies that there is some table where you can associate names (or whatever type of locators: call them pointers, whatever) with arbitrary values. But in fact that's not the case. > Thus Goedel was able to add back pointers contrary to the > set hierarchy of the theory of types and reintroduce Russel's paradox. Nope. Goedel didn't add anything, he just revealed what was already there: that you can have statements of number theory, well-formed formulas constructed out of existing operators without any backpointer tricks, which have true interpretations, but are not theorems. Everything in a Goedel's string can be recursively expanded to yield an ordinary formula! There is no infinite regress, no unchased embedded pointer-like things left behind. Self-reference is achieved using two tricks: Goedel numbering, and indirect reference. Godel numbering allows a formula to talk about formulas, by way of embedding their Godel numbers, and translating formula-manipulations into arithmetic manipulations (of interest are finite ones that will nicely unfold into finite formulas). In essence that which used to be ``code'' can be now treated as ``data''', and operations on code (logical derivations) become arithmetic operations on data. Indirect reference is needed because a formula G's Goedel number cannot be inserted into itself directly. If you start with a formula G which has some free variable V, and then produce some new formula by substituting G's Goedel number into it directly for occurences of V, you no longer have G but that other formula. You want whatever comes out to be G, and so the input formula, the one with the free variable, cannot be G, but perhaps a close relative which either talks about G, or whose constituent formulas cleverly end up talking about G after the substitution takes place. Instead of a direct (Goedel number) reference, you can insert into a formula some /procedure/ for making that formula's Goedel number out of another formula's Goedel number and talk about it that way. As an example, instead of saying ``here is a number'' by inserting its literal digits, you can say ``the number that results by applying this formula to this other number''. For instance, instead of writing the number 4 we can write successor(3). or 2 + 2. We explicitly mention some other number, and say how 4 is constructed out of it. Douglas Hofstadter exposition of all this is very good. To allow the formula G to mention its own Goedel number, Douglas Hofstadter uses another formula which he calls U, the ``uncle''. The trick is that: the procedure for making G's Goedel number out of U's number is the arithmetic equivalent of the same procedure that's used to substitute the Goedel number of U for the free variable in U itself. So as U (the formula) is treated by substituting its own Godel number for its one and only free variable, it produces G, and, at the same time, the arithmetic version of that substitution, fully contained inside the U formula itself, turns the now substituted copy of U into G also. U contains the fully expanded ``source code'' for the arithmetic version of the free-variable substitution procedure, and it contains a free variable representing the arithmetic version of the formula on which that algorithm is to be done. As that free variable within U is replaced by the Goedel number U, the overall formula becomes G, and the embedded free-variable-replacement procedure is instantiated concretely over U's Goedel number, so it becomes a constant, unparameterized calculation that produces G's Goedel number. Voila, G contains a procedure that computes the arithmetic object (Goedel number) that represents G's ``source code'' (the symbolic formula), out of the embedded number representing U's source code. Using that giant formula, G can assert things about itself, like ``I am not a theorem'' (i.e. ``there exists no integer representing the Goedel numbers of a list of true statements that represent a derivation deducing myself as the conclusion''). There are no name references or pointers or anything. All the functions are primitive recursive, and so can be expanded into finite-length formulas which contain only numbers and operators and variables---dummy ones that are bound to existential quantifiers, not to concrete values some external name/value table. From diesch at spamfence.net Wed Jun 8 14:14:48 2005 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 8 Jun 2005 20:14:48 +0200 Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> Message-ID: <20050608181448.2091.4.NOFFLE@dieschf.news.arcor.de> Rahul wrote: > Well is there an open source computer algebra system written in python > or at least having a python interface? > I know of 2 efforts: pythonica and pyginac...are there any others? Probably this is usable for you (I never used any of them): Package: mascyma Description: A user-friendly frontend for MAXIMA Mascyma is (trying to be) a user-friendly graphical frontend for the Computer Algebra System GNU MAXIMA. It is written in Python and provides two GUIs, one of which based on PyGTK, the other based on wxPython. Package: maxima Description: A fairly complete computer algebra system-- base system This system MAXIMA is a COMMON LISP implementation due to William F. Schelter, and is based on the original implementation of Macsyma at MIT, as distributed by the Department of Energy. I now have permission from DOE to make derivative copies, and in particular to distribute it under the GNU public license. . This package contains the main executables and base system files. Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From python at rcn.com Tue Jun 7 02:30:02 2005 From: python at rcn.com (Raymond Hettinger) Date: 6 Jun 2005 23:30:02 -0700 Subject: split up a list by condition? References: <3gjpk0FcrnknU1@individual.net> Message-ID: <1118125802.096110.167820@g49g2000cwa.googlegroups.com> >> while writing my solution for "The python way?", I came across this fragment: >> vees = [c for c in wlist[::-1] if c in vocals] >> cons = [c for c in wlist[::-1] if c not in vocals] >> >> So I think: Have I overlooked a function which splits up a sequence >> into two, based on a condition Trying to compress too much into one line is not "the python way" ;-) vees, cons = [], [] for c in reversed(wlist): if c in vocals: vees.append(c) else: cons.append(c) From bokr at oz.net Sun Jun 26 16:57:22 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 20:57:22 GMT Subject: Controlling assignation References: Message-ID: <42bf1570.277973574@news.oz.net> On Mon, 13 Jun 2005 15:52:14 +0200, =?ISO-8859-1?Q?Xavier_D=E9coret?= wrote: <...OTT [OT Title] posted text snipped.../> assignation != assignment ;-) Regards, Bengt Richter From peter at engcorp.com Thu Jun 9 07:52:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 07:52:07 -0400 Subject: help with sending mail in Program In-Reply-To: <42a814a4_1@newspeer2.tds.net> References: <42a56e49_3@newspeer2.tds.net> <42a814a4_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Tim Roberts wrote: >> Not exactly like this, you didn't. The list of destination addresses in >> SMTP.sendmail must be a sequence, not a string: > > Yes, exactly like that. This is a working module, the only thing I > changed to post it was the email address and the name of the SMTP > server. SMTP.sendmail() allows a single string as a to address. > > From the comment in smtplib.py: > - to_addrs : A list of addresses to send this mail to. A > bare > string will be treated as a list with 1 > address. Interesting... I suspect this "fix" was made in one of the more recent Python versions, since I know that in the past (at least with 1.5.2) a string would be treated as a sequence, resulting in many one-character destination addresses being used. :-( (And when I say "I know" this, I mean "I vaguely remember, and I wouldn't argue against evidence that I'm wrong". ;-) ) -Peter From kent37 at tds.net Fri Jun 3 06:03:29 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Jun 2005 06:03:29 -0400 Subject: optparse.py: FutureWarning error In-Reply-To: References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> Message-ID: <42a02aba$1_3@newspeer2.tds.net> Terry Reedy wrote: > "kosuke" wrote in message > news:1117765604.103092.154190 at g47g2000cwa.googlegroups.com... > >>man python --- >> >>COMMAND LINE OPTIONS > > > This should REALLY be on the doc page of the Python site. Hear, hear! I never even knew this existed! Where should it go in the docs? In the Language Reference or the Tutorial or...? Kent From d at e.f Fri Jun 24 12:34:55 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 11:34:55 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: Roy Smith wrote: > Tom Anderson wrote: > >>The one thing i really do miss is method overloading by parameter >>type. I used this all the time in java > > > You do things like that in type-bondage languages like Java and C++ > because you have to. Can you give an example of where you miss it in > Python? Well it's coming to a future Python version, so apparently there are many who can use it: http://wiki.python.org/moin/Python3.0Suggestions#head-7df9d7035174644fdae024ed4a5ea0960a003ef5 I don't know if you'll have method overloading, but there will be type checking. It's not actually compile-time "static typing" though. The type checking still happens at run-time similar to your isinstance example, making code run slightly slower than a normal python method: "Type checking is going to slow down your code." -GVR 2005 keynote, http://www.sauria.com/%7Etwl/conferences/pycon2005/20050324/The%20State%20of%20Python.html From tbr at nospam.nos Mon Jun 6 08:54:32 2005 From: tbr at nospam.nos (TechBookReport) Date: Mon, 06 Jun 2005 13:54:32 +0100 Subject: Review of 'Python Cookbook' Message-ID: TechBookReport (http://www.techbookreport.com) has just published a review of the Python Cookbook. This is an extract from the full review: We're big fans of cookbooks here at TechBookReport, whether its Java, XSLT or Linux, they're a great way of pulling together lots of useful snippets of code and technique in one place. For the beginner they provide instant advice, usable code and a way into new areas. They're also a great way to find out about coding styles, idioms, common workarounds and how to get the most out of your language (or operating system, development environment or application?). Given all of that then it should be no surprise that we love this second edition of the Python Cookbook. There's no doubt about it, this is an indispensable resource to have around. What's more, this latest edition has been enhanced and updated for Python 2.4, and now features more than 330 recipes across 20 chapters. Note that the recipes only cover Python 2.3 and 2.4, for older versions readers should look for the first edition of the book. As with the rest of O'Reilly's cookbooks, this one has a standard format for each recipe: state the problem, present a solution, discuss the solution and provide cross-references and pointers to further material. It's a good format, and allows each recipe to pretty much stand alone, even if there are pointers to other recipes in the 'see also' section. This makes the recipes a useful place to dip into for ideas and examples when hacking your own code. As with a real cookbook this is one that has a practical focus and belongs by your side when cooking not on some shelf gathering dust. Unlike most of the other books in the cookbook series, this one is not the product of one or two authors but very much a community effort, thanks in large part to the involvement of ActiveState. While the three editors deserve credit for the good job they've done putting it all together, it's down to the Python community for creating these recipes and providing the feedback to hone and improve them. Read the rest of the review here: http://www.techbookreport.com/tbr0163.html From jzgoda at gazeta.usun.pl Wed Jun 8 15:50:03 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Wed, 08 Jun 2005 21:50:03 +0200 Subject: __init__.py in packages In-Reply-To: References: Message-ID: Gary Wilson Jr napisa?(a): > What is intended use for __init__.py files? > Well, I found this: http://www.python.org/doc/essays/packages.html >>From what I can gather it is for initialization of the package when doing an > import, but I would really like to see an example or situation that makes good > use of the __init__.py file. > > Looking at the distutils __init__.py file, it only defines things like > __version__. However, looking at the logging __init__.py file, it is a > 1196-line monster with functions and classes defined throughout. > > What is the RightThing? I don't know The Right Thing, I just use __init__.py as namespace shortcut -- everything you define there (functions, classes, names), will be available at module level, not deeper. > Should I only define things in __init__.py that need to be defined when > importing a subpackage and/or module of package foo? > > Is it ok for me to define classes in foo/__init__.py? > Whereby I could do something like: > > from foo import MyClass > > Or is is better if I were to put these classes and/or functions in foo/core.py? > Whereby I would do something like: > > from foo.core import MyClass It's mostly a matter of taste. And logic. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From theller at python.net Fri Jun 3 13:50:54 2005 From: theller at python.net (Thomas Heller) Date: Fri, 03 Jun 2005 19:50:54 +0200 Subject: couple of new python articles on onlamp References: Message-ID: Jeremy Jones writes: > I've got a couple of new articles on ONLamp: > > Writing Google Desktop Search Plugins > http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html > > and > > Python Standard Logging > http://www.onlamp.com/pub/a/python/2005/06/02/logging.html > > > Comments, criticisms, flames all welcome. I've read the logging article, and I like it. Good work. Thanks, Thomas From guettli at thomas-guettler.de Fri Jun 24 06:56:33 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 24 Jun 2005 12:56:33 +0200 Subject: Help wanted in piping in Windows References: Message-ID: Am Fri, 24 Jun 2005 01:28:38 +0530 schrieb Apple Grew: > I want to develope a Winboard like application which will support > Winboard protocol. For that I require to know how to handle piping in > Python. I seperated out module popen2, but when I use > fileObject.readline() then it halts the program if the sub-process is > waiting for user input; will executing the readline() part in a seperate > thread be helpful? My target platform is Windows. > > Links to helpful web resources and sample Python codes will be highly > appreciated. Piping on Windows is not much different than on Unix. You should only have *one* open file descriptor. If the subprocess needs to read from stdin, then stdout and stderr should be redirected to a file. Otherwise you can get deadlocks, because the buffers have a finit size. AFAIK ">file" and "2>file" does work on windows. On Unix you can the module "select". HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From mtammerman at gmail.com Wed Jun 1 08:02:46 2005 From: mtammerman at gmail.com (Mike Tammerman) Date: 1 Jun 2005 05:02:46 -0700 Subject: Function Serialization Message-ID: <1117627366.569543.227090@o13g2000cwo.googlegroups.com> I want to serialize a function using its pointer. For example >>> s = """ ... def square(number): ... return number**2 ... """ >>> functions = {} >>> exec s in functions >>> f = functions['square'] >>> f Then, 1. Serialize f, 2. Store it into a file a db. One day later, 3. Retrieve from file or db, 4. Unserialize it 5. Use as it is a normal function, maybe I would set it to an object with setattr Any help will be very useful. Mike From scrimp212 at yahoo.com Fri Jun 10 16:49:33 2005 From: scrimp212 at yahoo.com (scrimp) Date: 10 Jun 2005 13:49:33 -0700 Subject: Using PAMIE to upload and download files...is it possible? In-Reply-To: <1118256512.379934.292780@z14g2000cwz.googlegroups.com> References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> <1118256512.379934.292780@z14g2000cwz.googlegroups.com> Message-ID: <1118436573.931101.78280@g44g2000cwa.googlegroups.com> This is your code I used...I didnt change anything from it def useSaveASDialog(filePath=None): from watsup.winGuiAuto import findTopWindow,findControl,setEditText from time import sleep rVal = None handle = winGuiAuto.findTopWindow("Save As") sButton = winGuiAuto.findControl(handle,"&Save","Button") sEdit = winGuiAuto.findControl(handle, None, "Edit") if filePath != None: winGuiAuto.setEditText(sEdit, filePath) rVal = winGuiAuto.getEditText(sEdit) winGuiAuto.clickButton(sButton) return rVal So, in the interactive window I make an instantiation of it and this is what I get r = useSaveASDialog("C:\Downloads") Traceback (most recent call last): File "", line 1, in ? File "C:\My Documents\python scripts\mytest1.py", line 6, in useSaveASDialog handle = winGuiAuto.findTopWindow("Save As") File "C:\PYTHON23\lib\site-packages\watsup\winGuiAuto.py", line 158, in findTopWindow raise WinGuiAutoError("No top level window found for wantedText=" + WinGuiAutoError: No top level window found for wantedText='Save As', wantedClass=None, selectionFunction=None, maxWait=1, retryInterval=0.1 So, I fire up IE manually and find a link to click on that brings up the download window and the first window I run into is the File Download window with an Open, Save, Cancel, and More Info buttons. I click on Save and that brings up the Save As window, so from there I go back to PythonIDE and do the same command in the window and it PythonIDE crashes. The weird thing is though it puts the path inside the Filename text box. Just the path without the file. Ill be testing this more next week, so ill get back with you then. Thanks for the start though!! --Barry From dalke at dalkescientific.com Fri Jun 3 01:34:54 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 03 Jun 2005 05:34:54 GMT Subject: provide 3rd party lib or not... philosophical check References: Message-ID: Maurice LING wrote: > Just a philosophical check here. When a program is distributed, is it > more appropriate to provide as much of the required 3rd party libraries, > like SOAPpy, PLY etc etc, in the distribution itself or it is the > installer's onus to get that part done? Depends on who you are delivering the software to. I've made distributions that include everything. Often for people who don't want to install other software. I've made distributions that assume several other packages were already installed. Often for people who are Python developers or who were okay with simple doing installation. Andrew dalke at dalkescientific.com From finite.automaton at gmail.com Tue Jun 28 17:00:47 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 28 Jun 2005 14:00:47 -0700 Subject: Creating Python wrapper for DLL References: <1119990428.163115.152440@g49g2000cwa.googlegroups.com> Message-ID: <1119992447.220001.258210@g49g2000cwa.googlegroups.com> ctypes! http://starship.python.net/crew/theller/ctypes/ From gene.tani at gmail.com Tue Jun 7 01:20:17 2005 From: gene.tani at gmail.com (gene tani) Date: 6 Jun 2005 22:20:17 -0700 Subject: split up a list by condition? In-Reply-To: <3gjpk0FcrnknU1@individual.net> References: <3gjpk0FcrnknU1@individual.net> Message-ID: <1118121617.529579.256620@g47g2000cwa.googlegroups.com> Sounds like itertools.groupby() is what you're looking for, just sort your sequence on the grouping func that you will pass as 2nd arg to groupby(), before you pass the sequence to groupby() http://www.python.org/doc/2.4/whatsnew/node13.html http://www.python.org/dev/doc/devel/lib/itertools-functions.html From roccomoretti at hotpop.com Mon Jun 20 15:13:12 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 20 Jun 2005 14:13:12 -0500 Subject: What is different with Python ? In-Reply-To: References: <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> <3hg08rFh2tr3U1@individual.net> <1119015358.155954.92430@g47g2000cwa.googlegroups.com> <1119067837.776544.198870@g49g2000cwa.googlegroups.com> Message-ID: Andrea Griffini wrote: > Indeed when talking about if learning "C" can hinder > or help learning "C++" I remember thinking that to > learn "C++" *superficially* learning "C" first is > surely pointless or can even hinder. > But to learn "C++" deeply (with all its quirks) I > think that learning "C" first helps. I think you are mistakingly bringing order into the picture, when extent is more likely the case. If you want to master C++, I think that most would agree you need to understand C. But there are many who would disagree that the path to C++ must *start* at C. (In fact, many people argue that a lot of bad C++ is due to people programming C in C++.) Instead they would argue that you should start by learning C++ "superficially", then learn C, and re-evaluate you C++ practices in light of the lessons learned from C. The example I'll pull out is natural languages - I understood the grammar & construction of my native tounge *much* better after learning a foreign language. From people I've talked to, this is a common occurance. But there would be few people who would advocate that one should learn a foreign language before learning one's native tounge. From twic at urchin.earth.li Wed Jun 8 19:24:35 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 9 Jun 2005 00:24:35 +0100 Subject: Getting a DOM element's children by type (STUPID) Message-ID: Hi, If i get myself a DOM tree using xml.dom.minidom (or full-fat xml.dom, i don't mind), is there an easy way to ask a element for its child elements of a particular type? By 'type' i mean 'having a certain tag'. This strikes me as a rather common thing to want to do, but i can't see a method for it; it seems i have to go through elem.childNodes myself, fishing out the ones i want. Or rather, to write exactly the same three-line helper function that millions of other people must have written to do this. Am i missing something blindingly obvious? I'm happy to RTFM here, but would appreciate a pointer to the appropriate such manual, since the docs i have to hand are somewhat unenlightening. Thanks, tom -- Just because Congresspeople do it, doesn't mean it's right. -- Ian York From maxm at mxm.dk Wed Jun 8 09:32:09 2005 From: maxm at mxm.dk (Max M) Date: Wed, 08 Jun 2005 15:32:09 +0200 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> Message-ID: <42a6f318$0$204$edfadb0f@dread12.news.tele.dk> ajikoe at gmail.com wrote: > Hello, > > I use windows notepad editor to write text. > > For example I write (in d:\myfile.txt): > Helo > World > > If I open it with python: > FName = open(d:\myfile.txt,'r') > h = FName.readlines() > print h > > I get h : ['Helo\n', 'World'] > > I thought notepad use \r\n to to end the line. > > What's wrong with it? Python tries to be clever. Open it in binary mode to avoid it: FName = open(d:\myfile.txt,'rb') -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From jepler at unpythonic.net Wed Jun 22 19:57:20 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 22 Jun 2005 18:57:20 -0500 Subject: Is this a bug? I don't know where to start In-Reply-To: <20050622230524.82193.qmail@web52809.mail.yahoo.com> References: <20050622230524.82193.qmail@web52809.mail.yahoo.com> Message-ID: <20050622235717.GA2874@unpythonic.net> Your list "targets" contains some values twice. >>> targets=[97,101,139,41,37,31,29,89,23,19,8,13,131,19,73,97,19,139,79,67,61,17,113,127] >>> for t in set(targets): ... if targets.count(t) > 1: print t ... 97 139 19 It looks like the "duplicated" items in the output contain one of the duplicated items from the input. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From philippe at philippecmartin.com Mon Jun 20 12:14:38 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 16:14:38 GMT Subject: Python choice of database References: Message-ID: Thanks, I'm looking at KirbyBase also but wonder if it can handle bitmaps (I could always pickle it first I guess). Regards, Philippe John Abel wrote: > Philippe C. Martin wrote: > >>Thank you all for your answers. >> >>A pure Python would have beenmy first choice. yet I now feel I should >>spend some time looking at PySQLite (I like the fact it's pre-compiled for >>Windows). >> >>Thanks. >> >>Philippe >> >> >> >>Philippe C. Martin wrote: >> >> >> >>>Hi, >>> >>>I am looking for a stand-alone (not client/server) database solution for >>>Python. >>> >>>1) speed is not an issue >>>2) I wish to store less than 5000 records >>>3) each record should not be larger than 16K >>> >>> >>>As I start with Python objects, I thought of using shelve, but looking at >>>the restrictions (record size + potential collisions) I feel I should >>>study my options a bit further before I get started. >>> >>> >>>Regards, >>> >>>Philippe >>> >>> >> >> >> > Out of the suggestions SnakeSQL and KirbyBase are pure python. Gadfly > is sorta pure, in that it will work without the compiled kjbuckets lib. > > J From mandus at gmail.com Wed Jun 29 05:46:15 2005 From: mandus at gmail.com (Mandus) Date: Wed, 29 Jun 2005 09:46:15 +0000 (UTC) Subject: map vs. list-comprehension Message-ID: Hi there, inspired by a recent thread where the end of reduce/map/lambda in Python was discussed, I looked over some of my maps, and tried to convert them to list-comprehensions. This one I am not sure how to conver: Given three tuples of length n, b,i and d, I now do: map(lambda bb,ii,dd: bb+ii*dd,b,i,d) which gives a list of length n. Anyone have an idea what the equivalent list comprehension will be? take care, -- Mandus - the only mandus around. From enleverlesO.OmcO at OmclaveauO.com Sat Jun 25 10:41:22 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Sat, 25 Jun 2005 16:41:22 +0200 Subject: Excellent Site for Developers References: Message-ID: <42bd6dbc$0$1235$8fcfb975@news.wanadoo.fr> rather... super troll From spam.csubich+block at block.subich.spam.com Sun Jun 12 21:25:42 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Sun, 12 Jun 2005 21:25:42 -0400 Subject: Following the white rabbit (was "The Python Way") In-Reply-To: <3h3rerFf41vdU1@individual.net> References: <3h3rerFf41vdU1@individual.net> Message-ID: Claudio Grondi wrote: >> Just follow the white rabbit. > > > This triggers in me the temptation to start > a thread asking: > > What (in your opinion) can a good programmer > learn from watching all of the Matrix movies? > Which part, one, two or three deals most with > the philosophy of programming? IMO, in my opinion almost certainly the first. The first can be summed up in the words, "free your mind." From my very limited experience, that captures 90% of the Zen right there. The second... uh... "dancing rave orgies are fun?" Doesn't quite work. The third is entirely inappropriate, since it's rather hard to program in Python after one has gouged one's eyes out with a rusty spoon. From Gerald.Klix at klix.ch Fri Jun 17 05:06:35 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Fri, 17 Jun 2005 11:06:35 +0200 Subject: strxfrm works with unicode string ? In-Reply-To: <1118997804.678723.170070@g44g2000cwa.googlegroups.com> References: <1118997804.678723.170070@g44g2000cwa.googlegroups.com> Message-ID: <42B2929B.2060800@klix.ch> How about: import locale s=u'\u00e9' print s locale.setlocale(locale.LC_ALL, '') locale.strxfrm( s.encode( "latin-1" ) ) --- HTH, Gerald nicolas.riesch at genevoise.ch schrieb: > I am trying to use strxfm with unicode strings, but it does not work. > This is what I did: > > >>>>import locale >>>>s=u'\u00e9' >>>>print s > > ? > >>>>locale.setlocale(locale.LC_ALL, '') > > 'French_Switzerland.1252' > >>>>locale.strxfrm(s) > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > locale.strxfrm(s) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in > position 0: ordinal not in range(128) > > > Someone sees what I did wrong ? > -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From kay.schluehr at gmx.net Fri Jun 10 11:33:29 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Jun 2005 08:33:29 -0700 Subject: Basic questions about packages/modules. References: <2fdabf19.0506100638.119d604a@posting.google.com> Message-ID: <1118417609.458087.28400@o13g2000cwo.googlegroups.com> Negroup schrieb: > Hi, first of all sorry for boring you with a such simple request. I'm > using Python since few days, and I like it even if I'm not yet in > confidence. I'd like to organize my programs in hierarchical > structures, thus I thought that packages could be the solution, > however I have some difficulties understanding their utilization (even > after reading chapter 6 of the tutorial, about modules). > > Now an example (silly) to clarify my doubts: > > This is the structure: > main.py > importers/ > __init__.py (empty) > importer1.py > config/ > __init__.py (empty) > parameters.py > > main.py > ======= > from importers import importer1 > print importer1.display() > > importers/importer1.py > ====================== > from config import parameters > def display(): > return '-' * parameters.counter > > config/parameters.py > ==================== > counter = 5 > > > All works fine when I run "python main.py", while I get an error > trying to run "python importers/importer1.py": > > Traceback (most recent call last): > File "importers/importer1.py", line 1, in ? > from config import parameters > ImportError: No module named config > > Can you explain why does that happen? It prevents me to test > importer1.py alone. > > TIA, > negroup mainpackage/ main.py importers/ __init__.py (empty) importer1.py config/ __init__.py (empty) parameters.py If this is the package structure and you run 'python main.py' from mainpackage the config package is already in the search path. Therefore importing config in subsequent modules succeeds. If you run importer1.py on the level of importers config may not be in the PYTHONPATH and the import fails. Solution: reference config in the import statement so that the package can be found. from mainpackage.config import parameters should be suffient if mainpackage is in the PYTHONPATH. But note that you have to be consistent with your import statements because the module will be cached in sys. modules using it's import path as key. Doing both from mainpackage.config import parameters and from config import parameters in different modules leads to reimports and different modules. This may cause trouble if you compare objects using class information because the id's of the classes are different. Kay From phm4 at kent.ac.uk Thu Jun 30 06:32:27 2005 From: phm4 at kent.ac.uk (Philipp H. Mohr) Date: Thu, 30 Jun 2005 11:32:27 +0100 (BST) Subject: Store multiple dictionaries in a file Message-ID: Hello, I would like to store multiple dictionaries in a file, if possible one per line. My code currently produces a new dictionary every iteration and passes it on to another peace of code. In order to be able to re-run some experiments at a later date I would like to store every dictionary in the same file. I looked at pickel, but that seems to require a whole file for each dictionary. It would be great if some one could tell me how to do that. Thank you, Phil From peter at engcorp.com Wed Jun 8 18:52:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Jun 2005 18:52:06 -0400 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> <1118264973.349272.173370@z14g2000cwz.googlegroups.com> Message-ID: Robert Kern wrote: > The problem arises that, in the presence of rich comparisons, (a == b) > is not always a boolean value, while (a is b) is always a boolean value. But that still doesn't mean that in a case where a == b (via __eq__) returns a non-boolean, __ne__ would not be defined as well. In other words, there's _nothing_ preventing this "fix" from being made to provide saner behaviour in the most common case (which happens to pose the greatest risk of inadvertent mistakes for those who aren't aware of the requirement to define both) while still allowing the cases that need unusual behaviour to get it by (as they already surely do!) defining both __ne__ and __eq__. -Peter From root at localhost.localdomain Wed Jun 15 02:37:51 2005 From: root at localhost.localdomain (root) Date: Wed, 15 Jun 2005 18:37:51 +1200 Subject: New WYSIWYG Python IDE in the works Message-ID: Hello all I am currently developing a new WYSIWYG RAD tool for python. There are screenshots and a small video demo on the site. Please visit at http://www.geocities.com/visualfltk Cheers JMan From mwm at idiom.com Tue Jun 21 23:15:17 2005 From: mwm at idiom.com (Mike Meyer) Date: 21 Jun 2005 20:15:17 -0700 Subject: extreme newbie References: <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> <42B48FDE.4010700@lexicon.net> <0s7bb111j9iimeicputkooj4a8gf4l2dji@4a <11bcfl3icgm5836@corp.supernews.com> Message-ID: <5j4qbrrsje.fsf@idiom.com> Grant Edwards writes: > Under Unix it's not all that hard to accidentally create files > like that. Sometimes you have to resort to blasting them away > by i-node number, or by moving the files you want to keep and > then nuking the directory. A standard practice on our early Unix system at the university was to issue the command '% touch "$HOME/*"; clear' on any terminals found unattended. But we were a nasty bunch. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From sxanth at ceid.upatras.gr Thu Jun 23 10:40:28 2005 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Thu, 23 Jun 2005 17:40:28 +0300 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <42BAC9DC.3050106@ceid.upatras.gr> Michael Hoffman wrote: > Stelios Xanthakis wrote: > >> Magnus Lycka wrote: > > > > >>> Right. Silly me. Maybe in some future Python version, True and False >>> will be constants, like None is since Python 2.4. >> >> >> Actually, there is support in marshal to write True and False objects so >> I don't understand why this isn't in 2.4 > > > Because it would break existing code. Yes. Code that has variables named 'True' and 'False'. Stelios From see at sig.for.address.edu Sat Jun 18 01:36:08 2005 From: see at sig.for.address.edu (Doug Schwarz) Date: Sat, 18 Jun 2005 05:36:08 GMT Subject: Regex for repeated character? References: <5J9se.136$Q75.39412@newshog.newsread.com> Message-ID: In article <5J9se.136$Q75.39412 at newshog.newsread.com>, Leif K-Brooks wrote: > How do I make a regular expression which will match the same character > repeated one or more times, instead of matching repetitions of any > (possibly non-same) characters like ".+" does? In other words, I want a > pattern like this: > > >>> re.findall(".+", "foo") # not what I want > ['foo'] > >>> re.findall("something", "foo") # what I want > ['f', 'oo'] How's this? >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbcccddddcccbba')] ['a', 'bb', 'ccc', 'dddd', 'ccc', 'bb', 'a'] -- Doug Schwarz dmschwarz&urgrad,rochester,edu Make obvious changes to get real email address. From http Wed Jun 1 23:20:30 2005 From: http (Paul Rubin) Date: 01 Jun 2005 20:20:30 -0700 Subject: dictionaries and threads References: Message-ID: <7x3bs1h2bl.fsf@ruckus.brouhaha.com> Gary Robinson writes: > As far as I can tell, if the Python bytecodes that cause dictionary > modifications are atomic, then there should be no problem. But I don't > know that they are because I haven't looked at the bytecodes. Depending on behavior like that is asking for trouble. If it doesn't kill your app's performance, put some kind of locks around the dictionary and/or direct all access to the directory through a single thread. The favorite Python idiom for that seems to be the Queue module; you'd set up a work queue and a result queue to communicate with the thread controlling the dictionary. If your app absolutely can't stand that, look to a more fundamental solution, maybe something like POSH (poshmodule.sf.net). From jjl at pobox.com Fri Jun 3 14:46:11 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jun 2005 18:46:11 +0000 Subject: scripting browsers from Python References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> <87r7fl7lwf.fsf@pobox.com> Message-ID: <87zmu72s98.fsf@pobox.com> Olivier Favre-Simon writes: [...] > > I'd like to have a reimplementation of ClientForm on top of something > > like BeautifulSoup... > > > > > > John > > When taken separately, either ClientForm, HTMLParser or SGMLParser work > well. > > But it would be cool that competent people in the HTML parsing domain join > up, and define a base parser interface, the same way smart guys did with > WSGI for webservers. Perhaps. Given a mythical fixed quantity of volunteer coding effort I could assign to any HTML parsing project, I'd really prefer that somebody separated out the HTML parsing, tree building and DOM code from Mozilla and/or Konqueror. > So libs like ClientForm would not raise say an AttributeError if some > custom parser class does not implement a given attribute. > > Adding an otherwise unused attribute to a parser just in case one day it > will interop with ClientForm sounds silly. And what if ClientForm changes > its attributes, etc. [...] I'm sorry, I didn't really follow that at all. What I hoped to get from implementing the ClientForm interface on top of something like BeautifulSoup was actually two things: 1. Better parsing 2. Access to a nice, and comprehensive, object model that lets you do things with non-form elements, and the ability to move back and forth between ClientForm and BeautifulSoup objects. I already did this for the HTML DOM with DOMForm (unsupported), but for various reasons the implementation is horrid, and since I no longer intend to put in the effort to support JavaScript, I'd prefer a nicer tree API than the DOM. John From nothingcanfulfill at gmail.com Thu Jun 30 22:26:40 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 30 Jun 2005 19:26:40 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <1120184800.499445.240250@f14g2000cwb.googlegroups.com> Eh, just figured it'd be worth noting...map, filter, and reduce should be possible with the extended list syntaxes. Well, filter I know is, but hte others /should/ be possible. filter(lambda: <>, <>) [some_var for some_var in <> if <>] Honestly, though, I hope they don't drop the map functions and such. That's one of the stronger functions of the language (IMO). -Wes From andreas at kostyrka.org Thu Jun 2 11:06:56 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 2 Jun 2005 17:06:56 +0200 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> Message-ID: <20050602150655.GA30964@heaven.kostyrka.org> On Thu, Jun 02, 2005 at 01:57:25AM -0700, Robert Kern wrote: > And for thoroughness, allow me to add "even if they have no intention or > desire to profit monetarily." I can't explain exactly why this is the > case, but it seems to be true in the overwhelming majority of cases. > Academic projects with non-commercial clauses languish in obscurity > while academic Open Source projects thrive. The contributors to the Open Well, it's easily explained. (Well at least my motivation in this case) I do not touch things that I cannot use "generally" and being a "commercial" IT consultant this basically means: *) opensource is better than commercial payware. (because "for free" (as in beer) is usable in more contexts) *) GPL is acceptable for much stuff, because I can install GPL'ed stuff for a customer. *) GPL is not acceptable for "library" stuff, because as a software developer I'm sometimes forced to do "closed" stuff. (Yep, even nowadays there are place where it's basically a legal requirement.) Implications: *) qt is a bordercase: GPL for free, or commercial for pay. Not perfect but good enough. *) A number of O-R mappers for Python are of no relevance to me, because they are GPL. O-R mappers are development libraries. The idea is that I'm mostly not interested in learning tools that are not of general use. So basically, stuff not meeting this criteria, is only interesting if it's unique: *) commercial stuff is only interesting if there is no competing open-source project. *) GPL'ed "building blocks" are only interesting when there is no competing LGPL version. Example: OCR on Linux/Unix. There are no perfect solutions there so a GPL'ed solution might be ok. (Especially because one can use OCR without linking with a lib *grin*) Andreas From tundra at tundraware.com Wed Jun 22 18:57:09 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 22 Jun 2005 18:57:09 EDT Subject: Looking For Geodetic Python Software Message-ID: <447po2-iqt.ln1@eskimo.tundraware.com> Is anyone aware of freely available Python modules that can do any of the following tasks: 1) Given the latitude/longitude of two locations, compute the distance between them. "Distance" in this case would be either the straight-line flying distance, or the actual over-ground distance that accounts for the earth's curvature. 2) Given n latitude/longitude coordinates, compute the "geocenter". That is, return the lat/long of the location that is most "central" to all n initial coordinates. 3) Given n lat/long coordinates, compute a Kruskal-type spanning tree. 4) Given n lat/long coordinates, compute an optimal (shortest or longest) visitation path that reaches each node exactly once. Better still would be something that had "pluggable" heuristic engines so we could try different approaches like greedy, shortest-path, hill climbing, and so forth. It would be even nicer if one could also simulate different routing schemes (Monte Carlo?). In effect, I'm looking for something that mates traditional graph traversal heuristics with operations research tools working on a geodetic coordinate system. This is *waaaaay* outside my field of expertise so I'm hoping someone has taken the pain of it for dummies like me ;) TIA, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From dalke at dalkescientific.com Thu Jun 2 23:32:08 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 03 Jun 2005 03:32:08 GMT Subject: Two questions References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> <3g9vflFbd3puU1@individual.net> Message-ID: Greg Ewing wrote: > Hmmm... if these are GPL weapons, if you want to fire > them at anyone you'll *have* to make them available to > all other countries as well... not good for > non-proliferation... I think the source code only needs to be sent to the country which receive the weapons. Include a DVD with the warhead (in a usable form for further development) and the GPL should be satisfied. Andrew dalke at dalkescientific.com From miki.tebeka at zoran.com Thu Jun 30 07:51:53 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Thu, 30 Jun 2005 14:51:53 +0300 Subject: POP3 and "seen" flag Message-ID: <20050630115152.GS2620@zoran.com> Hello All, Is there a way to know in a POP session of a message was seen (old) or not (new)? Thanks. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 193 bytes Desc: not available URL: From r.s at ZZmindspring.com Mon Jun 20 20:27:04 2005 From: r.s at ZZmindspring.com (r.e.s.) Date: Tue, 21 Jun 2005 00:27:04 GMT Subject: sudoku dictionary attack References: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> <1119287197.993599.160240@g47g2000cwa.googlegroups.com> Message-ID: "Oliver Albrecht" <55028344773 at t-online.de> wrote ... > Has some one an sodoku-task-generator? Sudoku puzzles can be generated (and solved) online at http://act365.com/sudoku/ From simon.brunning at gmail.com Wed Jun 8 07:55:11 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 8 Jun 2005 12:55:11 +0100 Subject: test In-Reply-To: References: Message-ID: <8c7f10c605060804556934c665@mail.gmail.com> On 6/8/05, Nader Emami wrote: > L.S., > > I would like to learn how does work the "unit test" concept in Python. I > have try the 'romantest.py' of the "Dive in Python" book and I get the > next problem: > > Traceback (most recent call last): > File "romantest.py", line 153, in ? > unittest.main() > File "/usr/lib/python2.3/unittest.py", line 721, in __init__ > self.runTests() > File "/usr/lib/python2.3/unittest.py", line 758, in runTests > result = self.testRunner.run(self.test) > File "/usr/lib/python2.3/unittest.py", line 657, in run > startTime = time.time() > AttributeError: 'module' object has no attribute 'time' > > I can't understand it! Would somebody tell me how I can solve this > problem. Thanks, Wild guess - have you got a module called time.py of your own somewhere around? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From trentm at ActiveState.com Fri Jun 17 22:27:36 2005 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 17 Jun 2005 19:27:36 -0700 Subject: extreme newbie In-Reply-To: <7xr7f0o4ka.fsf@ruckus.brouhaha.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <7xr7f0o4ka.fsf@ruckus.brouhaha.com> Message-ID: <20050618022736.GA2946@ActiveState.com> [Paul Rubin wrote] > Try "Dive Into Python", www.diveintopython.org (site is very slow > right now, try later). Note that "Dive Into Python" is included in the ActivePython Windows compiled help file so you can read and search it locally: http://ftp.activestate.com/ActivePython/etc/ActivePython24.chm Cheers, Trent -- Trent Mick TrentM at ActiveState.com From mwm at mired.org Tue Jun 28 18:51:46 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 28 Jun 2005 18:51:46 -0400 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: <863br2nlh9.fsf@bhuda.mired.org> Tom Anderson writes: > On Fri, 24 Jun 2005, Roy Smith wrote: >> Tom Anderson wrote: >>> The one thing i really do miss is method overloading by parameter >>> type. I used this all the time in java >> You do things like that in type-bondage languages > I love that expression. I think it started out as 'bondage and > discipline languages', which is even better. I'm going to start > referring to python as a 'sluttily typed' language. Since the user is the one bound with B&D languages, they are clearly tops. Which makes Python a bottom. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From kent37 at tds.net Fri Jun 24 06:46:37 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 06:46:37 -0400 Subject: formatted xml output from ElementTree inconsistency In-Reply-To: References: Message-ID: <42bbe3e9$1_1@newspeer2.tds.net> Matthew Thorley wrote: > Greetings, perhaps someone can explain this. I get to different styles > of formatting for xmla and xmlb when I do the following: > > Is that because the some_file.xml is already nicely formatted? I thought > that the formatting was ignored when creating new elements. ElementTree is preserving the whitespace of the original. > > Is their a function to 'pretty print' an element? AFAIK this is not supported in ElementTree. I hacked my own by modifying ElementTree._write(); it wasn't too hard to make a version that suited my purposes. Kent From bronger at physik.rwth-aachen.de Fri Jun 3 10:38:53 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 03 Jun 2005 16:38:53 +0200 Subject: Removing a warnings filter? Message-ID: <87ekbj8pz6.fsf@wilson.rwth-aachen.de> Hall?chen! When I add a warning filter with warnings.filterwarnings, how can I get rid of it? I've read about resetwarnings(), but it removes all filters, even those that I didn't install in a certain function. In particular, I want to transform one special form of warning in an exception to keep track of it more easily. However, before leaving my function I want to restore the old status. How can this be achieved? Thank you! Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From rrr at ronadam.com Thu Jun 30 14:19:26 2005 From: rrr at ronadam.com (Ron Adam) Date: Thu, 30 Jun 2005 18:19:26 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <86y88um4y3.fsf@bhuda.mired.org> <42c1ecaf$1@nntp0.pdx.net> <42c2926a$1@nntp0.pdx.net> Message-ID: Antoon Pardon wrote: > Op 2005-06-29, Scott David Daniels schreef : > >>Roy Smith wrote: >> >>>Andrew Durdin wrote: >>> >>>>Corrected version: >>>> result = [(lambda: expr0), lambda: expr1][bool(cond)]() >> >>Sorry, I thought cond was a standard boolean. >>Better is: >> result = [(lambda: true_expr), lambda: false_expr][not cond]() > > > How about the following: > > result = (cond and (lambda: true_expr) or (lambda: false_expr))() > That works as long as long as they are expressions, but the ? format does seem to be more concise I admit. To use *any* expressions in a similar way we need to use eval which is a lot slower unfortunately. result = eval(['expr0','expr1'][cond]) A thought occurs to me that putting index's before the list might be an interesting option for expressions. result = expr[expr0,expr1] This would probably conflict with way too many other things though. Maybe this would be better? result = index from [expr0,expr1] Where index can be an expression. That is sort of an inline case statement. Using a dictionary it could be: result = condition from {True:expr1, False:expr0} As a case using values as an index: case expr from [ expr0, expr2, expr3 ] Or using strings with a dictionary... case expr from { 'a':expr0, 'b':expr1, 'c':expr3 } else: expr4 Reads nice, but can't put expressions in a dictionary or list without them being evaluated first, and the [] and {} look like block brackets which might raise a few complaints. Can't help thinking of what if's. ;-) Cheer's Ron From zunbeltz at gmail.com Wed Jun 1 04:15:57 2005 From: zunbeltz at gmail.com (Zunbeltz Izaola) Date: Wed, 01 Jun 2005 10:15:57 +0200 Subject: avl tree References: Message-ID: On Tue, 31 May 2005 22:40:19 +0200, Berthold H?llmann wrote: > You can grab it from > > > Thanks i will play with it. But i have realize that what i need was exactly a binary tree. I haven't used tree yet and i don't know if i can use the avl instaead an ordinary binary tree. I have to construct a tree like this A B C A C A B B C A B B C A C but i think i can construct a avl using left/right. Am I correct? Thanks again, Zunbeltz > Please report any problems to me. I'll do my best to solve them. > > Regards, > Berthold From superprad at gmail.com Mon Jun 13 18:01:27 2005 From: superprad at gmail.com (PyPK) Date: 13 Jun 2005 15:01:27 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118697529.173406.134460@g44g2000cwa.googlegroups.com> Message-ID: <1118699398.977677.319560@g44g2000cwa.googlegroups.com> When i try this i get this error: import Image >>> im = Image.open('image.tif') >>> im.getpixel((10,19)) Traceback (most recent call last): File "", line 1, in ? File "Image.py", line 858, in getpixel self.load() File "/usr/local/lib/python2.4/site-packages/PIL/ImageFile.py", line 180, in load d = Image._getdecoder(self.mode, d, a, self.decoderconfig) File "Image.py", line 328, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder group4 not available From timr at probo.com Wed Jun 8 23:06:36 2005 From: timr at probo.com (Tim Roberts) Date: Wed, 08 Jun 2005 20:06:36 -0700 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: Renato Ramonda wrote: > >wxWidgets apps look ALMOST native on windows (combobox and similar >widgets are emulated, and look really bad), That just isn't true. They use the standard combo box. >Last time I looked wx did not have spacers (vbox, hbox and the like)... >this leads to ugly non resizable vb-style guis, in my experience wx uses "sizers" to do the same thing. Same purpose, different philosophy. I find sizers more natural, but people should certainly stick to whatever makes them comfortable. >And that's not even starting to consider the version mess: try to >install xCHM, Boa Constructor, aMule, VLC and some other app together... >instant madness. They why would you do it? gvim and wxPython do the job for me. No mess. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From none at no.chance Wed Jun 29 13:59:06 2005 From: none at no.chance (Peter Tillotson) Date: Wed, 29 Jun 2005 17:59:06 +0000 Subject: importing packages from a zip file Message-ID: Hi all, I was wondering if this is possible. In python v2.3 the import systems was extended via PEP302 to cope with packages. *.py files in a directory hierarchy can be imported as modules each level in the directory hierarchy needs to contain at least an empty __init__.py file. eg. With the file system base/ __init__.py branch1/ __init__.py myModule.py I can import myModule as follows import base.branch1.myModule At the same time its possible to store modules in a flat zip-file and import modules with the following. from myZip.zip import myModule.py but is there a way to do both at the same time? eg. from myZip.zip import base.branch1.myModule I'm interested in this in the development of mobile code for some Grid applications :-) thanks in advance p From cam.ac.uk at mh391.invalid Thu Jun 23 12:38:19 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 23 Jun 2005 17:38:19 +0100 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Antoon Pardon wrote: > Op 2005-06-22, Michael Hoffman schreef : > >>Remi Villatel wrote: >> >>>Fredrik Lundh wrote: >>> >>>>checking if a logical expression is true by comparing it to True is bad >>>>style, and comparing values using "is" is also bad style. >>> >>>I wrote it this way because, first, it's perfectly valid Python code and, >>>second and most important, it's also a valid english sentence. >> >>As others have pointed out, it's not perfectly valid code. In fact it is >>frequently incorrect. > > > That the same code would be incorrect in other circumstances doesn't > make it invalid as it was used in a specific situation. > > I have written code my self with an "if var is True" statement and > that is exactly what I wanted. Replacing it with "if var" would > have broken the the program. That point was not lost on me (which is why I said it was frequently incorrect). I think it was lost on the OP though. -- Michael Hoffman From Scott.Daniels at Acm.Org Mon Jun 20 16:28:43 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 20 Jun 2005 13:28:43 -0700 Subject: binary file In-Reply-To: <42b6fe7a$1_2@newspeer2.tds.net> References: <42b6af4f$1_3@newspeer2.tds.net> <556d8$42b6b8c2$9117fe9b$19867@news2.tudelft.nl> <42b6fe7a$1_2@newspeer2.tds.net> Message-ID: <42b71fa2@nntp0.pdx.net> Kent Johnson wrote: > Nader Emami wrote: >> Kent Johnson wrote: >>> Nader Emami wrote: >>>> I have used the profile module to measure some thing as the next >>>> command: >>>> profile.run('command', 'file') >>>> ...How can I read (or convert) the binary file to an ascii file? >>> Use an instance of pstats.Stats to interpret the results: >>> from pstats import Stats >>> s = Stats('file') >>> s.print_stats() >> I got the same result as the execution of command. But I would like to >> write to the an external 'ascii' file! > Oh, I get it, pstats.Stats doesn't have a way to send the output to a > file. That's surprising! I may be missing something here, but: import sys, pstats s = pstats.Stats('file') sys.stdout, old = open('somefile.txt', 'w'), sys.stdout s.print_stats() sys.stdout, old = old, sys.stdout old.close() Looks to solve your problem to me. --Scott David Daniels Scott.Daniels at Acm.Org From kent37 at tds.net Fri Jun 10 08:49:57 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Jun 2005 08:49:57 -0400 Subject: Is pyton for me? In-Reply-To: References: Message-ID: <42a98c1d$1_1@newspeer2.tds.net> Andrew Dalke wrote: > import subprocess > def gensky(hour): > subprocess.check_call(["gensky", "3", "21", str(hour)], > stdout = open("sky%d.rad" % (hour,), "w")) > > > The main differences here are: > - the original code didn't check the return value of os.system(). > It should do this because, for example, the gensky program might > not be on the path. The check_call does that test for me. Where do you find check_call()? It's not in the docs and I get >>> import subprocess >>> subprocess.check_call Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'check_call' with Python 2.4.1. Kent From sheltraw at berkeley.edu Wed Jun 22 16:06:25 2005 From: sheltraw at berkeley.edu (SHELTRAW, DANIEL) Date: Wed, 22 Jun 2005 13:06:25 -0700 Subject: import search path Message-ID: Hello Python list If a Python program has an import statement like: import FFT how do I determine the path to the imported file? Thanks, Daniel From beyer at imb-jena.de Mon Jun 13 14:32:25 2005 From: beyer at imb-jena.de (Andreas Beyer) Date: Mon, 13 Jun 2005 11:32:25 -0700 Subject: Adding to Exception.args Message-ID: <42ADD139.8080001@imb-jena.de> Hi, If an exception gets raised while I am parsing an input file I would like to know where (in which line) the error occured. I do not want to create my own exception class for that purpose and I also do not want to deal with all possible kinds of exceptions that might occur. I came up with the following code: inp = file(file_name) for n, line in enumerate(inp): try: # parse line ... except Exception, e: inp.close() # Is this necessary for 'r' files? args = list(e.args) args.insert(0, 'line: %d'%(n+1)) e.args = tuple(args) raise Which looks like this in the traceback: ValueError: ('line: 3', 'invalid literal for float(): not_a_number') Is this the 'correct' way to do that? Is there any specific order to the arguments in e.args? Should my 'user argument' be at the beginning or at the end of e.args? Thanks! Andreas From bootsch at acm.org Tue Jun 21 05:55:10 2005 From: bootsch at acm.org (Paul Boots) Date: Tue, 21 Jun 2005 11:55:10 +0200 Subject: ZEO client hangs when combined with other asyncore code Message-ID: Dear people, We have an application that makes use of a ZEO client and has other async socket code that implements as POP3 proxy. The ZEO client is called (to query and store ZEO server) from within the proxy code when it runs during mail checks, so we have multiple async connections at the same time. Somehow, a call to the ZEO client never returns, it just hangs and sits there. In an attempt to fix this problem we added code to use a different socket map for the proxy objects, the ZEO client uses the default asyncore socket_map. But that did NOT solve our problem. At this point we are clueless to the reason behind this behaviour and hope that anyone on this list has some ideas or similar experiences. I realize this is a very terse description of our application, when necessary I can elaborate. -- Best regards, Paul Boots From bastian.salmela at gmail.com Tue Jun 28 07:55:05 2005 From: bastian.salmela at gmail.com (bastian.salmela at gmail.com) Date: 28 Jun 2005 04:55:05 -0700 Subject: pyqt, windows xp and systray applications.. possible? Message-ID: <1119959705.054932.159780@g47g2000cwa.googlegroups.com> hi, I've been searching long, and found some information, but still not enough for me to actually make it happen. so, I ask here. is it possible, in windows, to make PyQT application hide itself into systray area? I read,that you might have to use winEventFilter(), and do some magic with WM_ messages. well, I don't know enough windows API.. so if anyone here have done this, could you please help me out and show a little example how it's done.. thanks in advance. .b From fperez.net at gmail.com Fri Jun 17 13:59:15 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 17 Jun 2005 11:59:15 -0600 Subject: whos -- a function listing objects References: <1118948272.051392.323240@g14g2000cwa.googlegroups.com> Message-ID: benyang22 at yahoo.com wrote: > I have been a long time Matlab user. I Python, I miss Matlab's whos > command. you might want to look at ipython. whos, and a bit more come for free: planck[~]> ipython -pylab Python 2.3.4 (#1, Feb 2 2005, 12:11:53) Type "copyright", "credits" or "license" for more information. IPython 0.6.16_cvs -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. Welcome to pylab, a matplotlib-based Python environment. For more information, type 'help(pylab)'. In [1]: def foo(): pass ...: In [2]: a=rand(128,128) In [3]: x=3.14 In [4]: import code In [5]: whos Variable Type Data/Info -------------------------------- a array 128x128: 16384 elems, type `d`, 131072 bytes (128 kb) code module /lib/python2.3/code.pyc'> foo function x float 3.14 In [6]: whos array Variable Type Data/Info ----------------------------- a array 128x128: 16384 elems, type `d`, 131072 bytes (128 kb) In [7]: whos function Variable Type Data/Info -------------------------------- foo function Cheers, f From anthra.norell at tiscalinet.ch Thu Jun 16 15:45:41 2005 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Thu, 16 Jun 2005 21:45:41 +0200 Subject: Single test for a class and all its subclasses? References: <007c01c57180$d6619880$0201a8c0@mcuf7> <4660fe3005061502283c37d7a8@mail.gmail.com> Message-ID: <026001c572ab$fb065f00$0201a8c0@mcuf7> ----- Original Message ----- From: "Konstantin Veretennicov" To: "Anthra Norell" Cc: "Python SIG" Sent: Wednesday, June 15, 2005 11:28 AM Subject: Re: Single test for a class and all its subclasses? > On 6/15/05, Anthra Norell wrote: > > > > class C: ... > > class C2 (C): ... > > > > # What I want to do: > > > > if x.__class__ in (C, C2): > > do_something_with (x) > > If you have an instance, you can use isinstance() built-in. > Exactly what I've been looking for: isinstance (c, C) -> True isinstance (c, C2) -> False isinstance (c2, C2) -> True isinstance (c2, C) -> True Thank you very much! Frederic From benji at benjiyork.com Sun Jun 26 16:27:37 2005 From: benji at benjiyork.com (Benji York) Date: Sun, 26 Jun 2005 16:27:37 -0400 Subject: unittest: collecting tests from many modules? In-Reply-To: <42bf093c.274849712@news.oz.net> References: <1118588778.234523.112910@g14g2000cwa.googlegroups.com> <42bf093c.274849712@news.oz.net> Message-ID: <42BF0FB9.3020405@benjiyork.com> "Jorgen Grahn" wrote: >What's the best way of creating a test.py which >- aggregates the tests from all the test_*.py modules? You might want to check out the test runner in Zope 3 (svn://svn.zope.org/repos/main/Zope3/trunk/src/zope/app/testing) It aggregates test reporting, does code coverage, lets you select subsets of the tests to run, as well as control verbosity. And, if you feel experimental you might want to preview the new Zope test runner currently under development (svn://svn.zope.org/repos/main/zope.testing). -- Benji York From xah at xahlee.org Sun Jun 12 18:42:58 2005 From: xah at xahlee.org (Xah Lee) Date: 12 Jun 2005 15:42:58 -0700 Subject: tree functions daily exercise: Table In-Reply-To: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> Message-ID: <1118616178.259864.187180@g44g2000cwa.googlegroups.com> Here's the next tree functions exercise in Python, Perl, Java. Other language solutions welcome. http://xahlee.org/tree/tree.html --------------------- Table('exprString', [iMax]) generates a list of iMax copies of value of eval('exprString'), and returns the refence to the list. i.e. [eval('exprString'),eval('exprString'),...] Table('exprString', ['i', iMax]) generates a list of the values by evaluating 'exprString' when 'i' in the string runs from 1 to iMax. Table('exprString', ['i', iMin, iMax]) starts with 'i' = iMin. Table('exprString', ['i', iMin, iMax, iStep]) uses steps iStep. If iStep is negative, then the role of iMin and iMax are reversed. Inputs such as [1, -3 , 1] returns bad result. Table('exprString', ['i', iMin, iMax, iStep], ['j', jMin, jMax, iStep], ... ) gives a array by iterating 'i', 'j' in 'exprString'. For example, Table('f(i,j)', ['i',1,3], ['j',5,6]) returns [[f(1, 5), f(1, 6)], [f(2, 5), f(2, 6)], [f(3, 5), f(3, 6)]]. In general, Table has the form Table('expressionString', iterator1, iterator2, ...) where 'expressionString' is a string that will be evaluated by eval. iterator have one of the following forms [iMax], ['dummyVarString',iMax], ['dummyVarString',iMin, iMax], or ['dummyVarString',iMin, iMax, iStep]. If Table fails, 0 is returned. Table can fail, for example, when the argument are not appropriate references or the iterator range is bad such as ['i',5,1]. Example: Table('q(s)' ,[3]); # returns ['s','s','s'] Table( 'i**2' , ['i', 4]); # returns [1, 4, 9, 16] Table('[i,j,k]',['i',2],['j',100,200,100],['k',5,6]) # returns [[[[1,100,5],[1,100,6]],[[1,200,5],[1,200,6]]], # [[[2,100,5],[2,100,6]],[[2,200,5],[2,200,6]]]] Wolfram Research's Table function documentation is at: http://documents.wolfram.com/mathematica/functions/Table (this post is not affliated with Wolfram Research Incorporated and has not been approved by Wolfram Research Incorporated.) The first argument of Table function in Mathematica (mma) is a expression. Most other languages cannot have such symbolic expressions. In Perl, a string is choosen instead as the experssion, and it is being evalutade later as code. This may not be a practical choice but anyway it's just a exercise. Each other language should choose appropriate design for this emulation... Perl, Python, Java solutions will be posted by me in the coming days. Xah xah at xahlee.org ? http://xahlee.org/ From cpunerd4 at gmail.com Sat Jun 18 12:23:37 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 09:23:37 -0700 Subject: extreme newbie In-Reply-To: References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> Message-ID: <1119111817.610572.73580@g14g2000cwa.googlegroups.com> I see your point, although I don't think there is much a 14 year old can do to sue someone. . . I'm sure my code won't be that valuable untill I'm older though. Thanks From peter at engcorp.com Sun Jun 12 21:52:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Jun 2005 21:52:12 -0400 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Andrea Griffini wrote: > On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen > wrote: >>I think new CS students have more than enough to learn with their >>*first* language without having to discover the trials and tribulations >>of memory management (or those other things that Python hides so well). > > I'm not sure that postponing learning what memory > is, what a pointer is and others "bare metal" > problems is a good idea. ... > I think that for a programmer skipping the > understanding of the implementation is just > impossible: if you don't understand how a > computer works you're going to write pretty > silly programs. I'm curious how you learned to program. What path worked for you, and do you think it was a wrong approach, or the right one? In my case, I started with BASIC. Good old BASIC, with no memory management to worry about, no pointers, no "concrete" details, just FOR loops and variables and lots of PRINT statements. A while (some months) later I stumbled across some assembly language and -- typing it into the computer like a monkey, with no idea what I was dealing with -- began learning about some of the more concrete aspects of computers. This worked very well in my case, and I strongly doubt I would have stayed interested in an approach that started with talk of memory addressing, bits and bytes, registers and opcodes and such. I won't say that I'm certain about any of this, but I have a very strong suspicion that the *best* first step in learning programming is a program very much like the following, which I'm pretty sure was mine: 10 FOR A=1 TO 10: PRINT"Peter is great!": END And no, I don't recall enough BASIC syntax to be sure that's even correct, but I'm sure you get my point. In one line I learned (implicitly at first) about variables, control structures and iteration, output, and probably a few other things. More importantly by far, *I made the computer do something*. This should be everyone's first step in a programming course, and it doesn't take the slightest understanding of what you call "concrete" things... (though I'd call these things very concrete, and memory management "esoteric" or something). If I had been stuck in a course that made me learn about memory management before I could write a program, I'm pretty sure I'd be doing something fascinating like selling jeans in a Levis store... -Peter From snail at objmedia.demon.co.uk Fri Jun 3 06:51:18 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 3 Jun 2005 11:51:18 +0100 Subject: Problem calling Python methods from C Message-ID: Hello everyone, I'm trying to do something in C calling Python and its failing. I'd be grateful if you could take a look and hopefully you have an answer. What I'm trying to do is determine the address of the "collect" function in the "gc" module. I want to do this so that we can determine when a garbage collection happens, regardless of how it is triggered (explicitly by a user call, or implicitly by the behaviour of the program allocating lots of data). As far as I can tell, the gc.collect function is not exposed as a C API, so I cannot hook that to do the monitoring I want. Therefore the only way to get the address to hook is to inspect the Python module function dictionaries, well I think its the only way :-) The approach is to get the module that holds "gc". You can do this by calling PyImport_AddModule for an existing module - it will return it. Then you get the dictionary of methods from the module and lookup the method in there. Well, that was my theory after looking at the Python source code. I've shown the source code below. // get "collect" method from GC module // this module should always be present // as it is a fundamental part of Python PyObject *module; DWORD funcAddress = NULL; module = PyImport_AddModule("gc"); if (module != NULL) { // get dictionary of methods for this module PyObject *dict; dict = PyModule_GetDict(module); if (dict != NULL) { // lookup "collect" in the dictionary PyObject *func; int numItems; // check we have some elements, // strangely there are only 2 numItems = PyDict_Size(dict); // this works, good, that is expected func = PyDict_GetItemString(dict, "__name__"); // this fails, why? "collect" is a method in "gc" // I would expect it to work func = PyDict_GetItemString(dict, "collect"); } } Hopefully someone can shed some light on why this doesn't work, or explain what the correct method should be if I am doing the wrong thing. Answers as descriptions, Python or C most welcome. Cheers Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From max at alcyone.com Sat Jun 18 03:52:31 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 18 Jun 2005 00:52:31 -0700 Subject: Python documentation problem In-Reply-To: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Message-ID: <14udnXvoHKYiTy7fRVn-oA@speakeasy.net> Xah Lee wrote: > Fuck the python doc wasted my time. Fuck python coders. Use your words! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The mind is not a vessel to be filled but a fire to be kindled. -- Plutarch From theller at python.net Wed Jun 8 16:40:46 2005 From: theller at python.net (Thomas Heller) Date: Wed, 08 Jun 2005 22:40:46 +0200 Subject: running distutils installer without admin on windows References: <1118241029.833151.252720@g47g2000cwa.googlegroups.com> <1118241612.999333.224880@f14g2000cwb.googlegroups.com> <1118247598.432934.169860@g14g2000cwa.googlegroups.com> Message-ID: "timothy.williams at nvl.army.mil" writes: > I didn't build the installer, someone else did. I did get the source > and installed cygwin to see if I could recreate it; at least build the > library, but when I tried to do a build_ext I got a message saying I > needed to have the .NET SDK installed. You could at least open the installer exe in winzip or a similar tool, and unpack it manually to the site-packages directory. Thomas PS: I *think* that the distutils from newer Python versions (2.4.1 and 2.3.5) create installers that can also run without admin rights. From kent37 at tds.net Tue Jun 7 13:54:21 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 13:54:21 -0400 Subject: xmlrpclib - methodHelp doesn't work In-Reply-To: <1118164334.528966.125920@g47g2000cwa.googlegroups.com> References: <1118164334.528966.125920@g47g2000cwa.googlegroups.com> Message-ID: <42a5df03$1_2@newspeer2.tds.net> srinivasanr at gmail.com wrote: > I tried out the examples in this website for XML-RPC using python - > http://www.onlamp.com/pub/a/python/2000/11/22/xmlrpcclient.html?page=2 > But I get the following errors when I try to execute the code. Here is > the snippet of the code with the error messages. >>>>meerkatsvr.system.methodSignature(meerkat.getChannels) > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'meerkat' is not defined > >>>>meerkatsvr.system.methodHelp(meerkat.getItems) > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'meerkat' is not defined You have to give the method names as strings. Your code is looking for a 'getChannels' or 'getItems' attribute of something named 'meerkat', but there is no such name in the current scope. Try this: Type "help", "copyright", "credits" or "license" for more information. >>> import xmlrpclib >>> meerkatURI = "http://www.oreillynet.com/meerkat/xml-rpc/server.php" >>> meerkatsvr = xmlrpclib.Server(meerkatURI) >>> meerkatsvr.system.listMethods() ['meerkat.getChannels', 'meerkat.getCategories', 'meerkat.getCategoriesBySubstring', 'meerkat.getChannelsByCategory', 'meerkat.getChannelsBySubstring', 'meerkat.getItems', 'system.listMethods', 'system.methodHelp', 'system.methodSignature'] >>> print meerkatsvr.system.methodSignature('meerkat.getChannels') [['array']] >>> print meerkatsvr.system.methodHelp('meerkat.getItems') Returns an array of structs of RSS items given a recipe struct. Kent From grahamd at dscpl.com.au Sat Jun 11 02:41:08 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 10 Jun 2005 23:41:08 -0700 Subject: Mod_python psp import module problem References: <1118464361.670242.170970@g47g2000cwa.googlegroups.com> Message-ID: <1118472068.301304.288130@g43g2000cwa.googlegroups.com> May be related to this bug: http://issues.apache.org/jira/browse/MODPYTHON-12 Where you have: import mod_python.psp change it to: psp = apache.import_module("mod_python.psp") Access the PSP object then as: psp.PSP and not: mod_python.psp.PSP It will happen where somewhere else within the same document tree there is a PythonHandler specified as mod_python.psp as well as the explicit import of mod_python.psp. Depending on which ones gets triggered first, it will screw up. Graham From tim.golden at viacom-outdoor.co.uk Wed Jun 22 04:55:34 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 22 Jun 2005 09:55:34 +0100 Subject: Running WMI within a Windows service Message-ID: <9A28C052FF32734DACB0A288A3533991EBB91F@vogbs009.gb.vo.local> [cameron.mccloud at gmail.com] | [.. re problems running WMI in a service ...] | Changing the path didn't do anything, but changing the name of the | module to my_wmi did the trick. | | Thanks very much, | | Cam. | Thanks for the feedback; I'll try to find the time to experiment a bit but I know I've used the change-the-name trick in the past. It has been suggested that I permanently change the module name, but I'm a bit loth to do that. Mark (Hammond) was talking about a patch which would prevent imports from picking up the false .dll, but I don't know if it's gone anywhere. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From grobinson at goombah.com Tue Jun 14 15:09:48 2005 From: grobinson at goombah.com (Gary Robinson) Date: Tue, 14 Jun 2005 15:09:48 -0400 Subject: Thread priorities? Message-ID: <20050614150948.752489.8bacee83@goombah.com> In the application we're writing (http://www.goombah.com) it would be helpful for us to give one thread a higher priority than the others. We tried the recipe here: http://groups-beta.google.com/group/comp.lang.python/msg/6f0e118227a5f5de and it didn't seem to work for us. We don't need many priority levels. We just need one thread to *temporarily* have a higher priority than others. One thing that occurred to me: There wouldn't by any chance be some way a thread could grab the GIL and not let it go until it is ready to do so explicitly? That would have the potential to solve our problem. Or maybe there's another way to temporarily let one thread have priority over all the others? Gary -- Gary Robinson CTO Emergent Music, LLC grobinson at goombah.com 207-942-3463 Company: http://www.goombah.com Blog: http://www.garyrobinson.net From peter at engcorp.com Fri Jun 3 07:31:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Jun 2005 07:31:09 -0400 Subject: decimal and trunkating In-Reply-To: References: <429f0656$0$32668$626a14ce@news.free.fr> <3g8fcjFarp9dU1@individual.net> <8f-dnecR35jVkwLfRVn-tw@powergate.ca> <3g8kk4Fb5v3dU1@individual.net> Message-ID: chris wrote: > I'm new to Python ... and I've used decimal._round() as above. What's the > deal with using underscore methods? (A link will do if that'll save you some > typing). Generally the underscore methods provide *internal* functionality that might be used by other, more externally accessible (i.e. documented!) methods in the object. While as I've said I'm no expert in Decimal and can't say how _round() is intended to be used, it is not documented (as far as I can see) and certainly therefore follows this way of thinking about underscore methods. Several of us have found at least one suitable alternative (i.e. quantize()) that don't rely on underscore methods. (Think of the underscore as being a non-binding convention that says "don't use this externally if possible, as it doesn't form part of the contract guaranteed by this object... it may be removed in the future, may not work exactly as you wish, may have side effects that aren't documented or haven't been analyzed fully when used externally, etc.") -Peter From and-google at doxdesk.com Wed Jun 15 16:20:25 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 15 Jun 2005 13:20:25 -0700 Subject: Python as CGI on IIS and Windows 2003 Server References: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> Message-ID: <1118866825.583734.5450@o13g2000cwo.googlegroups.com> Lothat wrote: > No test with or without any " let the IIS execute python scrits as cgi. > Http Error code is 404 (but i'm sure that the file exists in the > requested path). Have you checked the security restrictions? IIS6 has a new feature whereby script mappings are disabled by default even if they are listed in the configuration list. To turn CGI on, go to the IIS Manager snap-in and select the 'Web Service Extensions' folder. Select 'All Unknown CGI Extensions' and click 'Allow'. Incidentally, the string I am using is: "C:\Program Files\Python\2.4\python.exe" -u "%s" "%s" -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From ryanlbowman at yahoo.com Thu Jun 30 18:22:21 2005 From: ryanlbowman at yahoo.com (Ryan Bowman) Date: Thu, 30 Jun 2005 15:22:21 -0700 (PDT) Subject: Python syntax high-lighting and preservation on web In-Reply-To: <312cfe2b050629062046796a52@mail.gmail.com> Message-ID: <20050630222221.85938.qmail@web51906.mail.yahoo.com> --- Gregory Pi?ero wrote: > Hey guys, > > Does anyone know where I can pick up a style sheet (css) and/or other > files/programs I might need to display python code on my website with > tab preservation(or replace with spaces) and colored syntax? I want > something similar to the python code on a page like this: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303770 > > (I think this is a python-list question although maybe it belongs in a > css group?) I figure some of you guys would have experience with > this. > > ----- If you use emacs to edit your code another option is the package htmlize.el, which produces an html file from a file as it is displayed in emacs, syntax highlighting and indentation preserved. I've used it a few times. It produces CSS in the head of the html code. http://fly.srk.fer.hr/~hniksic/emacs/htmlize.el.html ---- Ryan Bowman I get the feeling that the compiler just skips over all the comments... ---- __________________________________ Yahoo! Mail Mobile Take Yahoo! Mail with you! Check email on your mobile phone. http://mobile.yahoo.com/learn/mail From timr at probo.com Thu Jun 9 00:41:20 2005 From: timr at probo.com (Tim Roberts) Date: Wed, 08 Jun 2005 21:41:20 -0700 Subject: help with sending mail in Program References: <42a56e49_3@newspeer2.tds.net> Message-ID: Kent Johnson wrote: >Ivan Shevanski wrote: >> Could someone send me a good tutorial for sending mail then? The one I >> found is not what I'm looking for. Also please dont send me the stmp >> definition cause i've looked at that enough. > >Here is a module I use to send mail to myself using smtplib: Not exactly like this, you didn't. The list of destination addresses in SMTP.sendmail must be a sequence, not a string: >#!/usr/local/bin/python > >''' Send mail to me ''' > >from smtplib import SMTP > >def sendToMe(subject, body): > me = '"Kent Johnson" ' > send(me, me, subject, body) > > >def send(frm, to, subject, body): > s = SMTP() ># s.set_debuglevel(1) > s.connect('mail.mycompany.com') > s.ehlo('10.0.3.160') # IP address of my computer, I don't remember why I needed this > > msg = '''From: %s >Subject: %s >To: %s > >%s >''' % (frm, subject, to, body) > > s.sendmail(frm, to, msg) s.sendmail(frm, [to], msg) > s.quit() > > >if __name__ == '__main__': > sendToMe('Testing', 'This is a test') -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vincent at visualtrans.de Sat Jun 25 02:26:36 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 25 Jun 2005 08:26:36 +0200 Subject: Running Python scripts under W2K with I/O redirection References: <1119629947.977882.174830@g49g2000cwa.googlegroups.com> Message-ID: schrieb im Newsbeitrag news:1119629947.977882.174830 at g49g2000cwa.googlegroups.com... |I apologise if this is a well known problem. I've searched and can't | find a clear description or fix. Hope someone can help. | | I am running my Python scripts under Windows 2000 using Python 2.4 | Build 243 from Activestate. | | If I want to specify a file as standard input to my script I can just | enter a command like: | | H:\> pyscript.py file.inp | | and that's what I get. All ok so far. | | However if I enter commands like: | | H:\> type file.inp | pyscript.py | | or | | H:\> pyscript.py < file.inp | | It doesn't work. I've also tried the variant of parsing for a command | line argument of '-' or 'filename' and then specifically either copying | the sys.stdin file object or opening the file specified, then using | that file object. Same problem. | | Interestingly enough, if I specify my commands as: | | H:\> type file.inp | python pyscript.py | | or | | H:\> python pyscript.py < file.inp | | It all works the (unix-like) way I wanted it to. This leads me to | suspect there is something wrong in the way that Python is being | invoked by Windows in my problem situation rather than an inherent | fault within Python itself. Your suspicion is correct see: http://support.microsoft.com/default.aspx?kbid=321788 -- Vincent Wehren | | Does anyone have any idea what the problem could be and how to fix it? | I know its a really minor niggle but it'd make this poor deprived | unix-guy-forced-into-windows-servitude very happy. | | Thanks, sub1ime_uk | | sub1ime_uk (at) yahoo (dot) com | From noreply at gcgroup.net Tue Jun 28 17:16:51 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 28 Jun 2005 21:16:51 GMT Subject: tkinter radiobutton In-Reply-To: References: <1ygwe.532$Ox3.193@newssvr12.news.prodigy.com> Message-ID: <77jwe.1481$cb6.662@newssvr30.news.prodigy.com> > What follows looks more like a spec than a question. It is, but I wanted to show why I was getting confused trying to use control variables to maintain the overall relationship. Thank you. This is exactly what I'm trying to do, and oddly enough similar in concept to what I was doing, but far more readable and maintainable (thus the philosophical component :-)) using 'for x, column in enumerate(columns):' for a looping structure cleared up a lot of the convoluted 'score keeping' I was trying to do in my nested loops. Also, does 'row == var.get() for var in self.variables' perform the comparison row == var.get() for each item in self.variables? I would have had to write: for var in self.variables: return row == var.get() Again, thanks. Bill Peter Otten wrote: > William Gill wrote: > > >>I thought the problem was practical, not philosophical, but what do I >>know I'm the one asking for help. > > > What follows looks more like a spec than a question. > > >> columns can have 0 or 1 selection >> rows can have 0,1,2,3, or 4 selections. > > >>Loop through the 4 intVars 4 times; compare their value to the value for >>the row being processed; if they are the same bitor a value to a >>rowVariable i.e. convert the column information (intVar values) to row >>information. > > > Here's my implementation: > > import Tkinter as tk > > class Radiogrid(tk.Frame): > def __init__(self, master, columns, trace_write=None): > tk.Frame.__init__(self) > self.variables = [] > self.buttons = [] > for x, column in enumerate(columns): > var = tk.IntVar() > if trace_write: > var.trace_variable("w", trace_write) > self.variables.append(var) > self.buttons.append([]) > for y, text in enumerate(column): > rbn = tk.Radiobutton(self, text=text, variable=var, value=y) > rbn.grid(column=x, row=y) > self.buttons[-1].append(rbn) > def get_row_state(self, row): > return tuple(row == var.get() for var in self.variables) > > if __name__ == "__main__": > root = tk.Tk() > def show_state(*args): > for i in range(3): > print "row", i, rg.get_row_state(i) > print > rg = Radiogrid(root, > ["alpha beta gamma".split(), > "one two three".split(), > "guido van rossum".split()], > show_state > ) > rg.pack() > root.mainloop() > > I hope this will move further discussion from the abstract to the > concrete :-) > > Peter > From ncoghlan at gmail.com Thu Jun 30 05:06:09 2005 From: ncoghlan at gmail.com (NickC) Date: 30 Jun 2005 02:06:09 -0700 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> <1120023753.231890.182890@g43g2000cwa.googlegroups.com> Message-ID: <1120122369.102213.307350@o13g2000cwo.googlegroups.com> > Gentle folk of comp.lang.python, I heartily thank you all for your > input. I think I'm taking the boys through the door marked "Logo." We > may be back this way, though. We will likely need MORE in the nebulous > future. I am impressed with the outpouring of support here! Before you commit totally to the LOGO idea, take a look at Guido van Robot: http://gvr.sourceforge.net/ http://gvr.sourceforge.net/about.php http://gvr.sourceforge.net/lessons/rfrank/ Cheers, Nick. From guyon.moree at gmail.com Wed Jun 8 05:38:59 2005 From: guyon.moree at gmail.com (=?iso-8859-1?B?R3V5b24gTW9y6WU=?=) Date: 8 Jun 2005 02:38:59 -0700 Subject: Binary numbers In-Reply-To: References: Message-ID: <1118223539.513060.229760@g49g2000cwa.googlegroups.com> Don't know if this is what you mean, but: Binary to decimal: >>> bin_num = '100001011' >>> int(bin_num, 2) 267 >>> def dec2bin(dec_number): ... if dec_number == 0: return '0' ... return (dec2bin(dec_number >> 1) + str(dec_number % 2)) ... >>> dec2bin(267) '0100001011' -- Guyon Mor?e guyon.moreeNOSP at Mgmail.com http://gumuz.looze.net From guy.lateur at pandora.be Fri Jun 24 17:12:10 2005 From: guy.lateur at pandora.be (guy lateur) Date: 24 Jun 2005 14:12:10 -0700 Subject: Office COM automatisation - calling python from VBA In-Reply-To: References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <1119647530.626534.142390@z14g2000cwz.googlegroups.com> > You want to use --- Python ??? So far I haven't been informed of any serious arguments as to why I wouldn't. > How, pray tell, do you add up (VBA+VBA+VBA+VBA+VBA) and have it come out > equaling Python? My total was this: 57*python + wxPython. > Do you think that might please a few of us here in this > particular newsgroup? Yes. From ivanlan at pauahtun.org Thu Jun 30 19:50:34 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 30 Jun 2005 17:50:34 -0600 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> <86k6kb8nj7.fsf@bhuda.mired.org> Message-ID: <42C4854A.ADDF2739@pauahtun.org> Hi All-- Mike Meyer wrote: > > xeys_00 at yahoo.com writes: > > As other have noted, C was never really used for everything. Unix > tools were designed to connect together from the very beginning, which > is what makes shell scripting so powerful. This was true before there > was a C. Likewise, some things you need more control over the machine > than you get in C - those are still done in assembler. These days, C > compilers let you embed assembler statements in your C, so some of > these things are done in such variants. > It really was used "for everything"; C compilers have *always* let you include assembler, with the "asm" keyword. Unless you're talking about the early days of DOS/Windows compilers, about which I know little, but all *K&R* compilers had asm. If you wanted to write kernel code and device driver code (including disk drivers) for large Unix systems, asm was a requirement. To put it in perspective, for Gould systems in the 80s, for the entire OS (BSD-derived Unix), there were under 100 lines of assembler, all in a very few device drivers (multiple thousands of lines of code, don't remember exactly how many). And living with structs instead of classes was not nearly as much of a pain in the butt as you make out; it was perfectly reasonable to include methods within structs, by including a pointer to a function. X10 and X11 showed just how object-oriented you could get with C, using callbacks with required signatures, and specifying how Widgets were to be written--contracts before there were contracts. It's true that OO languages are better, and languages like Python which allow you to combine fairly low-level calls with an OO worldview make life *vastly* easier, but C is still hugely flexible, highly adaptable, and very powerful. For about 10 or 15 years there, knowing C was pretty much a guarantee of a good job. That changed when C++ compilers became common and good and not merely preprocessors that wrote really, really ugly C. Metta, -ly y'rs, Ivan;-) ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From http Sun Jun 5 20:57:32 2005 From: http (Paul Rubin) Date: 05 Jun 2005 17:57:32 -0700 Subject: random module question References: Message-ID: <7xd5r0714z.fsf@ruckus.brouhaha.com> "Roose" writes: > Can I rely on the random.py module to produce the same series of numbers for > future/past versions of Python, given the same seed? Can I rely on it > across different architectures and operating systems? > > I looked at the docs and couldn't find this stated anywhere. My feeling is > yes, but it's a fairly big claim so I want to make sure. I do not think you should rely on this. It uses a very specific algorithm (Mersenne Twister) which is written in C and is nonstandard, and future Python implementers shouldn't be expected to implement the exact same algorithm. It's probably already unavailable in Jython. See SF bug 917055 for some further discussion. From http Wed Jun 1 05:37:07 2005 From: http (Paul Rubin) Date: 01 Jun 2005 02:37:07 -0700 Subject: Help with Queues and Threading References: Message-ID: <7xd5r6ifjw.fsf@ruckus.brouhaha.com> Ognjen Bezanov writes: > But if I run the loop directly (i.e. not using threads, just calling the > function) it works just fine. What could the problem be? You have to say args=(cmddata,) with the comma inside the parens, to make a seqence instead of a parenthesized expression. From onurb at xiludom.gro Tue Jun 7 05:17:35 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 07 Jun 2005 11:17:35 +0200 Subject: Question about Object Oriented + functions/global vars? In-Reply-To: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> References: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> Message-ID: <42a56630$0$23154$636a15ce@news.free.fr> flamesrock wrote: > ok, so to my knowledge, object oriented means splitting something into > the simplest number of parts and going from there. So you may want to refine your knowledge. What you're talking about is top-down functional decomposition, and it's almost the opposite of OO. OO is about interacting objects. An object is defined by an identity, a state, a behaviour, and (even if implicitely) an interface. Objects do interact by sending messages to each others. The interface of a given object is the list of *what* messages this object understands (ie: can respond to). The behavior is defined by *how* a given object responds to messages (different objects can respond differently to the same message, and a given object may respond differently to the same message according to it's current state). The state is made up of the object's internals vars. > But the question is- > when is it enough? > > For example I have the following code: > > #def put_file(file_id, delete=False): > # """ Function to put the file on the FTP Server > # """ > # print "["+file_id+"] FTP for this file started" > # print "[" + file_id + "] Connecting to machine " + global_addr Where does this 'global_addr' var come from ? > # ftp_pool = FTP_pool(file_id,1,40,global_uid,global_pwd) idem for global_uid and global_pwd. And what are those magic numbers 1 and 40 ? > # print 'in put_file' > # try: > # ftp = ftplib.FTP(global_addr) > # ftp.login(global_uid, global_pwd) > # print ftp.getwelcome() +'\n' > # ftp.cwd(global_ftp_loc) > >># ext = os.path.splitext(file_id)[1] >># if ext not in (".sc4", ".snpickle"): >># ftp.storlines("STOR " + file_id, open(file_id)) >># else: >># ftp.storbinary("STOR " + file_id, open(file_id, "rb"), 1024) > > # ftp.quit() > # ftp_pool.close_all() > # except: Take care of too-large-except-clause. Here it's ok since you re-raise the exception, but this is usually a bad practice to not specify the exception class(es) you want to catch. Hint: sys.exit() works by raising SystemExit. > # ftp_pool.close_all() > # print "[" + file_id + "]Unable to access FTP location" > # print "[" + file_id + "]Error:" + str(sys.exc_info()[0]) + " " > + str(sys.exc_info()[1]) > # upload_status[file_id] = "FAILED" Where does this upload_status comes from ? > # raise > # else: > # print "[" + file_id + "] FTP for file completed" > # upload_status[file_id] = "SUCCESS" > > would the lines with '>#' best be split up into a seperate function, > for example: > > #def upload(ftp, file): dont use 'file', it shadows the builtin file class. > # ext = os.path.splitext(file)[1] > # if ext in (".txt", ".htm", ".html"): > # ftp.storlines("STOR " + file, open(file)) > # else: > # ftp.storbinary("STOR " + file, open(file, "rb"), 1024) Nope. The calling code should not have to worry about this. This should be a responsability of some object(s) abstracting the file, and should be implemented as different behaviors (using text or binary) in response to the same message. In short, this could look like: the_file = FtpFileDescriptor(path) try: # the_file objects knows if it must use text or binary. # we, as client, just don't care about this gory detail. the_file.store() except MyFtpUploadError, e: # TODO pass > > and then doing the call 'upload(file_id)', or is it a better practice > to leave things the way they were? I'm confused. > > Finally, is it considered 'un-object-oriented' in python to have > functions inside a module that are called by objects (ie the upload > function above) and/or use global variables in combination? In Python, everything's an object (well... almost everything). At runtime, a module is an object : >>> ftplib >>> ftplib.__class__ >>> ftplib.__class__.__name__ 'module' module-level 'functions' are methods of the given module object, and 'global' vars (the term 'global' is somewhat misleading, since it reaaly means 'module-level') are attributes of the module object. Now what makes the difference between OO and non-OO is not the use of classes, objects etc, but how you *design* your program. Your code snippet makes use of OO features (classes, objects etc), but is typical of procedural style. Not because you use 'module-level' functions and vars, but because there's no abstraction, no separation of concerns and responsabilities. > -thanks in advance HTH (not sure, but...) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Wed Jun 15 21:36:11 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 16 Jun 2005 11:36:11 +1000 Subject: splitting delimited strings In-Reply-To: References: Message-ID: <42b0d789$1@news.eftel.com> Leif K-Brooks wrote: > Mark Harrison wrote: > >>What is the best way to process a text file of delimited strings? >>I've got a file where strings are quoted with at-signs, @like this at . >>At-signs in the string are represented as doubled @@. > > >>>>import re >>>>_at_re = re.compile('(?>>>def split_at_line(line): > > ... return [field.replace('@@', '@') for field in > ... _at_re.split(line)] > ... > >>>>split_at_line('foo at bar@@baz at qux') > > ['foo', 'bar at baz', 'qux'] The plot according to the OP was that the @s were quotes, NOT delimiters. From piet at cs.uu.nl Fri Jun 17 06:15:27 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 17 Jun 2005 12:15:27 +0200 Subject: whos -- a function listing objects References: <1118948272.051392.323240@g14g2000cwa.googlegroups.com> Message-ID: >>>>> benyang22 at yahoo.com (b) wrote: >b> I have been a long time Matlab user. I Python, I miss Matlab's whos >b> command. >b> So I have written a little utility whos.py, which can be downloaded >b> here: >b> http://beluga.eos.ubc.ca/~tang/softwares/python/ >b> Here is the doc string: >b> # Before using whos, do: >b> execfile('whos.py') >>> execfile('whos.py') >>> whos() Traceback (most recent call last): File "", line 1, in ? File "whos.py", line 142, in whos iType1 = string.split(str(iType), "'")[1] NameError: global name 'string' is not defined Using execfile is a bad way to get the function definition. Import is the way to go. Just add a line: import string to the beginning of whos.py, and the the usage should be: from whos import whos whos() or import whos whos.whos() -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From hongqn at gmail.com Mon Jun 20 02:23:07 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Mon, 20 Jun 2005 14:23:07 +0800 Subject: Can we pass some arguments to system("cmdline")? In-Reply-To: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> References: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> Message-ID: <42B660CB.3020404@gmail.com> Didier C wrote: > Hi! > I was wondering if we can pass some arguments to system("cmdline")? > > E.g in Perl, we can do something like: > > $dir="/home/cypher"; > > system("ls $dir"); > > which would instruct Perl to do an "ls /home/cypher" > > But in python, doing something like > > dir="/home/cypher" > system("ls dir") > > would cause python to execute "ls dir" where "dir" might not exist at > all! Is there a way to reproduce the same thing in Python? > > Thanks for any insights. > > cheers, > Didier. You should use something like this: dir = "/home/cypher" system("ls %s" % dir) -- Qiangning Hong _______________________________________________ / lp1 on fire \ | | \ -- One of the more obfuscated kernel messages / ----------------------------------------------- \ \ \ ___ _____ ___ / \ / /| / \ | | / / | | | | | /____/ | | | | | | | | | | | | | {} | / | | | | |____|/ | | | | |==| | | | \___________/ | | | | | From hancock at anansispaceworks.com Mon Jun 13 14:41:48 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 13:41:48 -0500 Subject: How to get/set class attributes in Python In-Reply-To: <0001HW.BED206D2002D2163F0407550@news.gmane.org> References: <0001HW.BED206D2002D2163F0407550@news.gmane.org> Message-ID: <200506131341.48379.hancock@anansispaceworks.com> I really think the problem is that you are trying to use techniques whose only reason for existing is that they make up for deficiencies in other languages: For example, the *reason* for the Java or C++ use of get/set methods is to allow for the future possibility of needing to make those operations dynamic. Python solves this by allowing you to create get/set methods *only when needed* by using "properties", using exactly the same interface as provided by ordinary attributes. Thus there is no need to artificially add get/set methods in the general case. This results in much cleaner and more concise code. The *reason* for taking so much care that a variable is of the right type in classes in C++ or Java is because the program will crash if they are not. In Python, you would be better served to: 1) Assume the variables are of a sensible type (not necessarily the one you expected, though), and provide exception handling to catch the case where their interface does not match what you expect. 2) Check for the specific interface methods that you need, only (if all you plan to do is read from a "file", you shouldn't worry about whether the "file" object you've been handed actually has a "write" method or not). This is often called "duck typing". 3) Use "interfaces" (either from Zope or PyProtocols) to specify the required *behavior* (not type). Let's face it -- should it matter if you "are a programmer" or only if you "can program"? This is the difference in philosophy behind a dynamically-typed language like Python and a statically typed one like Java. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From jan.danielsson at gmail.com Mon Jun 6 19:29:21 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Tue, 07 Jun 2005 01:29:21 +0200 Subject: Creating file of size x In-Reply-To: <11a9mlh4t7oif3c@corp.supernews.com> References: <42a4cea6$1@griseus.its.uu.se> <56qdnYcDS9f3TDnfRVn-tw@speakeasy.net> <42a4d256$1@griseus.its.uu.se> <11a9mlh4t7oif3c@corp.supernews.com> Message-ID: <42a4db07$1@griseus.its.uu.se> Grant Edwards wrote: >>>> Is there any way to create a file with a specified size? >>> >>>What do you want to put in the file? Once you've answered that >>>question, the solution should present itself. >> >>Check blocks from an FEC-encoder (Freenet, more specifically). >> >> The problem is that the design I'm working on won't guarantee what >>order the blocks will be returned in -- so I need to be able to seek to >>block n's location and write the ckeck block. > > Exactly. And precisely how did that fail? It didn't -- but that's on my platform; I have no idea how it'll work on another platform; which is why I wanted to be able to first create the file of the specified size, and then start writing to it. >>Next block could be m, where m < n. So, they aren't continous. > > If you do a seek before each write, it doesn't matter. According to Python, posix, Linux, Windows, ANSI-C? From deets at web.de Tue Jun 7 12:13:01 2005 From: deets at web.de (Diez B. Roggisch) Date: Tue, 07 Jun 2005 18:13:01 +0200 Subject: time consuming loops over lists In-Reply-To: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> Message-ID: querypk at gmail.com wrote: > X-No-Archive: yes > Can some one help me improve this block of code...this jus converts the > list of data into tokens based on the range it falls into...but it > takes a long time.Can someone tell me what can i change to improve > it... > > if data[i] in xrange(rngs[j],rngs[j+1]): > That's a bummer: You create a list and then search linearily in in - where all you want to know is if rngs[j] <= data[i] < rngs[j+1] Attached is a script that does contain your old and my enhanced version - and shows that the results are equal. Running only your version takes ~35s, where mine uses ~1s!!! Another optimization im too lazy now would be to do sort of a "tree search" of data[i] in rngs - as the ranges are ordered, you could find the proper one in log_2(len(rngs)) instead of len(rngs)/2. Additional improvements can be achieved when data is sorted - but that depends on your application and actually sizes of data. Diez -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.py URL: From gene.tani at gmail.com Wed Jun 22 19:01:36 2005 From: gene.tani at gmail.com (gene tani) Date: 22 Jun 2005 16:01:36 -0700 Subject: Optimize a cache In-Reply-To: <7xoe9yt6ob.fsf@ruckus.brouhaha.com> References: <7xoe9yt6ob.fsf@ruckus.brouhaha.com> Message-ID: <1119477894.072497.20750@g14g2000cwa.googlegroups.com> a ring buffer? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/68429 From steven.bethard at gmail.com Wed Jun 29 16:11:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Jun 2005 14:11:20 -0600 Subject: Modules for inclusion in standard library? In-Reply-To: <1120072104.541014.166820@o13g2000cwo.googlegroups.com> References: <3ian37Fkjle0U1@individual.net> <1120072104.541014.166820@o13g2000cwo.googlegroups.com> Message-ID: Noah wrote: > def unzip(list): > if len(list) == 0: return () > l = [] > for t in range(len(list[0])): > l.append(map( lambda x,t=t: x[t], list )) > return tuple(l) The simplest solution to this problem that I know of: def unzip(iterable): return zip(*iterable) However, Guido feels that this is an abuse of the argument passing machinery. For a version that is a little more careful in the case of iterables, see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302325 STeVe From deets at web.de Mon Jun 27 17:12:44 2005 From: deets at web.de (Diez B. Roggisch) Date: Mon, 27 Jun 2005 23:12:44 +0200 Subject: Getting binary data out of a postgre database In-Reply-To: <1119878398.854244.132830@z14g2000cwz.googlegroups.com> References: <1119636233.488038.170240@z14g2000cwz.googlegroups.com> <3i320qFjktsjU2@uni-berlin.de> <1119878398.854244.132830@z14g2000cwz.googlegroups.com> Message-ID: <3ib8eeFkler1U1@uni-berlin.de> projecktzero wrote: > Sorry for the late reply. I didn't check the group/list over the > weekend. > > Anyway, I added a print rec[0] just after the fetchone. Then I ran it > from the command line, and it spewed a bunch of binary gibberish nearly > locking up Putty. > > To me, it seems like it's coming out in the right format, but I'm not > sure what I'm doing wrong. If you have any ideas, I'd really > appreciate it. What does print rec[0].__class__ give you? And what about using tempFile.write(str(rec[0])) if print really resulted in the binary data, this might help. The DB-Api isn't too detailed about binary columns at all - the just mentioned a Binary() object, and something about buffer objects. I'm not sure how to ndeal with these - they seem to be mentioned in the C-Api-Section only. Sorry that I can't be of more help. Diez From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 7 15:19:23 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 07 Jun 2005 21:19:23 +0200 Subject: split up a list by condition? In-Reply-To: <1118125802.096110.167820@g49g2000cwa.googlegroups.com> References: <3gjpk0FcrnknU1@individual.net> <1118125802.096110.167820@g49g2000cwa.googlegroups.com> Message-ID: <3gma9rFd6jmpU1@individual.net> Raymond Hettinger wrote: >>> while writing my solution for "The python way?", I came across this fragment: >>> vees = [c for c in wlist[::-1] if c in vocals] >>> cons = [c for c in wlist[::-1] if c not in vocals] >>> >>> So I think: Have I overlooked a function which splits up a sequence >>> into two, based on a condition > > Trying to compress too much into one line is not "the python way" ;-) I know (there is a Guido quote about this, I just lost the source...) > vees, cons = [], [] > for c in reversed(wlist): > if c in vocals: > vees.append(c) > else: > cons.append(c) > Well, I've found a uglier solution, vees, cons = [], [] [(vees, cons)[ch in vocals].append(ch) for ch in wlist] Reinhold From darkpaladin79 at hotmail.com Thu Jun 9 00:14:47 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 00:14:47 -0400 Subject: help In-Reply-To: <1d7.3db374ed.2fd07bad@aol.com> Message-ID: -Ivan >From: Baboon1234 at aol.com >To: python-list at python.org >Subject: help >Date: Thu, 2 Jun 2005 11:11:41 EDT > >When i try to open IDLE(python GUI) it says that i have a socket error: >conection refused what do i do to fix this >-- Reinstall my friend. . .Reinstalling is the cure for everything. . . -Ivan _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From tim.golden at viacom-outdoor.co.uk Tue Jun 14 05:52:48 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Jun 2005 10:52:48 +0100 Subject: Where is Word? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8CD@vogbs009.gb.vo.local> [Guy Lateur] | I need a way to get the path where MS Word/Office has been | installed. I need | to start Word from a script (see earlier post), but it | doesn't work if I | don't know its path. So "os.system("winword.exe %s" % | fileName)" doesn't | always work; I need to say "os.system("C:\Program Files\Microsoft | Office\Office10\winword.exe %s" % fileName)". While this doesn't answer the question you're asking, I believe it does solve the problem you're facing. Relying on the fact that the Microsoft Office products will have associated themselves as the default (Open) action with files of the appropriate extensions, you can use os.startfile: import os os.startfile ("c:/temp/blah.doc") HTH TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From timr at probo.com Thu Jun 16 23:47:42 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 16 Jun 2005 20:47:42 -0700 Subject: "also" to balance "else" ? References: Message-ID: Nicolas Fleury wrote: > >But the feature is already there: > >for x in : > BLOCK1 > if : > ALSO-BLOCK > break >else: > BLOCK2 I've been using Python for 8 years. I never knew that feature was in there. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From hongqn at gmail.com Tue Jun 21 13:14:21 2005 From: hongqn at gmail.com (Qiangning Hong) Date: Wed, 22 Jun 2005 01:14:21 +0800 Subject: utf8 silly question In-Reply-To: <1374382022.20050621191607@bounce-software.com> References: <1374382022.20050621191607@bounce-software.com> Message-ID: <42B84AED.9090807@gmail.com> Catalin Constantin wrote: > i have the following code: > > c=chr(169)+" some text" > > how can i utf8 encode the variable above ? > something like in php utf8_encode($var);?! > > chr(169) is the © (c) sign ! > > 10x for your help ! > > p.s.: i tryed using codecs, etc but always get an error message > like: 'ascii' codec can't decode byte 0xa9 in position 0... ascii can not handle chr(169), so you need to use some other encoding to make unicode string first, such as latin-1. In [1]:c = chr(169) + ' some text' In [2]:u = unicode(c, 'latin-1') In [3]:u8 = u.encode('UTF-8') In [4]:u8 Out[4]:'\xc2\xa9 some text' In [5]:print u8 ? some text *NOTE*: At the last statement "print u8" I can print a UTF-8 string directly because my console is UTF-8 encoding. On your machine the © sign maybe not show. -- Qiangning Hong _______________________________ ( Do you like "TENDER VITTLES"? ) ------------------------------- o /\ ___ /\ o // \/ \/ \\ (( O O )) \\ / \ // \/ | | \/ | | | | | | | | | o | | | | | |m| |m| From johan at sege.nu Thu Jun 9 09:06:41 2005 From: johan at sege.nu (Johan =?iso-8859-1?Q?Segern=E4s?=) Date: Thu, 9 Jun 2005 15:06:41 +0200 Subject: XML + SOAP + Webservices In-Reply-To: References: Message-ID: <20050609130640.GA20963@segernas.se> On 2005-06-09 14:20 +0200 or thereabouts, Diez B. Roggisch wrote: > a way to pass a server the necessary callback information. It basically > consists of the url to talk to. That by the way is no limitation of But of course, a little slip in my thoughts. > Sooo - concluding remarks could be: > - soap and python - not so good > - if you can, use some other RPC to interface .NET - like IPython, or > win32, or even corba if you can. Basically, don't write the implementation to talk to the SOAP/WDSL-services in Python, find something else and this 'something else' produces an XML file which I then parse with Python? win32 isn't an option, we only have *nix-boxes around and we plan to stay that way. Very good answer btw, thanks alot. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rkern at ucsd.edu Fri Jun 3 01:20:13 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 02 Jun 2005 22:20:13 -0700 Subject: (OT) lincense protection generator In-Reply-To: References: <429FD59D.3020201@REMOVEMEcyber.com.au> Message-ID: Aahz wrote: > In article <429FD59D.3020201 at REMOVEMEcyber.com.au>, > Steven D'Aprano wrote: > >>Alternatively, put a lot of error checking in one >>module which you import and run at startup. Something like: >> >>try: >> import mymodule >> import databasemodule >>except: >> print "PEBCAK error, call tech support" >> sys.exit(99) > > Yeah, except it's PEBKAC. ;-) I'm pretty sure it's commutative. :-) FOLDOC says PEBCAK, Jargon File says PEBKAC, po-tay-to, po-tah-to. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From michele.simionato at gmail.com Wed Jun 15 06:12:07 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jun 2005 03:12:07 -0700 Subject: dynamic In-Reply-To: References: Message-ID: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> Having a class that returns instances of some other class is horrible, but since you asked for it: class A(object): pass class B(object): pass class Foo(object): def __new__(cls, arg): if arg=="a": return A() else: return B() print Foo("a") print Foo("b") Michele Simionato P.S. don't do it! From mwm at mired.org Thu Jun 30 18:53:16 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 30 Jun 2005 18:53:16 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: <86k6kb8nj7.fsf@bhuda.mired.org> xeys_00 at yahoo.com writes: > I posted a article earlier pertaining programming for my boss. Now I am > gonna ask a question about programming for myself. I just finished my > first C++ Class. Next semester is a class on encryption(and it's > probably gonna be a math class too). And finally back in programming in > the fall with C++ and Java 1. The C++ will cover pointers, and linked > lists, sorting algorithms, etc... I run linux and OS X. I have read in > the old days that C was used for everything. It was a systems > programming language, and also did a lot of the same stuff Bash scripts > and perl do now. So, in that era, C did it all, from short to tall. My > question is, can Python "do it all"? I am wondering what to learn as my > scripting language. I have read that perl is good up to about 250 > lines, and after that it gets kind of hairy. However, from what little > I have heard about Python, it's very well suited for readability due to > the whitespace requirements of the language, and very good for large > projects due to it's large amount of modules and it's object oriented > structure. I would like opinions as to the suitability of Python as a > general purpose language for programming unix, everything from short > scripts to muds. Thanks for your patience, opinions, and comments. As other have noted, C was never really used for everything. Unix tools were designed to connect together from the very beginning, which is what makes shell scripting so powerful. This was true before there was a C. Likewise, some things you need more control over the machine than you get in C - those are still done in assembler. These days, C compilers let you embed assembler statements in your C, so some of these things are done in such variants. Some things require you to be able to generate machine code. Those can't be done in any current implementation of Python. That doesn't mean they'll never be doable in Python - just not now. As mentioned, some things needvery explicit control over the generated machine code. Those things aren't done in C now, and will never be done in C or Python. Rather than talk about how suitable Python is for programming in general, I wanted to talk about the things you mentioned you'd be learning. Python doesn't have explicit pointers - except that every name is a pointer. That makes it hard to learn about pointers with Python. You can do data structures in Python, though. Just replace the C/C++ struct with a class, and manipulate the attributes like you'd manipulate struct members. For instance, a linked list might be represented by: class ListNode: def __init__(self, data): self.data = data self.next = None A routine that manipulated a list might look like: def cons(car, cdr): car.next = cdr Though I'd be tempted to make it a method of ListNode: def cons(self, cdr): self.next = cdr You build a list from the back to the front like so: LinkedList = cons(ListNode(1), cons(ListNode(2), ListNode(3))) or LinkedList = ListNode(1).cons(ListNode(2).cons(ListNode(3))) (this is heavily influenced by LISP; you might prever a different abstraction) and then you'd iterate over the list like so: item = LinkedList while item: Process(item.data) item = item.next Compared to a C implementation, which would look like: struct ListNode { struct ListNode *next ; void *data ; } ; and an iteration like so: struct ListNode *item ; item = &LinkedList ; while (item) { Process(item->data) ; item = item->next ; } I won't get into the details of building a list in C. It's just too ugly. Sorting is generally done on arrays, though there are methods that use lists, etc. You can study those just fine in Python. However, those are mostly of academic interest. Any computing platform worth mentioning will have a good, general-purpose sort facility available. Using that is certainly faster than writing and debugging your own. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martin.witte at gmail.com Thu Jun 16 15:13:02 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 16 Jun 2005 12:13:02 -0700 Subject: dir() with string as argument In-Reply-To: References: Message-ID: <1118949182.960884.61440@g43g2000cwa.googlegroups.com> What about martin at ubuntu:~ $ python Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py > x = __import__('sys') py > dir(x) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions'] From ptmcg at austin.rr.com Mon Jun 27 12:15:23 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Jun 2005 09:15:23 -0700 Subject: Beginner question: Converting Single-Element tuples to list References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <1119883969.197756.22140@f14g2000cwb.googlegroups.com> Message-ID: <1119888923.782530.286990@g44g2000cwa.googlegroups.com> Modified version of test program, to handle empty strings -> empty lists. import pyparsing as pp import sys def test(s): results = pp.ZeroOrMore( pp.Word(pp.alphas) ).parseString( s ) print repr(s),"->",list(results) print "Python version:", sys.version print "pyparsing version:", pp.__version__ test("abc def") test("abc") test("") Prints: Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] pyparsing version: 1.3.1 'abc def' -> ['abc', 'def'] 'abc' -> ['abc'] '' -> [] From simon.brunning at gmail.com Thu Jun 30 05:08:03 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 30 Jun 2005 10:08:03 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> Message-ID: <8c7f10c605063002083ccc1e88@mail.gmail.com> On 6/29/05, Christopher Arndt wrote: (snip) > Most of these are probably not elegible due to license issues but I'd > love to see SQLite support added to Python-out-of-the-box. Adding sqllite to the standard library has been discussed before: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fd150297c201f814 -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ognjen at mailshack.com Wed Jun 1 05:33:10 2005 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Wed, 01 Jun 2005 10:33:10 +0100 Subject: Help with Queues and Threading Message-ID: <429D80D6.2010709@mailshack.com> Hi, all Thanks all of you who helped me with the threading and queues issue. I am trying to get it working but I am having problems. When I try to run the following: cmddata = mediaplay.initcommandqueue() #initiates the Queue to send commands down mediathread = threading.Thread( target=mediaplay.mainloop, args=(cmddata) ) #starts the main loop, which will wait for a command then execute it, Queue object passed to it. threading.Thread.start(mediathread) # start the thread I get the following error: >>> Exception in thread Thread-1: Traceback (most recent call last): File "/usr/lib/python2.3/threading.py", line 436, in __bootstrap self.run() File "/usr/lib/python2.3/threading.py", line 416, in run self.__target(*self.__args, **self.__kwargs) TypeError: mainloop() argument after * must be a sequence But if I run the loop directly (i.e. not using threads, just calling the function) it works just fine. What could the problem be? From mg.mailing-list at laposte.net Fri Jun 3 12:34:54 2005 From: mg.mailing-list at laposte.net (mg) Date: Fri, 03 Jun 2005 18:34:54 +0200 Subject: Compile debug packages on windows Message-ID: <42A086AE.5070402@laposte.net> First, I compiled Python in DEBUG on Win32 with MSCV.net and the solution distributed in the Python packages. Second, I try to compiled NUMARRAY with my python debug : python_d setup.py build And the compilation crash with the following message : the file python25.lib does not exist (it is normal, because only python25_d.lib exist !) I opened the source file which include Python.h, which include pyconfig.h.located in the directory PC. Then, I found this : #ifdef MS_COREDLL # ifndef Py_BUILD_CORE /* not building the core - must be an ext */ # if defined(_MSC_VER) /* So MSVC users need not specify the .lib file in their Makefile (other compilers are generally taken care of by distutils.) */ # ifdef _DEBUG # pragma comment(lib,"python25_d.lib") # else # pragma comment(lib,"python25.lib") # endif /* _DEBUG */ # endif /* _MSC_VER */ # endif /* Py_BUILD_CORE */ #endif /* MS_COREDLL */ Then, the symbol _DEBUG need to be define... (I added at the beginning of the file: it seems to be the solution) to import the debug version instead of the release version. But, how can I run the compilation (options on the comand line maybe) which use the python25_d.lib, i.e. how the symbol _DEBUG can be defined when I write 'python_d setup.py build' ? In other words, with a Python in debug, I would generate packages in debug too and propagate the debug mode from Python to the packages... Thanks From peter at engcorp.com Sat Jun 18 12:44:45 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:44:45 -0400 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: D H wrote: > Peter Hansen wrote: >> With respect to the author, and an understanding that there is >> probably much that didn't go into his self-description (add >> "about.htm" to the above URL), it sounds as though he knows primarily, >> perhaps solely, C and C++, and has done relatively little serious >> development since he seems to have spent most of his time either >> teaching or writing (words, not source code). >> >> Does he even *know* any real high level languages such as Python? > > So you say he "has done relatively little serious development" and that > he may not even know about Python. I didn't see any evidence from those > pages to draw either conclusion. In fact the 4th paragraph quite > contradicts them both. Clearly this is a matter of opinion. Now that you've expressed yours, did you have a point to make besides that you like to contradict my posts? Maybe you'd like to take the opportunity to mention Boo? -Peter From cjbottaro at alumni.cs.utexas.edu Mon Jun 6 10:57:09 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Mon, 06 Jun 2005 09:57:09 -0500 Subject: Question about Object Oriented + functions/global vars? References: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> Message-ID: flamesrock wrote: > ok, so to my knowledge, object oriented means splitting something into > the simplest number of parts and going from there. That sounds like normal top down imperative (procedural) programming to me. > But the question is- when is it enough? Thats a judgment call on the programmer's part. > For example I have the following code: [...snip...] > would the lines with '>#' best be split up into a seperate function, > for example: > #def upload(ftp, file): [...snip...] > and then doing the call 'upload(file_id)', or is it a better practice > to leave things the way they were? I'm confused. Judgment call...=) > Finally, is it considered 'un-object-oriented' in python to have > functions inside a module that are called by objects (ie the upload > function above) and/or use global variables in combination? 1. The upload function is not an object. 2. Functions are made to be called. 3. Some people think globals should be avoided if possible. I think it depends on the size of your project and how much convenience they can give you vs. how much confusion they can potentially cause. > -thanks in advance Btw, object oriented programming is the splitting up of the program into things called object which are data and their related methods. Bah, its hard to explain, but its like instead of focusing on functions that manipulate a square, you instead have a square and its related methods. Also, I can't think of OOP without thinking of polymorphism. Ehh, this stuff is too hard for me to explain, it would be easier with examples (but too long for me to write)...=) -- C From ivanlan at pauahtun.org Mon Jun 27 15:24:12 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Mon, 27 Jun 2005 13:24:12 -0600 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: <42C0525C.A0B02082@pauahtun.org> Hi All-- Aahz wrote: > > Perhaps. But adding the time to learn those IDEs in addition to the time > to learn Java is ridiculous. I've been forced to use Java a bit to > support credit cards for our web application; I've got a friend whose > Java-vs-Python argument hinges on the use of Eclipse; I was unable to > make use of Eclipse in the time I had available for the project. > Were there _good_ reasons not to do the credit card part of the web app in Java instead of Python? As in, there is no secure module, or you didn't have time, or Python doesn't support crucial APIs? I'm very curious. > f u cn rd ths, u cn gt a gd jb n nx prgrmmng. > l tk t. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From benji at benjiyork.com Mon Jun 13 13:18:34 2005 From: benji at benjiyork.com (Benji York) Date: Mon, 13 Jun 2005 13:18:34 -0400 Subject: implicit variable declaration and access In-Reply-To: References: Message-ID: <42ADBFEA.5060904@benjiyork.com> Ali Razavi wrote: > Ali Razavi wrote: > >>Is there any reflective facility in python >>that I can use to define a variable with a >>name stored in another variable ? > Got it! use higher order functions like Lisp! No, you use higher order functions like Python. :) > code = x + '= 0' > exec(code) You should generally stay away from exec for lots of reasons. I won't elaborate but a search of this group would be informative. If you want to affect the globals (which you probably don't) you can do this: >>> x = 'my_var' >>> globals()[x] = 7 >>> my_var 7 If you want to set an attribute on a particular object (which is more likely), you can do this: >>> class C: ... pass ... >>> c = C() >>> setattr(c, x, 8) >>> c.my_var 8 > code = 'print ' + x > exec(code) Getting the value would be like this, respectively: >>> print globals()[x] 7 >>> getattr(c, x) 8 HTH -- Benji York From skip at pobox.com Wed Jun 22 22:33:54 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 22 Jun 2005 21:33:54 -0500 Subject: case/switch statement? In-Reply-To: <1119471259.814294.225130@g14g2000cwa.googlegroups.com> References: <200506131204.40950.hancock@anansispaceworks.com> <1119471259.814294.225130@g14g2000cwa.googlegroups.com> Message-ID: <17082.8082.141830.406142@montanaro.dyndns.org> Martin> The namespace issue alluded to doesn't exist when using the very Martin> similar approach suggested earlier in this thread by Andrew Martin> Durdin Sure, but I don't think I want to pay the cost of the exec statement. if/else would probably be quicker. -- shown again below in a [very] contrived example Martin> illustrating access to the local namespace: Martin> greeting = "Hello there, " Martin> x = 2 Martin> exec { Martin> 1: """greeting += 'Tom'""", Martin> 2: """greeting += 'Dick'""", Martin> 3: """greeting += 'Harry'""", Martin> }.get(x, """greeting += 'Unknown'""") Martin> print greeting Martin> Martin Martin> -- Martin> http://mail.python.org/mailman/listinfo/python-list From robin at SPAMREMOVEjessikat.fsnet.co.uk Sat Jun 4 05:30:46 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Sat, 04 Jun 2005 09:30:46 +0000 Subject: SimpleXMLRPCServer security Message-ID: <42A174C6.30804@jessikat.fsnet.co.uk> What are the security issues for an xmlrpc server with 127.0.0.1 as host? Clearly anyone with local access can connect to the server so we should protect the server and client code, but in my particular case the client starts as a cgi script and in general must be world readable/executable. Switching uid at startup allows the client code to be private; so is that a strategy for protecting the encryption/decryption which obfuscates the xmlrpc channel? Anyone done this sort of thing before? -- Robin Becker From roccomoretti at hotpop.com Thu Jun 30 09:31:53 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 30 Jun 2005 08:31:53 -0500 Subject: Add methods to string objects. In-Reply-To: References: <2fdabf19.0506300201.5fb56b59@posting.google.com> <1120134661.407265.251710@z14g2000cwz.googlegroups.com> Message-ID: Roy Smith wrote: > In article <1120134661.407265.251710 at z14g2000cwz.googlegroups.com>, > "simon.dahlbacka at gmail.com" wrote: > > >>You can even get closer, but it is NOT recommended >> >>class foostr(str): >> def plural (self): >> if self.value[-1] in "sz": >> return self.value + "es" >> else: >> return self.value + "s" >> >> >>#ugly hack >>setattr(__builtins__, "str", foostr) >> >>print str("apple").plural() >> >># this however does not work >># print "apple".plural() > > > It's fascinating that the setattr() works (and I agree with you that it's a > bad idea), but given that it does work, why doesn't it work with a string > literal? Because the string literal is the *actual* C-level builtin string type, not whatever type happens to be in __builtins__.str at the time. ("At the time" is also a tricky proposition - string literals are made into obects at compile time, before __builtins__ is twiddled with.) BTW, on setattr(): ''' setattr( object, name, value) This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123. ''' i.e. '''setattr(__builtins__, "str", foostr)''' is the same as '''__builtins__.str = foostr''', but I would agree that the setattr gives more of a "black magic" warning. From chinook.nr at tds.net Mon Jun 20 23:45:37 2005 From: chinook.nr at tds.net (Chinook) Date: Mon, 20 Jun 2005 23:45:37 -0400 Subject: Using code objects? Message-ID: <0001HW.BEDD05A1000D6CC7F00FF3B0@smtp.tds.net> Using code objects? =================== As an OO exercise I have a factory pattern that returns class objects that each have an "action" method. ClassObj.action() in turn returns a code object in my recursive process loop. I create the code objects as a one time step outside my factory pattern and potential class definitions, then reference them in my potential classes which seems to work as expected. When I create the code objects though, it seems a couple different ways work and I'm wondering which is better and why (or is there a more correct technique in this situation)? The two different ways are illustrated below: Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> def foo(st): ... print st ... >>> exp1 = 'foo("#expersion 1#")' >>> exp2 = 'foo("#expersion 2#")' >>> obj1 = compile(exp1, 'whatever', 'single') >>> exec obj1 #expersion 1# >>> obj2 = compile(exp2, 'whatever', 'exec') >>> exec obj2 #expersion 2# >>> Thank you, Lee C From philippe at philippecmartin.com Tue Jun 21 16:04:09 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 21 Jun 2005 20:04:09 GMT Subject: UML to Python/Java code generation References: Message-ID: Try this: http://uml.sourceforge.net/index.php Regards, Philippe Maurice LING wrote: > Hi, > > Is there any UML tools that is able to take UML and generate Python codes? > > Cheers > Maurice From andreas at kostyrka.org Wed Jun 15 09:12:37 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 15 Jun 2005 15:12:37 +0200 Subject: FAQ: __str__ vs __repr__ In-Reply-To: <42b021ba$1@griseus.its.uu.se> References: <42b021ba$1@griseus.its.uu.se> Message-ID: <20050615131237.GA29482@heaven.kostyrka.org> Well, It means that eval(repr(x)) == x if at all possible. Basically: repr('abc') -> 'abc' str('abc') -> abc You'll notice that 'abc' is a valid python expression for the string, while abc is not a valid string expression. Andreas On Wed, Jun 15, 2005 at 02:46:04PM +0200, Jan Danielsson wrote: > Sorry, but I Just Don't Get It. I did search the 'net, I did read the > FAQ, but I'm too dumb to understand. > > As far as I can gather, __str__ is just a representation of the > object. For instance: > > class ServerConnection: > def __str__(self): > buf = "Server: " + self.name + "\n" > buf += "Sent bytes: " + str(self.sentBytes) + "\n" > buf += "Recv bytes: " + str(self.recvBytes) + "\n" > return buf > > However, I don't understand what __repr__ should be. There's a phrase > in the documentation which makes it highly confusing for a beginner like > me: "If at all possible, this should look like a valid Python expression > that could be used to recreate an object with the same value (given an > appropriate environment).". What does that mean? Does it mean that I > should return: > > def __str__(self): > buf = "self.name=" + self.name + "\n" > buf += "self.sentBytes=" + str(self.sentBytes) + "\n" > buf += "self.recvBytes=" + str(self.recvBytes) + "\n" > return buf > > ..or is there some other "valid Python expression" format which I > have yet to encounter? > -- > http://mail.python.org/mailman/listinfo/python-list From mhoy4 at cox.net Mon Jun 13 14:16:03 2005 From: mhoy4 at cox.net (Mike) Date: Mon, 13 Jun 2005 11:16:03 -0700 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: <42ADCD63.3030906@cox.net> >there should be no room for "magic" in a computer >for a professional programmer. > well put. sounds like the makings of a good signature... From mwm at mired.org Fri Jun 10 18:50:15 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 10 Jun 2005 17:50:15 -0500 Subject: Is pyton for me? References: Message-ID: <867jh16d3s.fsf@guru.mired.org> "Mark de+la+Fuente" writes: > I need to write simple scripts for executing command line functions. > Up till now I've used C-Shell scripts for this, but I'm looking for > a better alternative. And I keep reading about how ?easy? it is to > program with python. Lots of answers - but everyone concentrated on telling you how to do what you were trying to do, and no one answered your question. Which is actually typical of the c.l.python, but may not be what you want. As others pointed out, Python isn't a shell, or even a shell scripting language, so it doesn't handle what you're doing in a "natural" way. Because of that, it may not be the language for you. Python has features that work well for building large systems, but those tend to cause extra work when you want to do things that other languages make simple. One thing you might consider is changing shells. See for reasons why you might want to drop csh. There's a similar paper discussing the problems with later versions of sh (bash, late ksh, etc.), but from what I recall the problems mostly come from trying to use the extra features that have been added to those shells. So when writing sh scripts, I tend to stay with fundamental bourne features. Other languages have less overhead in invoking external commands. Rexx and Perl come to mind. You might want to give them a look. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From randy at randyedmonds.com Fri Jun 17 15:19:41 2005 From: randy at randyedmonds.com (randy) Date: 17 Jun 2005 12:19:41 -0700 Subject: Please help me understand this code.... Message-ID: <1119035981.924689.139880@f14g2000cwb.googlegroups.com> Hello, I am a programmer, but not a python guy. So I am a little confused with the following python code. Specifically what does the ":" do in the array arithmetic? new_page = map[opage] old_page = map[opage^1] center = new_page[1:-1,1:-1] origcenter = array(center) center[:] = old_page[2:,2:] center += old_page[1:-1,2:] center += old_page[:-2,2:] center += old_page[2:,1:-1] center += old_page[:-2,1:-1] center += old_page[2:,:-2] center += old_page[1:-1,:-2] center += old_page[:-2,:-2] center >>= 2 center -= origcenter center -= (center>>density) Thanks!! Randy From me at privacy.net Wed Jun 29 11:22:22 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 29 Jun 2005 11:22:22 -0400 Subject: Reading output from a child process non-blockingly References: Message-ID: On Wed, 29 Jun 2005 15:45:20 +0200, Thomas Guettler wrote: > Check out.log with "tail" or "less +F". Do you see the data appear in > small chunks? ... You'll need "tail -f", I think. Regards, Dan -- Dan Sommers From ptmcg at austin.rr.com Wed Jun 15 21:18:27 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Jun 2005 18:18:27 -0700 Subject: splitting delimited strings References: Message-ID: <1118884707.001324.305180@g49g2000cwa.googlegroups.com> Mark - Let me weigh in with a pyparsing entry to your puzzle. It wont be blazingly fast, but at least it will give you another data point in your comparison of approaches. Note that the parser can do the string-to-int conversion for you during the parsing pass. If @rv@ and @pv@ are record type markers, then you can use pyparsing to create more of a parser than just a simple tokenizer, and parse out the individual record fields into result attributes. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul test1 = "@hello@@world@@foo at bar" test2 = """@rv@ 2 @db.locks@ @//depot/hello.txt@ @mh@ @mh@ 1 1 44 @pv@ 0 @db.changex@ 44 44 @mh@ @mh@ 1118875308 0 @ :@@: :@@@@: @""" from pyparsing import * AT = Literal("@") atQuotedString = AT.suppress() + Combine(OneOrMore((~AT + SkipTo(AT)) | (AT + AT).setParseAction(replaceWith("@")) )) + AT.suppress() # extract any @-quoted strings for test in (test1,test2): for toks,s,e in atQuotedString.scanString(test): print toks print # parse all tokens (assume either a positive integer or @-quoted string) def makeInt(s,l,toks): return int(toks[0]) entry = OneOrMore( Word(nums).setParseAction(makeInt) | atQuotedString ) for t in test2.split("\n"): print entry.parseString(t) Prints out: ['hello at world@foo'] ['rv'] ['db.locks'] ['//depot/hello.txt'] ['mh'] ['mh'] ['pv'] ['db.changex'] ['mh'] ['mh'] [':@: :@@: '] ['rv', 2, 'db.locks', '//depot/hello.txt', 'mh', 'mh', 1, 1, 44] ['pv', 0, 'db.changex', 44, 44, 'mh', 'mh', 1118875308, 0, ':@: :@@: '] From steve at REMOVEMEcyber.com.au Thu Jun 23 23:40:33 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 24 Jun 2005 13:40:33 +1000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> Message-ID: <42BB80B1.70202@REMOVEMEcyber.com.au> Tim Peters wrote: > [Steven D'Aprano] >>It isn't necessary to look at complex numbers to see the difference >>between positive and negative zero. Just look at a graph of y=1/x. In >>particular, look at the behaviour of the graph around x=0. Now tell me >>that the sign of zero doesn't make a difference. > > > OK, I looked, and it made no difference to me. Really. If I had an > infinitely tall monitor, maybe I could see a difference, but I don't > -- the sign of 0 on the nose makes no difference to the behavior of > 1/x for any x other than 0. On my finite monitor, I see it looks like > the line x=0 is an asymptote, and the graph approaches minus infinity > on that line from the left and positive infinity from the right; the > value of 1/0 doesn't matter to that. Well, I didn't say that the value of zero made a difference for _other_ values of x. Perhaps you and I are interpreting the same graph differently. To me, the behaviour of 1/x around x = 0 illustrates why +0 and -0 are different, but it isn't worth arguing about. >>Signed zeroes also preserve 1/(1/x) == x for all x, > > > No, signed zeros "preverse" that identity for exactly the set {+Inf, > -Inf}, and that's all. Preverse? Did you mean "pervert"? Or just a mispelt "preserve"? Sorry, not trying to be a spelling Nazi, I genuinely don't understand what you are trying to get across here. > That's worth something, but 1/(1/x) == x isn't > generally true in 754 anyway. Of course it isn't. Sorry, I was thinking like a mathematician instead of a programmer again. (Note to self: write out 1000 lines, "Real number != floating point number".) [snip] >>>Odd bit o' trivia: following "the rules" for signed zeroes in 754 >>>makes exponeniation c**n ambiguous, where c is a complex number with >>>c.real == c.imag == 0.0 (but the zeroes may be signed), and n is a >>>positive integer. The signs on the zeroes coming out can depend on >>>the exact order in which multiplications are performed, because the >>>underlying multiplication isn't associative despite that it's exact. >> > >>That's an implementation failure. Mathematically, the sign of 0**n should >>depend only on whether n is odd or even. If c**n is ambiguous, then that's >>a bug in the implementation, not the standard. > > > As I said, these are complex zeroes, not real zeroes. The 754 > standard doesn't say anything about complex numbers. In rectangular > form, a complex zero contains two real zeroes. There are 4 > possiblities for a complex zero if the components are 754 > floats/doubles: > > +0+0i > +0-0i > -0+0i > -0-0i > > Implement Cartesian complex multiplication in the obvious way: > > (a+bi)(c+di) = (ac-bd) + (ad+bc)i Yes, but that supports what I said: it is an _implementation_ issue. A different implementation might recognise a complex zero and return the correctly signed complex zero without actually doing the multiplication. Assuming mathematicians can decide on which complex zero is the correct one. > Now use that to raise the four complex zeroes above to various integer > powers, trying different ways of grouping the multiplications. For > example, x**4 can be computed as > > ((xx)x)x > > or > > (xx)(xx) > > or > > x((xx)x) > > etc. You'll discover that, in some cases, for fixed x and n, the > signs of the zeroes in the result depend how the multiplications were > grouped. The 754 standard says nothing about any of this, _except_ > for the results of multiplying and adding 754 zeroes. Multiplication > of signed zeroes in 754 is associative. The problem is that the > extension to Cartesian complex multiplication isn't associative under > these rules in some all-zero cases, mostly because the sum of two > signed zeroes is (under 3 of the rounding modes) +0 unless both > addends are -0. Try examples and you'll discover this for yourself. Yes, point taken. But that is just another example of where floats fail to be sufficiently close to real numbers. In a "perfect" representation, this would not be a factor. However... now that I think of it... in polar form, there are an uncountably infinite number of complex zeroes. z = 0*cis(0), z = 0*cis(0.1), z = 0*cis(-0.21), ... I think I won't touch that one with a fifty foot pole. -- Steven. From roy at panix.com Sun Jun 19 08:19:08 2005 From: roy at panix.com (Roy Smith) Date: Sun, 19 Jun 2005 08:19:08 -0400 Subject: Is there something similar to ?: operator (C/C++) in Python? References: Message-ID: , Bo Peng wrote: > I have around 10 of them. Using these if/else, it will take 50 lines for > a function call. It also bothers me to have 10 variables left in the > namespace, in addition to finding 10 meaningful names. If you've got 10 different conditional branches in a single function, that's pretty messy logic no matter what language you write it in or what syntactic sugar you've got to let you write it compactly. Can you give us some idea of what it is that you're trying to do? It pretty unusual to see a requirement like that. > The FAQ provides two solutions, neither of them are elegant. I guess I > will use if/else for reasability purpose. I agree that the and/or hack is ugly, and I generally stay away from it because I think if/else is easier to read and understand. But if you've got 10 of them, the compactness (and, as you say, avoiding having to create 10 temp variables) of the and/or probably means the hack is worth doing. Somthing like: myComplicatedFunction (cond1 and value1a or value1b, cond2 and value2a or value2b, cond3 and value3a or value3b, cond4 and value4a or value4b, cond5 and value5a or value5b, cond6 and value6a or value6b, cond7 and value7a or value7b, cond8 and value8a or value8b, cond9 and value9a or value9b, cond10 and value10a or value10b) is kind of ugly, but at least you only have to understand what's going on with the and/or ONCE, and then you can apply that understanding to the 10 repetitions of the construct. Having 50 lines of if/else makes it much harder to get your head around what's going on. From steve at REMOVETHIScyber.com.au Sun Jun 12 13:41:37 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 03:41:37 +1000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42ABAB62.4040205@lexicon.net> Message-ID: On Sun, 12 Jun 2005 08:11:47 -0400, Roy Smith wrote: > The point I was trying to make was that as computer science progresses, > stuff that was really important to know a lot about becomes more and more > taken for granted. This is how we make progress. > > I used to worry about memory busses at the milivolt and microsecond level. > I knew about termination impedances and wired-OR logic, and power budgets > and all that good stuff. Today all I know about memory is you go to > www.crucial.com, type in your Visa card number, and the nice UPS guy shows > up with some SIMMs in a few days. Yes. But (to a first approximation) memory either works or it doesn't. And we never need to worry about it scaling, because you don't get to assemble your own SIMMs -- you buy them pre-made. Software is nothing like that. [snip] > Just like you can't even begin to think about building today's > GUI-driven desktop applications if you're still worrying about > individual logic gates, you can't begin to think about solving some of > these really hard problems (and others we haven't even imagined) if > you're still worrying about memory buffer reference counting and garbage > collection. Yesterday's research projects are today's utilities and > tomorrow's historical footnotes. Nice in theory, but frequently breaks down in practice. Let's take a nice, real, Python example: I write an text-handling application in Python. I've taken your advice, and don't worry about messy details about the language implementation, and concentrated on the application logic. Consequently, I've used the idiom: new_text = "" for word in text: new_text = new_text + process(word) I test it against text containing a few thousand words, and performance is good. Then my customers use my application in the real world, using texts of a few hundreds of millions of words, and performance slows to a painful crawl. Python does a good job of insulating the developer from the implementation details, but even in Python those details can sometimes turn around and bite you on the behind. And your users will discover those bum-biting situations long before your testing will. Joel of "Joel On Software" discusses this issue here: http://www.joelonsoftware.com/articles/fog0000000319.html Of course, we should not prematurely optimise. But we should also be aware of the characteristics of the libraries we call, so we can choose the right library. Fortunately, a high-level language like Python makes it comparatively easy to refactor a bunch of slow string concatenations into the list-append plus string-join idiom. -- Steven. From timothy.williams at nvl.army.mil Mon Jun 13 10:49:01 2005 From: timothy.williams at nvl.army.mil (timothy.williams at nvl.army.mil) Date: 13 Jun 2005 07:49:01 -0700 Subject: Tk() doesn't bring up a window in Python2.4 Message-ID: <1118674141.504500.255150@o13g2000cwo.googlegroups.com> Hello. I recently installed Python2.4 on both Linux (Redhat FC3) and Windows XP. The build and installed went fine as far as I could tell. I Windows, when I bring up IDLE, or pythonwin, I can't bring up a new Frame widget with Tk(). If I use idle from a DOS window, everything's fine. Python programs I have that use Tkinter also work from either IDLE. Thanks for any help. From osv at javad.ru Fri Jun 24 11:09:05 2005 From: osv at javad.ru (Sergei Organov) Date: 24 Jun 2005 19:09:05 +0400 Subject: Favorite non-python language trick? References: Message-ID: Steven D'Aprano writes: > On Fri, 24 Jun 2005 00:55:38 -0600, Joseph Garvin wrote: > > > I'm curious -- what is everyone's favorite trick from a non-python > > language? And -- why isn't it in Python? > > Long ago, I used to dabble in Forth. You could say, the entire Forth > language was a trick :-) It was interesting to be able to define your own > compiler commands, loop constructs and so forth. > > One of the things I liked in Pascal was the "with" keyword. You could > write something like this: > > with colour do begin > red := 0; blue := 255; green := 0; > end; > > instead of: > > colour.red := 0; colour.blue := 255; colour.green := 0; > > Okay, so maybe it is more of a feature than a trick, but I miss it and it > would be nice to have in Python. ... that quickly becomes quite messy: with A do begin ..... with B do begin ..... with C do begin x := y; end; end; end; ... and now you need to check the declarations of C, B, and A to actually see what is assigned to what. Worse yet, adding field 'x' to 'C' will (silently) break the code :( I don't think it would be that nice to have it in Python. -- Sergei. From fred at adventistcare.org Mon Jun 27 16:03:35 2005 From: fred at adventistcare.org (Sells, Fred) Date: Mon, 27 Jun 2005 16:03:35 -0400 Subject: Running Python interpreter in Emacs Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317534@sunbelt.org> It works for me in W2000; I have an ancient .emacs file that someone gave me that I use on each new system, wheter unix or windows and have never had a problem. It usually has to be installed at C:/ to work, unless you understand emacs better than I. I've inserted the file ".emacs" below, for those who have attachment blocking. I make no guarantees, nor do I understand it, I just use it: ---------------------------------snip--------------------------------------- --------------- (setq initial-major-mode 'c-mode) (setq text-mode-hook 'turn-on-auto-fill) (setq-default indent-tabs-mode nil) (global-set-key "\C-z" 'narten-suspend-emacs) (global-set-key "\C-_" 'help-command) (setq help-char 31) (define-key global-map "\C-h" 'backward-delete-char-untabify) (global-set-key "\C-x\C-e" 'compile) (global-set-key "\C-x1" 'my-delete-other-windows) (setq manual-program "man") (setq manual-formatted-dir-prefix (list "/usr/man/cat" "/usr/local/X11R4/man")) (setq manual-formatted-dirlist (list "/usr/man/cat1" "/usr/man/cat2" "/usr/man/cat3" "/usr/man/cat4" "/usr/man/cat5" "/usr/man/cat6" "/usr/man/cat7" "/usr/man/cat8" "/usr/man/catl" "/usr/man/catn" "/usr/local/X11R4/man/catn" "/usr/local/X11R4/man/cat3" )) (global-set-key "\em" 'manual-entry) (global-set-key "\eg" 'goto-line) (global-set-key "\C-xb" 'my-switch-to-buffer) (global-set-key "\C-m" 'newline-and-indent) (global-set-key "\C-q" 'electric-buffer-list) (global-set-key "\C-x\C-b" 'buffer-menu) (global-set-key "\C-x\C-y" 'cd) (global-set-key "\es" 'shell) (global-set-key "\C-xd" 'display-filename) (global-set-key "\C-i" 'narten-do-a-tab) (global-set-key "\C-x\C-b" 'buffer-menu) (global-set-key "\C-_\C-_" 'help-for-help) (global-set-key "\C-_\C-a" 'apropos) (global-unset-key "\C-_\C-c") (global-unset-key "\C-_\C-d") (global-unset-key "\C-_\C-n") (global-unset-key "\C-_\C-w") (defun my-delete-other-windows () (interactive) (delete-other-windows) (recenter)) (defun narten-suspend-emacs () (interactive) (save-all-buffers) (suspend-emacs)) (defun narten-do-a-tab () (interactive) (cond ((looking-at "^") (progn (delete-horizontal-space) (indent-relative))) ((looking-at "[ \t]*") (tab-to-tab-stop))) (let ((beg (point))) (re-search-backward "[^ \t]") (tabify (point) beg)) (re-search-forward "[ \t]+")) (defun display-filename () (interactive) (message buffer-file-name)) (defun save-all-buffers () (interactive) (save-some-buffers 1) (message "done!")) (defun my-switch-to-buffer () "switch to buffer, using completion to prevent bogus buffer names from being given" (interactive) (switch-to-buffer (read-buffer "Switch to buffer: " (other-buffer) "t"))) ;;; ;;; GNUS stuff ;;; (setq gnus-nntp-server "astro") (setq gnus-your-domain "sunrise.com") (setq gnus-your-organization "Sunrise Software International") (setq display-time-day-and-date t) (setq display-time-no-load t) (setq display-newmail-beep t) (display-time) ;;(setq-default tab-width 4 );;;;;;;;;;;;;;;;fred (put 'narrow-to-region 'disabled nil) (put 'narrow-to-page 'disabled nil) (put 'insert-file 'disabled nil) (autoload 'python-mode "python-mode" "" t) (setq auto-mode-alist (cons '("\\.py$" . python-mode) auto-mode-alist)) ;;(my-delete-other-windows) ;;(electric-buffer-list) ;;(cond (window-system ;; (setq hilit-mode-enable-list '(not text-mode) ;; hilit-background-mode 'light ;; hilit-inhibit-hooks nil ;; hilit-inhibit-rebinding nil) ;; ;; (require 'hilit19) ;; )) ;; ;; Hilit stuff ;; ;;(cond (window-system ;; (setq hilit-mode-enable-list '(not text-mode) ;; hilit-background-mode 'light ;; hilit-inhibit-hooks nil ;; hilit-inhibit-rebinding nil) ;; ;; (require 'hilit19) ;; )) ;;(require 'paren) (setq-default transient-mark-mode t) ;;(electric-buffer-menu-mode) (my-delete-other-windows) ----------------------------------------snip ends-------------------------------------------------------------- -----Original Message----- From: Rex Eastbourne [mailto:rex.eastbourne at gmail.com] Sent: Sunday, June 26, 2005 2:49 PM To: python-list at python.org Subject: Re: Running Python interpreter in Emacs I went to My Computer | Properties | Advanced | Environment Variables and added c:\program files\python24 to both the PYTHONPATH and Path variables. Still no luck. I don't know whether the path I'm talking about is the same as the $PATH you referred to, or whether I'm supposed to put python.exe explicitly somewhere; could someone refer me to a place where I can read about these things? Thanks! Rex -- http://mail.python.org/mailman/listinfo/python-list --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From jeffelkins at earthlink.net Sat Jun 4 09:24:25 2005 From: jeffelkins at earthlink.net (Jeff Elkins) Date: Sat, 4 Jun 2005 09:24:25 -0400 Subject: Walking through a mysql db Message-ID: <200506040924.25574.jeffelkins@earthlink.net> I'm writing a small wxpython app to display and update a dataset. So far, I get the first record for display: try: cursor = conn.cursor () cursor.execute ("SELECT * FROM dataset") item = cursor.fetchone () Now, how do I step through the dataset one row at a time? My form has 'next' and 'back' buttons, and I'd like them to step forward or back, fetching the appropriate row in the table. I've tried setting cursor.rownumber by incrementing it prior to the fetchone() w/o effect. Thanks for any pointers. Jeff Elkins From xeys_00 at yahoo.com Mon Jun 27 14:51:21 2005 From: xeys_00 at yahoo.com (xeys_00 at yahoo.com) Date: 27 Jun 2005 11:51:21 -0700 Subject: Boss wants me to program Message-ID: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> I'm a manager where I work(one of the cogs in a food service company). The boss needed one of us to become the "tech guy", and part of that is writing small windows programs for the office. He wants the development work done in house, and he knows I am in school for a CS minor. I know basic C++(Part 2 of that is in the fall), and I will be taking Java 1 in the fall also. What is the easiest way for me to make windows programs that will do basic things like(Inventory, Menu Management, etc...)? I have heard visual basic is where it's at. I want to keep an open mind though, so I am wondering if python could be an option. The programs have no speed requirement. But they must be pretty, and not confuse my boss. Plus he wants well documented help for each function. I asked the windows programming group, but I thought I would ask here also. Thanks. Xeys From robin at reportlab.com Thu Jun 2 05:26:54 2005 From: robin at reportlab.com (Robin Becker) Date: Thu, 02 Jun 2005 10:26:54 +0100 Subject: BUG pythonw vs subprocess In-Reply-To: <7xfyw1zzt1.fsf@ruckus.brouhaha.com> References: <429DFB8B.4090102@jessikat.fsnet.co.uk> <7xfyw1zzt1.fsf@ruckus.brouhaha.com> Message-ID: <429ED0DE.7000805@chamonix.reportlab.co.uk> Paul Rubin wrote: > I thought pythonw didn't provide a console and so it could be that > stdin and stdout aren't connected to anything. Popen therefore doesn't > make sense. You have to use sockets or something. Well my example is explicitly using PIPE for stderr & stdin, but I don't know how to tell it to ignore stdin. The value None seems to be used to signal that the existing stdin is used and that fails. I believe the solution is just to use PIPE for stdin as well and then I don't have to write to it. -- Robin Becker From davecook at nowhere.net Thu Jun 2 04:36:26 2005 From: davecook at nowhere.net (Dave Cook) Date: Thu, 02 Jun 2005 08:36:26 GMT Subject: Newbie Here References: Message-ID: On 2005-05-31, Mark Sargent wrote: > for the same things, what do you primarily use it for. Could you show me Web apps using nevow/twisted for work, and pygtk apps for fun. You might browse around sourceforge a bit: http://sourceforge.net/softwaremap/trove_list.php?form_cat=178 Dave Cook From snail at objmedia.demon.co.uk Sat Jun 11 15:09:16 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Sat, 11 Jun 2005 20:09:16 +0100 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <5F+iClJcbzqCFw0u@objmedia.demon.co.uk> In message , EP writes >> that means) and are going crazy throwing around the Java buzzwords (not to >> mention XML). Sounds like someone has read about AJAX and decided that is what is next. They probably put 2 and 2 together and came up with 5 thinking the J stands for Java rather than Javascript and that your sever end must be Java. Well if they really want performance play the C++ (or assembler!) trump card and watch them squirm :-) I think you best approach is some serious education of upper management on the benefits and pitfalls of each language, and of switching languages. Also point out the huge costs: o Total write-off of all development costs of V1.0. o Total write off of all intellectual property assets of V1.0 (well if you are building V2.0 on something else, you've put V1.0 in the bin with zero re-use) o Total slap in the face and moral-crusher to the development team and support staff for V1.0. You will most likely see an exodus of talented staff after the change, if it happens. o Effectively starting from ground-zero, making the cost for implementing V2.0 the entire development cost, rather than the incremental cost for the jump to V2.0 from V1.0 using the existing language. The costs in human, timescale and financial terms for what these people are proposing are huge. This company may not survive the change. If they change you may want to consider the "abandon ship" approach and find a more reliable place to devote you skills to. Finally, read "The Peter Principle" and realise there are people like these with their sights set on getting to the top of the greasy pole without any consideration for the damage they cause to others. You need to identify such people and steer clear of them (they generally do not infect all companies). All the best. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From marcus.alanen at abo.fi Sun Jun 12 07:24:45 2005 From: marcus.alanen at abo.fi (Marcus Alanen) Date: Sun, 12 Jun 2005 14:24:45 +0300 Subject: Sending mail from 'current user' in Python In-Reply-To: <863brp6c11.fsf@guru.mired.org> References: <3gsve7Fe8957U1@individual.net> <863brp6c11.fsf@guru.mired.org> Message-ID: <42AC1B7D.8090502@abo.fi> Mike Meyer wrote: > BTW, an alternative for the username is the USER environment > variable. I don't know whether or not it exists on Windows. Or LOGNAME. Don't about windows, though. >>I've also tried opening a pipe to sendmail, and feeding the >>message to that instead. This too works great (and does give an >>appropriate default 'From'), but that also turns my problem into >>the problem of finding the location of the sendmail program, >>which doesn't seem like much of an improvement, portability-wise. > Well, you could provide a list of places to look for it. But you're > right, this doesn't help much with portability. No, but at least it can be expected to do the right thing w.r.t. sending the mail. >>Finally, if at all possible I'd also like to get this working on >>Windows, so I'd rather stick with the standard smtplib if I can. > smtplib needs an SMTP server to connect to. For unix systems, this is > typically localhost. What do you use for Windows systems? Or are you > connecting to your machine to deliver the mail? I'd be very surprised if the typical SMTP server is localhost on unix-like computers. Rather, sendmail is configured to transport the message to company/university mailserver(s). If that happens to fail, the mail is put on the queue at localhost, and transported later (e.g. via a cronjob) to the server. At no point is there a server on localhost involved. Of course, not everybody's computer is on such a network and a sendmail server may indeed be running on localhost, but that's not a very informed guess. Let the sendmail program take care of those details. The Unix Programming Frequently Asked Questions "Q5.2 What's the best way to send mail from a program?" is worth reading. I'd try some simple autodetection (Mike's suggestion sounded great) and prompt the user to correct the information, although sendmail itself ought to give good defaults, so this might not be necessary. Then try /usr/sbin/sendmail, /usr/libexec/sendmail and /usr/lib/sendmail. You could try using exitcode 127 to detect "program could not be found or executed" but I don't know how portable that is. I can't comment on the Windows side of things. Regards, Marcus From gcholakidis at hotmail.com.spam-remove Tue Jun 14 03:29:01 2005 From: gcholakidis at hotmail.com.spam-remove (Grigoris Tsolakidis) Date: Tue, 14 Jun 2005 10:29:01 +0300 Subject: extending Python base class in C References: Message-ID: There was good article of how to do this on DDJ home page www.ddj.com "harold fellermann" wrote in message news:mailman.378.1118678951.10512.python-list at python.org... Hi all, I once read that it is possible to use a python base class for a C extension class. To be precise, I want to achieve the following behavior: class PythonClass : pass class CClass(PythonClass) : "this class should be implemented as C extension" pass Unfortunately, google could not find me the right reference. Does anyone know how to do it, or where I can find relevant information? Thanks, - harold - -- Je me suis enferm? dans mon amour -- je r?ve. -- Paul Eluard From eurleif at ecritters.biz Fri Jun 24 18:28:46 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 24 Jun 2005 22:28:46 GMT Subject: a dictionary from a list In-Reply-To: <2133494.bAtaJnSUkF@teancum> References: <2133494.bAtaJnSUkF@teancum> Message-ID: David Bear wrote: > Is there an easy way to create a dictionary object with the members of > 'alist' being the keys in the dictionary, and the value of the keys set to > null? adict = dict.fromkeys(alist) From hancock at anansispaceworks.com Sat Jun 11 14:46:39 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 11 Jun 2005 13:46:39 -0500 Subject: Any way to not create .pyc files? In-Reply-To: References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: <200506111346.39365.hancock@anansispaceworks.com> On Saturday 11 June 2005 06:14 am, Piet van Oostrum wrote: > >>>>> Terry Hancock (TH) wrote: > >TH> It looks to me like Python just deleted a read-only file owned by > >TH> root in order to replace it with a new pyc file. Can somebody > >TH> explain that to me?! Isn't that supposed to be impossible? > > If the directory is writable, you can delete a file and write a new one > with the same name. The permissions of the file itself are of no importance > in this case. Yeah, I guess that must be so. I wonder why I never noticed it, though. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From drobinow at gmail.com Thu Jun 23 13:04:32 2005 From: drobinow at gmail.com (drobinow at gmail.com) Date: 23 Jun 2005 10:04:32 -0700 Subject: os.system(cmd) isn't working In-Reply-To: References: Message-ID: <1119546272.468604.245950@z14g2000cwz.googlegroups.com> If firefox is not your default browser, os.system(r'"cd c:\Program Files\Mozilla Firefox & firefox "' + '"www.blendertechnologies.com"') works for me. From philippe at philippecmartin.com Sat Jun 4 17:53:14 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 04 Jun 2005 21:53:14 GMT Subject: csv and iterator protocol Message-ID: Hi, I have the following working program: 1) I import data in csv format into internal data structures (dict + list) 2) I can export back to csv 3) I can store my internal data using pickle+bz2 4) I can reload it. Hovever I notice a factor 10 size loss using pickle. So I would like to bzip/store in csv format but am not certain how to read the data back as the csv module as described uses a file name in its constructor. I would like to avoid reading the data and writing it into a file prior to re-importing it. Can I initialize csv with input data stored in RAM (ex: a string) ? - so far I cannot get that to work. Or to rephrase the question, what Python "RAM" structure supports the "iterator protocol" ? Thanks, Philippe From mwm at idiom.com Tue Jun 21 23:26:06 2005 From: mwm at idiom.com (Mike Meyer) Date: 21 Jun 2005 20:26:06 -0700 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: <5jy893qdgx.fsf@idiom.com> Steven D'Aprano writes: > On Sat, 18 Jun 2005 15:00:02 +0200, Renato Ramonda wrote: > Hiding the source code does not make software more secure. Any bugs and > security holes will be there whether the software is distributed in source > code, object code, or something in between. I'm going to be pedantic about this. One definition of "more secure" is "has fewer security holes". With that definition, hiding your source code doesn't make any difference. Another definition of "more secure" is "has a higher cost to break into." By that definition, hiding your source code *does* make your software more secure. It's easier to find security holes by examining source near "insecure" operations than it is by trial and error. On the flip side, Thompson has shown that distributing source is not a preventative for trojans. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From almad at include.cz Tue Jun 14 05:45:30 2005 From: almad at include.cz (Almad) Date: Tue, 14 Jun 2005 11:45:30 +0200 Subject: ZCatalog for standalone Zodb? Message-ID: Hello, is ZCatalog available for standalone zodb? As far as I read tutorial, the relation to zope is obvious. I knew there is IndexedCatalog, but its not developed any more...and without indexing, oodbms are unusable for cms, imo. Thank You, -- Lukas "Almad" Linhart [:: http://www.almad.net/ ::] From tjreedy at udel.edu Thu Jun 9 12:08:18 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Jun 2005 12:08:18 -0400 Subject: Abstract and concrete syntax References: <11af9le2v96r1ac@news.supernews.com> Message-ID: "David Baelde" wrote in message news:pan.2005.06.09.10.58.11.232401 at ens-lyon.fr... > > Well, thanks for the answers. I guess the fact is that python does not > want to be a functional programming language. Correct. Python is a procedural, functional, OO language. > I agree that statements as expressions could allow obscure code. Guido considered (and, I presume, still considers) the distinction between statement and expression to be a feature, not a wart. Most Python functions do things that in Lisp require 'special forms' (or builtin macros, or whatever, in a particular version) with special quoting rules. For instance, if assignment were done in an expression, the targets would have to be quoted to avoid having them evaluated. Or the assignment expression would have to be a 'special expression' that did not evaluate all its terms (like setq in some (just older?) lisps). In Python, that 'special expression', with its 'quote, don't evaluate, targets' rule, is a statement! >The design of programming languages is a complicated thing... To make everything hang together, yes. Terry J. Reedy From pinard at iro.umontreal.ca Sat Jun 4 08:24:08 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sat, 4 Jun 2005 08:24:08 -0400 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117865294.079503.51230@o13g2000cwo.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <1117865294.079503.51230@o13g2000cwo.googlegroups.com> Message-ID: <20050604122408.GB6927@phenix.progiciels-bpi.ca> [Paddy] > If you still must have something like the c preprocessor > then unix has m4 (and it seems there is a windows version > http://gnuwin32.sourceforge.net/packages/m4.htm). The difficulty of `m4' for Python source is that macro expansions should be accompanied with proper adjustment of indentation, for adapting to the context where macros are getting expanded. Ren? Seindal's `m4' is surprisingly powerful, so maybe that with enough trickery (I really mean: a _lot_ of trickery), adjustment of indentation could be possible. And maybe that a simpler `m4' approach to Python macro-expansion could be made available through the later pluggin features which Ren? added to `m4'. (Yet I do not know if the pluggin features have been integrated in the `m4' distribution mainstream.) It would be much easier using `m4' for Python, if there was a way to invoke it after Python lexer and before further parsing, because and tokens would already been identified. If this was possible, `m4' would be a breeze to use as a pre-processor for Python. Still in this dreaming mode, there would also be one necessary detail missing for full comfort: that is, the recognition of `#line' like directives as generated by `m4' so Python tracebacks, for example, would correctly refer to the Python source lines before macro-expansion. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From noreply at gcgroup.net Thu Jun 16 14:01:00 2005 From: noreply at gcgroup.net (William Gill) Date: Thu, 16 Jun 2005 18:01:00 GMT Subject: access properties of parent widget in Tkinter In-Reply-To: <42b1ba13$1_2@newspeer2.tds.net> References: <42b17114$1_2@newspeer2.tds.net> <42b1ba13$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > William Gill wrote: > >> Kent Johnson wrote: >> >> If I change the area code in one record only the phonenumber table >> needs to be updated, but since areaCode is a child of phones, >> phones.hasChanged needs to be set to True by the areaCode entry widget. > > > One possibility is for the phones.hasChanged to poll the hasChanged > attributes of its children. In other words, instead of propagating > hasChanged up when a change occurs, poll the dependent widgets when you > need to know. > > Another way would be to pass a calllback to the child widget that it > calls when it is changed, or to set up some kind of event mechanism. In > Java I often set the parent to monitor property change events of the child. > >> >> > Personally I think it is bad design for a widget to assume anything >> > about its enclosing environment. What about passing a StringVar or >> > IntVar to the child widget and letting it work with that? >> >> This is not a criticism, but how is passing a known intVar or >> stringVar any different than designing with the knowledge that an >> areaCode widget can not exist except as a child of phonenumber? > > > When you pass a stringVar to the child, it knows only what it is told, > it is not assuming that some incantation on its parent will do the right > thing. This has a direct effect on reusability of the child in other > contexts. You may think you don't want to reuse the child, but it is > very handy to be able to make a small test harness for a widget rather > than firing up the whole application, navigating to the correct screen, > etc. It is much harder to do this if the widget depends on its enclosing > environment. And I find that if I design widgets for reuse, other uses > tend to come up often enough to make it worth-while. > > It's not that different from relying on any other global state. It makes > code harder to understand, harder to test and harder to reuse. > > More generally, IMO it is good practice to try to make acyclic > dependency graphs between classes and modules, so if the parent depends > on the child, the child shouldn't depend on the parent. > >> Besides, I need to pass the state of areaCode (has it changed or not), >> not its value? > > > OK, I misunderstood your original post on that point. > > Kent > >> I will digest this some more, and see if the polling of child attributes gets harder to follow than setting parent attributes. In theory it makes sense to have the independence you discuss, in this case it's hard to imaging needing the areaCode widget without the (parent) phonenumber widget, but this is the exception. So your suggestion makes more general sense. By the way, my suspicion was right, self.master.hasChanged = True , provides direct access, but now I'm not sure that's the way to go. Thanks, Bill From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 27 06:43:52 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 27 Jun 2005 12:43:52 +0200 Subject: turn text lines into a list In-Reply-To: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> Message-ID: <3ia3j8Fkilj7U1@individual.net> Xah Lee wrote: > i have a large number of lines i want to turn into a list. > In perl, i can do > > @corenames=qw( > rb_basic_islamic > sq1_pentagonTile > sq_arc501Tile > sq_arc503Tile > ); > > use Data::Dumper; > print Dumper(\@corenames); > > ---------- > is there some shortcut to turn lines into list in Python? str.splitlines From siyer at Princeton.EDU Fri Jun 10 15:36:54 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Fri, 10 Jun 2005 15:36:54 -0400 Subject: a question from a newcomer to this language Message-ID: <18b762872c743.42a9b396@Princeton.EDU> Hi, I am a undergraduate physics student, and I have been asked to write some code in Python for my summer job. Over the past few days, I have been learning Python and Tkinter, so naturally, I have several questions about the language. Here's one: Is there any way to convert a string into an instruction that will be executed? For example, suppose there's a string sString = "z = x*y". Is there any way to have the instruction z = x*y be executed by performing some operation on sString? Thanks in advance for your help. Shankar From tzot at sil-tec.gr Tue Jun 28 09:13:13 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 16:13:13 +0300 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> <11c166s2sh66b93@news.supernews.com> <1119923787.531336.292220@z14g2000cwz.googlegroups.com> Message-ID: On 27 Jun 2005 18:56:27 -0700, rumours say that "Inkiniteo" might have written: >I see. So... what about sending HTML email? If i send HTML tagged text, >the client will be able to read it as HTML? I agree with the others that HTML is part of the web, not of the e-mail system. I suggest you send your "info" as an attached text file; no client will mess with it. The email package is your friend for MIME messages. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From apardon at forel.vub.ac.be Thu Jun 30 04:39:57 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Jun 2005 08:39:57 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <86y88um4y3.fsf@bhuda.mired.org> <42c1ecaf$1@nntp0.pdx.net> <42c2926a$1@nntp0.pdx.net> Message-ID: Op 2005-06-29, Scott David Daniels schreef : > Roy Smith wrote: >> Andrew Durdin wrote: >>>Corrected version: >>> result = [(lambda: expr0), lambda: expr1][bool(cond)]() > Sorry, I thought cond was a standard boolean. > Better is: > result = [(lambda: true_expr), lambda: false_expr][not cond]() How about the following: result = (cond and (lambda: true_expr) or (lambda: false_expr))() -- Antoon Pardon From srinivasanr at gmail.com Tue Jun 7 21:59:54 2005 From: srinivasanr at gmail.com (srinivasanr at gmail.com) Date: 7 Jun 2005 18:59:54 -0700 Subject: xmlrpclib - methodHelp doesn't work In-Reply-To: <42a5df03$1_2@newspeer2.tds.net> References: <1118164334.528966.125920@g47g2000cwa.googlegroups.com> <42a5df03$1_2@newspeer2.tds.net> Message-ID: <1118195994.171792.277220@g14g2000cwa.googlegroups.com> oh. missed that one. thanks a lot. From rrr at ronadam.com Sun Jun 19 14:15:56 2005 From: rrr at ronadam.com (Ron Adam) Date: Sun, 19 Jun 2005 18:15:56 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: Message-ID: Bo Peng wrote: > Roy Smith wrote: > >> Can you give us some idea of what it is that you're trying to do? It >> pretty unusual to see a requirement like that. > > > def func(type_of_obj1, type_of_obj2, .....): > callfunc( [ > type_of_obj1 and obj1a() or obj1b(), > type_of_obj2 and obj2a() or obj2b(), > .... > ]) > > callfunc can take arbitrary number of objects whose types are determined > by type_of_obj1 etc. I was using a bunch of if/else to create objects > and pass them to callfunc. > > Since type_of_obj1 etc are usually binary and obj1a() etc will never be > false, the and/or solution does not look so bad in this case. > > Thanks. > Bo Are you matching the order to the obj_type? objlist = [ (type_obj1, obj1a, obj2b), (typ_obj2, obj2a, obj2b), etc...] objs = [type_of_obj1, type_of_obj2, etc...] for n in range(len(objs)): if objs[n] == objlist[n][0]: objlist[n][1]() else: objlist[n][2]() What significance does the order have? You might be able to use a dictionary of tuples. call_obj = {(type_obj1,0):obj1a, (type_obj1,0):obj1b, (type_boj2,1):obj2a, (type_obj2,1):obj2b, etc... } call_obj[(type_of_obj,order)]() Regards, Ron From sklass at pointcircle.com Fri Jun 17 13:32:27 2005 From: sklass at pointcircle.com (rh0dium) Date: 17 Jun 2005 10:32:27 -0700 Subject: Help implementing an idea In-Reply-To: References: Message-ID: <1119029547.185778.315500@g49g2000cwa.googlegroups.com> Try this.. #!/usr/bin/env python # Upload a file to a FTP server from sys import argv, exit from ftplib import FTP if len(argv) != 6: print 'Incorrect number of parameters' print 'USAGE: upload.py ' exit(0) server = argv[1] username = argv[2] password = argv[3] upfile = argv[5] downfile = argv[4] try: print 'Connecting to %s' % server ftp = FTP(server) ftp.login(username, password) print 'Connection to %s opened' % server #send file in binary mode to server (STOR command sets remote filename) ftp.storbinary('STOR %s' % upfile, open(downfile,'r')) ftp.quit() print 'File %s uploaded' % upfile except Exception, err: print 'Error uploading file. Error: %s' % err From fuzzyman at gmail.com Thu Jun 30 03:36:34 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 30 Jun 2005 00:36:34 -0700 Subject: Inheriting from object In-Reply-To: References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> Message-ID: <1120116994.917555.284570@g43g2000cwa.googlegroups.com> The reason I ask is that I often (well... a couple of times anyway) see cryptic omments like : and if you inherit from object you get all the benefits of new style classes Now I know about the advantages of inheriting from the built in types (if that's what you want to do) -but am a bit fuzzier on the 'general benefits'. I'm vaguely aware of properties.... I'll have to explore them at some point. Best Regards, Fuzzy http://www.voidspace.org.uk/python From jmccall at houston.rr.com Fri Jun 3 21:45:51 2005 From: jmccall at houston.rr.com (J. W. McCall) Date: Sat, 04 Jun 2005 01:45:51 GMT Subject: tutorial In-Reply-To: References: Message-ID: zzz wrote: > May I know where is the good website for Python tutorial? Many thanks. How about...the Python website? (www.python.org) Google is also a good place to find a great multitude of things, including Python Tutorials. From gsakkis at rutgers.edu Sun Jun 26 09:25:04 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 26 Jun 2005 06:25:04 -0700 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1119727040.440447.123000@f14g2000cwb.googlegroups.com> Message-ID: <1119792303.982745.69310@z14g2000cwz.googlegroups.com> "Konstantin Veretennicov" wrote: > > On 25 Jun 2005 12:17:20 -0700, George Sakkis wrote: > > If they go to itertools, they can simply be: > > > > def map(f, *iterables): > > return list(imap(f,*iterables)) > > > > def filter(f, seq): > > return list(ifilter(f,seq)) > > >>> from itertools import ifilter > >>> def filter(f, seq): > ... return list(ifilter(f,seq)) > >>> filter(str.isalpha, 'not quite!') > ['n', 'o', 't', 'q', 'u', 'i', 't', 'e'] > >>> __builtins__.filter(str.isalpha, 'not quite!') > 'notquite' Oops ! I've used filter only with lists and didn't know that it preserves the type for strings and tuples. Here's a (hopefully) correct version: def filter(f,seq): it = ifilter(f,seq) if isinstance(seq,basestring): return ''.join(it) elif isinstance(seq,tuple): return tuple(it) else: return list(it) By the way, the documentation of filter is unclear on what is the return type if seq is a subclass of list, tuple, str, or unicode; is it type(seq) or the base builtin type ? Let's see: def subclassFactory(cls): return type("Dummy_" + cls.__name__, (cls,), {'__new__' : lambda self, seq: cls.__new__(self, seq)}) baseToSub = dict([(base,subclassFactory(base)) for base in list,tuple,str,unicode]) f = lambda x: x.lower() for Base,Sub in baseToSub.iteritems(): assert type(__builtins__.filter(f, Sub('lowerUPPERCap'))) is Base for Base,Sub in baseToSub.iteritems(): for cls in Base,Sub: args = (f, cls('lowerUPPERCap')) assert filter(*args) == __builtins__.filter(*args) George From bronger at physik.rwth-aachen.de Thu Jun 30 05:24:18 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 30 Jun 2005 11:24:18 +0200 Subject: ANN: PyVISA 0.9 (first public release) Message-ID: <87oe9ogptp.fsf@wilson.rwth-aachen.de> Hall?chen! At http://pyvisa.sourceforge.net you can find information about the PyVISA package. It realises Python bindings for the VISA library functions, which enables you to control measurement devices via Python. Yesterday I released version 0.9. I tried to provide it with good documentation. It works very nicely with the GPIB in our lab, however, I haven't yet received feedback from others, so I leave it in beta status and with a version number < 1. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From kay.schluehr at gmx.net Wed Jun 1 14:05:39 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Jun 2005 11:05:39 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117644636.721724.41050@g14g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> Message-ID: <1117649139.569217.14600@g49g2000cwa.googlegroups.com> ironfroggy wrote: > because they are representing a seperate typing system outside of > python, to which I am creating a bridge. Since a type-hierarchy is a tree also a subtree of it is a type-hierarchy. You only have to map the root of a sub-hierarchy of Python classes to the root of the hierarchy of the other typing system and create an isomorphism between types. For exactly the same reason you can map Pythons type hierarchy onto a sub-hierarchy of it. This might not be completely sufficient because there are functions that operate on types ( like mro(), isinstance(), type() etc. ). Those must be mapped as well to counterparts of the other type-system. In contemporary CS slang this is called a 'Functor of Categories' with objects that are types ( and boolean values like True, False ) and arrows that are type aware functions like those listed above. Kay From peter at somewhere.com Mon Jun 13 07:35:00 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 13 Jun 2005 13:35:00 +0200 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Andrea Griffini schrieb: > On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen > wrote: > > >>I think new CS students have more than enough to learn with their >>*first* language without having to discover the trials and tribulations >>of memory management (or those other things that Python hides so well). > > > I'm not sure that postponing learning what memory > is, what a pointer is and others "bare metal" > problems is a good idea. I think Peter is right. Proceeding top-down is the natural way of learning (first learn about plants, then proceed to cells, molecules, atoms and elementary particles). If you learn a computer language you have to know about variables, of course. You have to know that they are stored in memory. It is even useful to know about variable address and variable contents but this doesn't mean that you have to know about memory management. MM is a low level problem that has to do with the internals of a computer system and shouldn't be part of a first *language* course. The concepts of memory, data and addresses can easily be demonstrated in high level languages including python e.g. by using a large string as a memory model. Proceeding to bare metal will follow driven by curiosity. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From bill.mill at gmail.com Wed Jun 8 09:36:45 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 8 Jun 2005 09:36:45 -0400 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> Message-ID: <797fe3d4050608063644d2f257@mail.gmail.com> On 8 Jun 2005 06:24:05 -0700, ajikoe at gmail.com wrote: > Hello, > > I use windows notepad editor to write text. > > For example I write (in d:\myfile.txt): > Helo > World > > If I open it with python: > FName = open(d:\myfile.txt,'r') > h = FName.readlines() > print h > > I get h : ['Helo\n', 'World'] > > I thought notepad use \r\n to to end the line. > > What's wrong with it? On windows, opening a file without 'b' in the file type argument does some things you might not expect, including changing /r/n to /n. Try: >>> f = file('d:/deleteme.txt', 'rb') >>> f.read() 'testing\r\n1\r\n2\r\n3' >>> f = file('d:/deleteme.txt', 'r') >>> f.read() 'testing\n1\n2\n3' Peace Bill Mill bill.mill at gmail.com From deets at web.de Wed Jun 22 16:15:12 2005 From: deets at web.de (Diez B. Roggisch) Date: Wed, 22 Jun 2005 22:15:12 +0200 Subject: Odd slicing behavior? In-Reply-To: References: Message-ID: <3htv6gFips59U1@uni-berlin.de> Dave Opstad wrote: > So given the equality of their slice representations, why do the v2[::] > and v2[0:10:1] assignments behave differently? My reading of section > 5.3.3 of the manual suggests that these should behave the same. > > If I'm just not seeing something obvious, please let me know! It's not so much obvious - I had to experiment myself a little bit. This works: v[0:10] = [1] So what can we conclude from that? It seems that what is implied by the slice-assignment syntax is that the slice is contingous. The reason becomes obvious when one does something like this: v[0:10:2] = [1,2] What do you expect to happen in this case? So - the rationale seems to be: "When using slice-assignment, a form like l[a:b:c] imposes possibly a non-continous section in l, for which the semantics are unclear - so we forbid it" It should be mentioned in the docs, though - and on could argue if [a:b:c] == [a:b] could be checked for at runtime (c being 1). But then - if you really wanted that, you could have written [a:b] in the first place. So - I'd say it's an doc-error at most :) Diez From EP at zomething.com Sun Jun 5 23:01:14 2005 From: EP at zomething.com (EP) Date: Sun, 5 Jun 2005 19:01:14 -0800 Subject: urllib2 pinger : insight as to use, cause of hang-up? Message-ID: <20050605190114.2003091643.EP@zomething.com> Hello patient and tolerant Pythonistas, Iterating through a long list of arbitrary (and possibly syntactically flawed) urls with a urllib2 pinging function I get a hang up. No exception is raised, however (according to Windows Task Manager) python.exe stops using any CPU time, neither increasing nor decreasing the memory it uses, and the script does not progress (permanently stalled, it seems). As an example, the below function has been stuck on url number 364 for ~40 minutes. Does this simply indicate the need for a time-out function, or could there be something else going on (error in my usage) I've overlooked? If it requires a time-out control, is there a way to implement that without using separate threads? Any best practice recommendations? Here's my function: -------------------------------------------------- def testLinks2(urlList=[]): import urllib2 goodLinks=[] badLinks=[] user_agent = 'mySpider Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' print len(urlList), " links to test" count=0 for url in urlList: count+=1 print count, try: request = urllib2.Request(url) request.add_header('User-Agent', user_agent) handle = urllib2.urlopen(request) goodLinks.append(url) except urllib2.HTTPError, e: badLinks.append({url:e.code}) print e.code,": ",url except: print "unknown error: ",url badLinks.append({url:"unknown error"}) print len(goodLinks)," working links found" return goodLinks, badLinks good, bad=testLinks2(linkList) -------------------------------------------------- Thannks in advance for your thoughts. Eric Pederson From grante at visi.com Fri Jun 24 22:29:33 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Jun 2005 02:29:33 -0000 Subject: Newbie question: SOLVED (how to keep a socket listening), but still some questions References: Message-ID: <11bpgcd8vsak3a6@corp.supernews.com> On 2005-06-25, Jp Calderone wrote: >>[I've never figured out why one would do a shutdown RDWR rather >>than close the connection, but I haven't put a lot of thought >>into it.] > > shutdown actually tears down the TCP connection; close > releases the file descriptor. > > If there is only one file descriptor referring to the TCP > connection, these are more or less the same. If there is more > than one file descriptor, though, the difference should be > apparent. Ah yes. I hadn't thought of that. I think the only time I had ever used shutdown was to shutdown just the transmit half. -- Grant Edwards grante Yow! An INK-LING? Sure -- at TAKE one!! Did you BUY any visi.com COMMUNIST UNIFORMS?? From guy.lateur at b-b.be Mon Jun 27 03:31:53 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Mon, 27 Jun 2005 07:31:53 GMT Subject: Office COM automatisation - calling python from VBA References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: Thanks for the input, people! From Me at Privacy.NET Fri Jun 3 00:00:36 2005 From: Me at Privacy.NET (Jeff_Relf) Date: 3 Jun 2005 04:00:36 GMT Subject: Targeting Win_XP is taboo somehow ? It shouldn't be. References: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> <429e7155.6739473@news.alphalink.com.au> Message-ID: Hi Leonard_Blaisdell and phaywood, I'm in Comp.OS.Linux.Advocacy Leonard_Blaisdell is in Comp.Sys.Mac.Advocacy. Re: The MicroSoft_C++ 7.1 code I showed, You told me: Unless clc has changed dramatically and rapidly, you won't be welcomed with this. What were you thinking ? Embrace the flames if they deign to reply at all. I wouldn't worry about an onslaught of replies if I were you, it was posted over 20 hours ago... you were the only reply. Targeting Win_XP is taboo somehow ? It shouldn't be. From jrastrick at student.usyd.edu.au Wed Jun 8 13:02:52 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 8 Jun 2005 10:02:52 -0700 Subject: Annoying behaviour of the != operator Message-ID: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> Can anybody please give me a decent justification for this: class A(object): def __init__(self, a): self.a = a def __eq__(self, other): return self.a == other.a s = A(3) t = A(3) >>> print s == t True >>> print s != t True I just spent a long, long time tracking down a bug in a program that results from this behaviour. Surely the != operator should, if no __ne__ method is present for either object, check to see if an __eq__ method is defined, and if so, return its negation? Actually, that brings me to a wider question - why does __ne__ exist at all? Surely its completely inconsistent and unnessecary to have seperate equals and not equals methods on an object? a != b should just be a short way of writing not (a == b). The fact the two can give a different answer seems to me to be utterly unintuitive and a massive pitfall for beginners (such as myself). From pierre.barbier at cirad.fr Thu Jun 30 12:11:50 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 30 Jun 2005 18:11:50 +0200 Subject: Multi Threading embedded python In-Reply-To: References: Message-ID: <42c41a04$0$12674$626a14ce@news.free.fr> Well, depends on what you want to achieve :) First, I don't think you can call Py_Initialize on many threads. You have special function to initialise different interpreters on per-thread basis. However, the main problem is: do you want to share data across your threads ? If the answer is 'no' then use one interpreter by thread, this is, by far, the simplest solution (and the most efficient ?). But if you *do* need to share data, then you are in big trouble man :) As far as I tried it, multi-threading and Python don't go along very well ! At least, not with system-threads. Basically, to run some Python code, you have to hold the GIL (Global Interpreter Lock) and you cannot *test* it, you have to try holding it, so be prepare to block your threads that would want to access Python ! What I would recommend (and that's what I do in my own software) is to use a single thread in which your Python interpreter is running. Then, use a message system in C++ to send commands and get them evaluated and sent back (if needed). By doing so, you'll avoid a lot of problems, and you won't loose significantly performances (or if you care about that, then Python is definitly not the language you need) nor parrallelism (you wouldn't be able to run many Python threads at the same time anyways). Well, I hope that help, Pierre amit a ?crit : > Hello, > > I am embedding a python script in a C++ application. The script can be > called simultaneously from multiple threads. > > What is the correct way to implement this situation: > > 1) Have unique python interpreter instantiations ( Py_Initialize() ) for > each thread. > > 2) Have one python interpreter, and implement a lock on it so it can't > be called simultaneously by multiple threads? > > Thanks > Amit From rrr at ronadam.com Fri Jun 24 17:17:09 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 24 Jun 2005 21:17:09 GMT Subject: Favorite non-python language trick? In-Reply-To: <1119634470.180697.212260@f14g2000cwb.googlegroups.com> References: <1119634470.180697.212260@f14g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > "Joseph Garvin" wrote: > > >>I'm curious -- what is everyone's favorite trick from a non-python >>language? And -- why isn't it in Python? > > > Although it's an optimization rather than language trick, I like the > inline functions/methods in C++. There has been a thread on that in the > past (http://tinyurl.com/8ljv5) and most consider it as useless and/or > very hard to implement in python without major changes in the language > (mainly because it would introduce 'compile-time' lookup of callables > instead of runtime, as it is now). Still it might be useful to have for > time-critical situations, assuming that other optimization solutions > (psyco, pyrex, weave) are not applicable. > > George Thanks for the link George, It was interesting. I think some sort of inline or deferred local statement would be useful also. It would serve as a limited lambda (after it's removed), eval alternative, and as a inlined function in some situations as well I think. Something like: name = defer then used as: result = name() The expression name() will never have arguments as it's meant to reference it's variables as locals and probably will be replaced directly with names's byte code contents at compile time. Defer could be shortened to def I suppose, but I think defer would be clearer. Anyway, it's only a wish list item for now. Regards, Ron From david.baelde at ens-lyon.fr Fri Jun 10 16:14:24 2005 From: david.baelde at ens-lyon.fr (David Baelde) Date: Fri, 10 Jun 2005 22:14:24 +0200 Subject: Abstract and concrete syntax References: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Message-ID: On Fri, 10 Jun 2005 06:57:19 -0700, Kay Schluehr wrote: >> You can do stuff like this: lambda x: x and 2 or 3 > lambda x: {True:2,False:3}.get(bool(a)) I also think these solutions are just hacks, less efficient, less readable. One shouldn't have to twist her mind to write such an easy idea. __ David From szport at fromru.com Wed Jun 29 11:37:11 2005 From: szport at fromru.com (szport at fromru.com) Date: 29 Jun 2005 08:37:11 -0700 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: <1120059431.398460.323510@g44g2000cwa.googlegroups.com> > e = 'i_am_an_attribute' > o.(e) = 10 > o.i_am_an_attribute == 10 Yes I mean this thing: to write o.(e) = 10 or o.[e] = 10 From thomasbartkus at comcast.net Thu Jun 9 10:35:29 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 9 Jun 2005 09:35:29 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: "Renato Ramonda" wrote in message news:lfJpe.15549$TR5.6995 at news.edisontel.com... > Thomas Bartkus ha scritto: > > The attractiveness of wxPython here is that it extends the platform > > neutrality of Python to GUI interfaces. On a Windows platform, the work > > looks like any other Windows program. On Gnome/Linux, the identical code > > fits right into the Gnome desktop scheme. *Big* plus. > > Then download gtk2.6 and glade for windows and then install pygtk and > code away to your satisfaction! :-D > I *will* try that. Thanks Thomas Bartkus From skromta at gmail.com Sun Jun 12 17:04:42 2005 From: skromta at gmail.com (Kalle Anke) Date: Sun, 12 Jun 2005 23:04:42 +0200 Subject: Learning more about "The Python Way" Message-ID: <0001HW.BED2700A0044BB0FF0284550@news.gmane.org> Those who have read my posts today have probably understood that I'm not a "true" Python programmer ... but I want to learn more (I think that Python is rather fun). I've read "Learning Python" pretty thoroughly, I've looked at some of the tutorials, some of online documentation, etc. But I still miss a lot of pieces for writing good python code, idioms, advanced usage/features, etc. I've also seen a lot of references to v3, but I haven't found any real documentation of what's planned for that version. So, I'm looking for advice/information on: + How to write "proper" python code instead of Java/Perl/C/C++/Pascal/Modula-2/etc inspired code + The more advanced parts/uses of Python + Discussions about the ideas behind different Python constructs + What's going to happen with v3 I would really appriciate some pointers to where I can find info about this. Web sites (I've looked at python.org but haven't manage to find the stuff of what I'm looking for ... but perhaps I've missed all the interesting parts) ? Books (I've got 'Learning Python' and 'Programming Python')? Other things? jem From Scott.Daniels at Acm.Org Wed Jun 22 19:03:25 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Jun 2005 16:03:25 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <7xoe9y3sxu.fsf@ruckus.brouhaha.com> References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> Message-ID: <42b9e6d4$1@nntp0.pdx.net> Paul Rubin wrote: > Scott David Daniels writes: > >>>Negative 0 isn't a NaN, it's just negative 0. >> >>Right, but it is hard to construct in standard C. > > > Huh? It's just a hex constant. Well, -0.0 doesn't work, and (double)0x80000000 doesn't work, and.... I think you have to use quirks of a compiler to create it. And I don't know how to test for it either, x < 0.0 is not necessarily true for negative 0. I am not trying to say there is no way to do this. I am trying to say it takes thought and effort on every detail, in the definition, implementations, and unit tests. --Scott David Daniels Scott.Daniels at Acm.Org From exarkun at divmod.com Fri Jun 24 10:26:53 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 24 Jun 2005 10:26:53 -0400 Subject: webserver application (via Twisted?) In-Reply-To: Message-ID: <20050624142653.5047.1892595433.divmod.quotient.8332@ohm> On Fri, 24 Jun 2005 12:35:40 GMT, flupke wrote: >I need to program and setup serveral webservices. >If i were still using jsp, i would use Tomcat to make the several >applications available on a given port. >How can i accomplish this in Python? >I was thinking about Twisted but it's not clear to me what parts i need >to make a webserver listen on a certain port and having it serve >different application based on the url that i received. > >Any advice on this? Roughly, from twisted.web import server, resource from twisted.internet import reactor root = resource.Resource() root.putChild("app1", getApp1()) root.putChild("app2", getApp2()) ... site = server.Site(root) reactor.listenTCP(80, site) reactor.run() You might also want to join the twisted-web mailing list: http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web Jp From jeff.maitland at gmail.com Fri Jun 24 13:50:21 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Fri, 24 Jun 2005 13:50:21 -0400 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <6829832e05062410506e564be9@mail.gmail.com> 1 trick I liked in C++ was for For loops. { for(int i = 0; i < 100; i++){ //do stuff } } wrapping the for loop in { } makes the i a local variable and then you can use it again in the code if not you will get a variable already defined error. As a side note python already keeps it a local variable, as most of us know, and even if it did we can redifne it if we needed with ease. Jeff On 6/24/05, D H wrote: > Roy Smith wrote: > > Tom Anderson wrote: > > > >>The one thing i really do miss is method overloading by parameter > >>type. I used this all the time in java > > > > > > You do things like that in type-bondage languages like Java and C++ > > because you have to. Can you give an example of where you miss it in > > Python? > > Well it's coming to a future Python version, so apparently there are > many who can use it: > http://wiki.python.org/moin/Python3.0Suggestions#head-7df9d7035174644fdae024ed4a5ea0960a003ef5 > I don't know if you'll have method overloading, but there will be type > checking. It's not actually compile-time "static typing" though. The > type checking still happens at run-time similar to your isinstance > example, making code run slightly slower than a normal python method: > "Type checking is going to slow down your code." -GVR 2005 keynote, > http://www.sauria.com/%7Etwl/conferences/pycon2005/20050324/The%20State%20of%20Python.html > -- > http://mail.python.org/mailman/listinfo/python-list > From donn at u.washington.edu Fri Jun 10 13:13:56 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 10 Jun 2005 10:13:56 -0700 Subject: without shell References: <11aj9d3fga9or8b@corp.supernews.com> Message-ID: In article <11aj9d3fga9or8b at corp.supernews.com>, Grant Edwards wrote: > On 2005-06-10, Mage wrote: > > >>py> file_list = os.popen("ls").read() > >> > >>Stores the output of ls into file_list. > >> > > These commands invoke shell indeed. > > Under Unix, popen will not invoke a shell if it's passed a > sequence rather than a single string. I suspect you're thinking of the popen2 functions. On UNIX, os.popen is posix.popen, is a simple wrapper around the C library popen. It always invokes the shell. The no-shell alternatives are spawnv (instead of system) and the popen2 family (given a sequence of strings.) Donn Cave, donn at u.washington.edu From kent37 at tds.net Sun Jun 19 17:20:06 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 19 Jun 2005 17:20:06 -0400 Subject: What platforms have Python Virtual Machines and what version(s) ofPython do they support? In-Reply-To: <1119185679.773426.110520@z14g2000cwz.googlegroups.com> References: <361ab1trhpgra9hig255r7arv68gfpe7lj@4ax.com> <1119170474.644310.102840@g49g2000cwa.googlegroups.com> <1119185679.773426.110520@z14g2000cwz.googlegroups.com> Message-ID: <42b5e0fb$1_1@newspeer2.tds.net> Fuzzyman wrote: > To the best of my knowledge jython is languishing at Python 2.1. The > PSF has funded a push to implement new style classes which will allow > it to be brought up to date. It's really not languishing any more. There is a lot of activity spearheaded by Brian Zimmer (who received the PSF grant) with help from several volunteers. They are planning an alpha release soon. I think the current released Jython will run on Java 1.1 but the new one will require Java 1.2. Kent From vdavidster at gmail.com Mon Jun 27 23:19:39 2005 From: vdavidster at gmail.com (vdavidster at gmail.com) Date: 27 Jun 2005 20:19:39 -0700 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: <1119888923.782530.286990@g44g2000cwa.googlegroups.com> References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <1119883969.197756.22140@f14g2000cwb.googlegroups.com> <1119888923.782530.286990@g44g2000cwa.googlegroups.com> Message-ID: <1119928779.725558.211940@g47g2000cwa.googlegroups.com> Hi Paul and everyone else, I ran the script and here's what I got: Python version: 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] pyparsing version: 1.3 'abc def' -> ['abc', 'def'] 'abc' -> ['abc'] It seems to work fine. I figured out what my problem was: my earlier description was erroneous. The type for Results2 was actually 'str', not 'pyparsing.ParseResults' as I had mentioned. (I was typing from memory -- I didn't actually run my code.... sorry, my bad). It seems that the way I was parsing it, I sometimes got pyparsing.parseResults lists, and sometimes got *strings* (not actually single-element lists as I thought). I had expected pyparsing results to always return lists, I guess with my token description below, it doesn't. Here's the bit of code I've wrote: from pyparsing import * unit = Word(alphanums) section = unit + Literal(':').suppress() line = ~section + Combine(unit + SkipTo(Literal(';'), include=True)) block = ZeroOrMore(line) file = Dict(ZeroOrMore(Group(section + block))) Results = dict(file.parseString(MyFileString) Where MyFileStrings (the string I want to parse) is something like this: var: x, y, z; constraints: x <= 1; y <= 2; z <= 3; And the results I'd get would be something like this: >>> Results {'var': 'x, y, z;', 'constraints': (['x <= 1', 'y <= 2', 'z <= 3'], {})} So going along Jeff Epler's line of thinking, I wrote a convenience function: def convertToList(input): if type(input) == str: output = [input] else: output = input return output So when I iterate through the keys of the Results dictionary, I just have to convertToList(value) and I will always get a list. Thanks for your feedback, everyone! (and embarassingly, I just realized I was talking to the author of pyparsing. Thanks for pyparsing, Paul! I'm using it to write a mini-language for defining process control models used in chemical engineering, and it has really given me a lot of leverage in terms of churning actual working code out in minimal time. I was thinking of doing it the lex/yacc way at first, but pyparsing is so much easier.) From tdw at tdw.net Wed Jun 22 07:17:51 2005 From: tdw at tdw.net (Tim Williams) Date: Wed, 22 Jun 2005 12:17:51 +0100 Subject: Getting/Saving email attachments w/ poplib and email modules References: <1119394743.478968.278290@g49g2000cwa.googlegroups.com> Message-ID: <008a01c5771c$08b8de10$ccbefea9@twilliams> ----- Original Message ----- From: > > Here's what I'm trying to do: > > I need to connect to a pop3 server, download all messages, and copy all > of the attachments into a specific directory. The actual email message ############## import email import poplib mimes = ["image/tif","image/tiff","images/x-tif","image/x-tiff", "application/tif","application/tiff","application/x-tif", "application/x-tiff"] def WriteAttachment(msg): for part in msg.walk(): if part.get_type() in mimes: name = part.get_filename() data = part.get_payload(decode=True) f = file(name,'wb') f.write(data) f.close() ms = poplib.POP3(server) ms.user(user) ms.pass_(passw) msgcount = len(ms.list()[1]) for i in range(msgcount): response, msg_as_list, size = ms.retr(i+1) msg = email.message_from_string('\r\n'.join(msg_as_list)) WriteAttachment(msg) ################################## From rkern at ucsd.edu Wed Jun 8 15:02:15 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 08 Jun 2005 12:02:15 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: <1118255048.849018.259500@g14g2000cwa.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> Message-ID: Jordan Rastrick wrote: > Are there any other reasonable examples people can give where it makes > sense for != and == not to be each other's complement? __eq__ and __ne__ implement *rich* comparisons. They don't have to return only True or False. In [1]:import Numeric In [2]:a = Numeric.array([1, 2, 3, 4, 5]) In [3]:b = Numeric.array([1, 0, 4, 0, 5]) In [4]:a == b Out[4]:array([1, 0, 0, 0, 1],'b') In [5]:a != b Out[5]:array([0, 1, 1, 1, 0],'b') In [6]:(a != b) == (not (a == b)) Out[6]:array([1, 0, 0, 0, 1],'b') In [7]:not (a == b) Out[7]:False In [8]:not (a != b) Out[8]:False -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From skip at pobox.com Sat Jun 11 20:47:58 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 11 Jun 2005 19:47:58 -0500 Subject: case/switch statement? In-Reply-To: References: Message-ID: <17067.34366.799918.491381@montanaro.dyndns.org> Steven> I've never understood why something like: Steven> if x = 5: Steven> do_this Steven> elif x = 6: Steven> do_that Steven> else: Steven> do_something_else Steven> is supposed to be "bad", but Steven> case of: Steven> x = 5: Steven> do_this Steven> x = 6: Steven> do_that Steven> otherwise: Steven> do_something_else Steven> is supposed to be "good". ... Steven> Arguably, a case statement *might* allow the compiler to Steven> optimize the code, maybe, sometimes. If the case values are constants known to the compiler, it can generate O(1) code to take the correct branch. (In fact, that could be done by the compiler for if statements such as in your example today. It just isn't.) It is precisely this behavior that is desired in many situations. See PEP 275 for details: http://www.python.org/peps/pep-0275.html Skip From michele.simionato at gmail.com Fri Jun 17 08:30:25 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Jun 2005 05:30:25 -0700 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: <1119011425.405165.186960@g44g2000cwa.googlegroups.com> I fail to see the relationship between your reply and my original message. I was complaining about the illusion that in the old time people were more interested in programming than now. Instead your reply is about low level languages being more suitable for beginners than high level languages. I don't see the connection. Michele Simionato From aahz at pythoncraft.com Fri Jun 3 00:27:09 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jun 2005 21:27:09 -0700 Subject: (OT) lincense protection generator References: <429FD59D.3020201@REMOVEMEcyber.com.au> Message-ID: In article <429FD59D.3020201 at REMOVEMEcyber.com.au>, Steven D'Aprano wrote: > >Alternatively, put a lot of error checking in one >module which you import and run at startup. Something like: > >try: > import mymodule > import databasemodule >except: > print "PEBCAK error, call tech support" > sys.exit(99) Yeah, except it's PEBKAC. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The only problem with Microsoft is they just have no taste." --Steve Jobs From me at privacy.net Mon Jun 13 11:44:39 2005 From: me at privacy.net (Dan Sommers) Date: 13 Jun 2005 11:44:39 -0400 Subject: string formatting using the % operator References: Message-ID: On Mon, 13 Jun 2005 15:12:54 GMT, William Gill wrote: > I am using the % operator to create queries for a db app. It works fine > when exact strings, or numbers are used, but some queries need partial > matching that use the '%' as a wildcards. So for example the resultant > string should be 'WHERE name LIKE %smith%' (would match silversmith, > smithy, and smith). Is there any way to get something like > searchterm = 'smith' > sql += 'WHERE name LIKE %s' % searchterm > to return 'WHERE name LIKE %smith%' I have tried using escapes, > character codes for the % sign, and lots of other gyrations with no > success. The only thing that works is if I modify searchterm first: > searchterm = 'smith' > searchterm ='%'+'smith'+'%' > sql += 'WHERE name LIKE %s' % searchterm > Any Ideas? Let the DB-API do more work for you: cursor = connection.cursor( ) sql = """SELECT column2, columns3 FROM table WHERE name LIKE %s""" values = ('%%%s%%' % searchterm,) # note that this is a tuple cursor.execute( sql, values ) HTH, Dan -- Dan Sommers From lambacck at gmail.com Wed Jun 8 14:28:59 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Wed, 8 Jun 2005 14:28:59 -0400 Subject: [Pyrex] Allocating an array.array of a specific length in pyrex In-Reply-To: <396556a2050608111658e56203@mail.gmail.com> References: <396556a2050608111658e56203@mail.gmail.com> Message-ID: The memory is not temporary, I am passing it out as an array, thus the malloc/free route will require double allocation(once for malloc/free, once for array.array). I am not using string because when I tried to pass the data in as string, pyrex complained about the conversion. However, I could probably use the same PyObject_AsReadBuffer function call to get at the data passed in to the function as a string and then pass it out as a string as well using the interface suggested ( PyString_FromStringAndSize and PyString_AsString ). Perhapse I need to substitute PyObject_AsWriteBuffer instead of PyString_AsString in order for my changes to get propegated back to the string object? -Chris On 6/8/05, Adam Langley wrote: > On 6/8/05, Chris Lambacher wrote: > > My question is, is there a better way to > > allocate the memory for the array.array object than: > > a = array.array('B', [0] * (pixels * 2)) > > cdef unsigned char *buffer > temp_string = PyString_FromStringAndSize(NULL, length) > buffer = PyString_AsString(temp_string) > > That's one way to do it. But it looks like you just want an area of > memory so why not: > > cdef extern from "stdlib.h": > ctypedef unsigned long size_t > void *malloc(size_t size) > void free(void *mem) > > ? > > AGL > > -- > Adam Langley agl at imperialviolet.org > http://www.imperialviolet.org (+44) (0)7906 332512 > PGP: 9113 256A CC0F 71A6 4C84 5087 CDA5 52DF 2CB6 3D60 > -- Christopher Lambacher lambacck at computer.org From arutz at mimoza.pantel.net Thu Jun 9 07:46:33 2005 From: arutz at mimoza.pantel.net (Antal Rutz) Date: Thu, 09 Jun 2005 13:46:33 +0200 Subject: tail -f sys.stdin Message-ID: <42A82C19.4050405@mimoza.pantel.net> Hi! Maybe a very newbie question but: I'd like to write a prog which reads one line at a time on its sys.stdin and immediately processes it. If there are'nt any new lines wait (block on input). I couldn't find a solution for it. Several methods that doesn't fit here: - reading the entire file-like object until EOF and then process - read one line(all lines) and when there aren't any lines more, quit. So I need a 'tail -f' for stdin. Thanks. -- --arutz From aahz at pythoncraft.com Wed Jun 8 09:40:54 2005 From: aahz at pythoncraft.com (Aahz) Date: Wed, 8 Jun 2005 06:40:54 -0700 Subject: REMINDER: BayPIGgies: June 9, 7:30pm (IronPort) Message-ID: <20050608134054.GA10909@panix.com> The next meeting of BayPIGgies will be Thurs, June 9 at 7:30pm at IronPort. Drew Perttula will discuss his Python-based lighting system controller. The system includes a music player, a variety of programs to design and time light cues, and drivers for hardware that outputs the DMX protocol used by most theatrical lighting gear. BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://www.baypiggies.net/ Before the meeting, we may meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The July 14 meeting will be Alex Martelli's "Black Magic" talk. Advance notice: The August 11 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From scrimp212 at yahoo.com Mon Jun 6 13:00:46 2005 From: scrimp212 at yahoo.com (scrimp) Date: 6 Jun 2005 10:00:46 -0700 Subject: Using PAMIE to upload and download files...is it possible? Message-ID: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> Ive been using PAMIE 1.4 to try to automate web page processes. The one thing I cannot do with it is upload files and download files. With uploading files, the file input box does not allow PAMIE to enter in a path to a file. With downloading files, I can click on the link to download the file, but thats where I get stuck at. It brings up that download window and then it brings up the where to save window. Theres no errors that I encounter when I get stuck at these spots it justs sits there not knowing what to do. If anyone has had success in both uploading or downloading or even some insight, I would greatly appreciate your help. Thanks! From zunbeltz at gmail.com Wed Jun 22 04:10:38 2005 From: zunbeltz at gmail.com (Zunbeltz Izaola) Date: Wed, 22 Jun 2005 10:10:38 +0200 Subject: asynchronous comunication, wxPython and threads. References: Message-ID: On Tue, 21 Jun 2005 11:07:35 -0400, Peter Hansen wrote: > > Please clarify: what does this mean? "Sending a socket" is not a usual > way to describe TCP communications. Do you mean your program _opens_ a > socket (like a phone connection) and _sends_ some data, then waits for > data to be received from the other end? Or are you (as it almost > sounds) opening and closing sockets repeatedly for each part of the > conversation? > Sorry for the lack of clarity. I opened the socket once (i don't know if itit is important to open inside or outside the comunication thread). And them send "packages" and wait for data. > > I think you are using the term "socket" where you should be using > "packet". A socket is the virtual connection created by TCP. A packet > is either a single blob of data sent by the TCP code in the operating > system, or perhaps a single chunk of your own data. > Thanks for the vocabulary correction. > If you are using a single TCP socket to send multiple packets, and you > are talking about those packets being sent out of order, it's very > unlikely and there must be another explanation. TCP _is_ reliable, and > you will not get data out of order unless you do something to screw > things up, for example by creating a race condition by doing > multithreaded code incorrectly. > I think this is the case (see the post of Toby). I didn't try it out but I think the problem is that i *do* comunication in both threads. > > Some people advise that, but there's really nothing *wrong* with doing > this in a second thread, and in fact I do similar things all the time > with no ill effects. While async frameworks _can_ make this easier, > they could also make it harder (at least for a while) as you adjust your > brain to the new approach. Furthermore, at least in the case of > wxPython and Twisted (on Windows) there can be problems integrating the > two loops. I don't believe the latest Twisted claims to have fully > solved the problems involved yet, so you might still be required to have > a second thread for the TCP stuff. > Yes, i have read that there is problems yet. > > I use a non-blocking socket and select() calls in my thread, and > communicate with the GUI thread using appropriate Queue objects and > calls to PostEvent() (or CallAfter()) on the wx side of things. It's > pretty straightforward, so if you post a small piece of your application > which reproduces the problem it shouldn't be hard for someone here to > help you fix it. > Thanks. First i would check if the problem is what Toby says. > > No more so than using threads, unless your problem is caused by the > threads themselves (as I suggested above) in which case it might be > easier to just fix the problem. > > -Peter Thank you very much Zunbeltz From ggg at zzz.it Fri Jun 10 11:24:49 2005 From: ggg at zzz.it (deelan) Date: Fri, 10 Jun 2005 17:24:49 +0200 Subject: about accessing mysql In-Reply-To: References: Message-ID: <1vnon2-fm6.ln1@news.interplanet.it> sinan , wrote: (...) > these command works at my computer but when i want to do in my server, > i get these messages as you seen, my both computer and server have > same python, same MySQLdb module and same database with same > priviliges.also how can i connect to remote database? is that work ? > db=MySQLdb.Connection(host="192.168.0.120",user="root",db="nux") > thank you. in addition to Diez observations please tell us: 1) version of mysql server you are trying to connect 1a) is the the mysql db been complied to support Innodb tables? please issue a "SHOW VARIBLES" command on the mysql console, there should be some mention on innodb support somewhere. 2) version of mysqldb you are using bye. -- deelan, #1 fan of adriana lima! From donald.welch at NOSPAM.hp.com Thu Jun 30 12:28:27 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Thu, 30 Jun 2005 09:28:27 -0700 Subject: Programmers Contest: Fit pictures on a page References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <1120083687.481004.197390@g47g2000cwa.googlegroups.com> Message-ID: <42c41ef2@usenet01.boi.hp.com> mensanator at aol.com wrote: > > > Chung Leong wrote: >> Isn't that an NP-complete problem or am I crazy? > > That makes it a more realistic challange, doesn't it? > > Suppose it was something simple, like calculating a > minimal spanning tree. Every program would produce the > same output. What kind of contest would that be? I was thinking maybe you could use a genetic algorithm, where the fitness function would caluclate the amount of waste. I'm not very familar with how to implement this sort of thing, though. -Don From mwm at mired.org Tue Jun 14 18:45:11 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 14 Jun 2005 17:45:11 -0500 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> <863brlzmy9.fsf@guru.mired.org> <86ekb4y5ut.fsf@guru.mired.org> Message-ID: <8664wgy2vc.fsf@guru.mired.org> Roy Smith writes: > Mike Meyer wrote: >> I've never seen someone explain why, for instance, string addition is >> O(n^2) beyond the very abstract "it creates a new string with each >> addition". No concrete details at all. > > I took a shot at that very question a while ago. Elephants never forget, > and neither does google (http://tinyurl.com/9nrnz). While that's an excellent explanation of why string addition is O(n^2), it doesn't really look at the concrete details of the Python string implementation - which is what I was referring to. I'm sorry that I was unclear in what I said. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tron.thomas at verizon.net Fri Jun 17 18:41:07 2005 From: tron.thomas at verizon.net (tron.thomas at verizon.net) Date: 17 Jun 2005 15:41:07 -0700 Subject: What makes an object uncopyable? Message-ID: <1119048067.749297.23010@g49g2000cwa.googlegroups.com> I am trying to make a copy of a certain Python object using the copy.copy() function. When I try to perform this operation I get an error like the following: copy.Error: un(shallow)copyable object of type ... What factors determine whether an object can be copied? From brian9511 at dslextreme.com Tue Jun 28 14:27:40 2005 From: brian9511 at dslextreme.com (muldoon) Date: 28 Jun 2005 11:27:40 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... Message-ID: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Americans consider having a "British accent" a sign of sophistication and high intelligence. Many companies hire salespersons from Britain to represent their products,etc. Question: When the British hear an "American accent," does it sound unsophisticated and dumb? Be blunt. We Americans need to know. Should we try to change the way we speak? Are there certain words that sound particularly goofy? Please help us with your advice on this awkward matter. From mnations at gmail.com Thu Jun 2 21:00:55 2005 From: mnations at gmail.com (Mudcat) Date: 2 Jun 2005 18:00:55 -0700 Subject: py2exe problems with win32com [ EnsureDispatch('ADODB.Connection') ] In-Reply-To: <1117138132.617482.171480@o13g2000cwo.googlegroups.com> References: <1117056064.693253.74330@z14g2000cwz.googlegroups.com> <1117138132.617482.171480@o13g2000cwo.googlegroups.com> Message-ID: <1117760455.228182.79290@g43g2000cwa.googlegroups.com> Ok apparently that's not the fix. I just tried that with Python 2.4 and the newest version of py2exe and win32all, and I can not get it to work. Can someone explain how to freeze Excel with the new version of py2exe? The old way isn't working anymore. I used one of the templates provided, but I kept getting CLSID errors, even when I provide the typelib in the options menu in setup. So "--progid" was removed, what replaced it? Thanks From pyguy2 at gmail.com Wed Jun 29 09:47:02 2005 From: pyguy2 at gmail.com (pyguy2 at gmail.com) Date: 29 Jun 2005 06:47:02 -0700 Subject: How to find Windows "Application data" directory?? In-Reply-To: <7xbr5pkdnb.fsf@ruckus.brouhaha.com> References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> <1120017647.696243.154880@f14g2000cwb.googlegroups.com> <7xbr5pkdnb.fsf@ruckus.brouhaha.com> Message-ID: <1120052822.554903.155610@z14g2000cwz.googlegroups.com> I had a post yesterday on just that. Anyways, I always love it when what can be a really annoying problem, reduces into as something simple and elegant like a python dict. (in general, I find dictionaries rock). I remember a similar eureka, when some time ago I found it really neat that split w/no args works on whitespace words. Or, things like min and sort actually travel down levels of data structures for you. Or, when one realizes things like "in" works on all sorts of sequences even filehandes, or you can treat gzipped files just like normal files, or coolness of cStringIO, or startswith and endsmith methods on strings, or . . . Hmm, I wonder if there is a page of the little python coolnesses. I recall one of python annoyances. john From Scott.Daniels at Acm.Org Wed Jun 15 11:07:50 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 15 Jun 2005 08:07:50 -0700 Subject: Using a base class for a factory function In-Reply-To: References: Message-ID: <42b03d12$1@nntp0.pdx.net> Riccardo Galli wrote (approximately): > I need a class to behave as a factory method for its children so that I could inherit > from it and still use it as a factory. Several others suggest you probably don't want to do this; I concur. Separating the factory from the interface (I presume you are doing some isinstance checking) is probably a good idea. If, for some reason, you feel you must implement your original plan, the following code should outline the trick (look up __new__ and study the code). class Interf(object): def __new__(klass, kind, *args, **kwargs): if kind is None: return object.__new__(klass, *args, **kwargs) elif kind == 'a': return Sub1(*args, **kwargs) else: assert kind == 'b' return Sub2(*args, **kwargs) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join( '%s=%r' % pair for pair in sorted(vars(self).items()))) class Sub1(Interf): def __new__(klass, *args, **kwargs): return Interf.__new__(klass, None, *args, **kwargs) def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class Sub2(Interf): def __new__(klass, *args, **kwargs): return Interf.__new__(klass, None, *args, **kwargs) def __init__(self, *args, **kwargs): self.xargs = args self.xkwargs = kwargs --Scott David Daniels Scott.Daniels at Acm.Org From simon.dahlbacka at gmail.com Thu Jun 30 08:31:01 2005 From: simon.dahlbacka at gmail.com (simon.dahlbacka at gmail.com) Date: 30 Jun 2005 05:31:01 -0700 Subject: Add methods to string objects. In-Reply-To: References: <2fdabf19.0506300201.5fb56b59@posting.google.com> Message-ID: <1120134661.407265.251710@z14g2000cwz.googlegroups.com> You can even get closer, but it is NOT recommended class foostr(str): def plural (self): if self.value[-1] in "sz": return self.value + "es" else: return self.value + "s" #ugly hack setattr(__builtins__, "str", foostr) print str("apple").plural() # this however does not work # print "apple".plural() From donn at drizzle.com Sat Jun 18 02:03:38 2005 From: donn at drizzle.com (Donn Cave) Date: Sat, 18 Jun 2005 06:03:38 -0000 Subject: Loop until condition is true References: Message-ID: <1119074614.700809@yasure> Quoth Remi Villatel : | What I'm trying to achieve is a conditionnal loop of which the condition | test would be done at the end so the loop is executed at least once. It's | some way the opposite of "while". | | So far, all I got is: | | while True: | some(code) | if final_condition is True: | break | # | # | | What I don't find so "nice" is to have to build an infinite loop only to | break it. | | Is there a better recipe? It depends, but that isn't too bad. The alternative would be flag variable, like "looping = 1; while looping: ..." The construct you're looking for is "until" in C, and there have been plenty of proposals to add this or other improvements to Python's repertoire. As far as I know, it hasn't happened because it isn't really needed. If you look at C code, at least in my experience the "until" loop is quite rarely used. (I don't see it once in the source to Python 2.4, for example.) Meanwhile, the "while True" (or "while 1") idiom is very familiar to Python programmers (just as the Python source has dozens of "for (;;)"), so it's preferred for legibility. It's nice, don't worry. Donn Cave, donn at drizzle.com From ptmcg at austin.rr.com Sun Jun 26 23:34:03 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Jun 2005 20:34:03 -0700 Subject: OO approach to decision sequence? In-Reply-To: References: <1119820490.656027.249730@g14g2000cwa.googlegroups.com> <1119823091.503532.60180@g44g2000cwa.googlegroups.com> Message-ID: <1119843243.568012.168810@g49g2000cwa.googlegroups.com> Ok, I'm glad you guys liked that design pattern. Here are a few additional footnotes: 1. As George mentions, the order of the converters is *very* important, especially in this particular case. One might question whether '1+0j' would convert to a complex or an int - my first thought was to make it an int, but that made the example more complicated, and I didn't really need to be fussy to make the example. 2. If this were a design for a deserializer, it would be a bit poor, if only because of this order-sensitivity. Also, there is no way to reconstruct a string containing a value that maps to one of the other types, such as 'True' or '1'. A better deserialize/serialize design would support quoted strings so that a string of '"1"' would not be misinterpreted as an int. But again, I didn't want to take on deconstructing quoted strings, escaped characters, etc. But in general, when designing a deserializer/serializer, it's better to make the output more unambiguous. 3. I once had an O-O expert tell me that this was not really a Chain-of-Responsibility pattern. His take was that, in COR, each link succeeds, or calls the next link in the chain. In my design, each link is just one of a collection, and succeeds or raises an exception; the iteration is done from the calling routine. I really haven't found a name for this pattern, so I just call it "modified COR". -- Paul From thomasbartkus at comcast.net Tue Jun 28 13:07:26 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 28 Jun 2005 12:07:26 -0500 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com><1119956464.362328.290370@o13g2000cwo.googlegroups.com> Message-ID: "phil" wrote in message news:mailman.1002.1119975443.10512.python-list at python.org... > > > > > Theres even a version of Python for .NET, called IronPython. The major > > advantage of this is that you get to program in Python, which I can > > tell you from experience is a lot more enjoyable and pain-free than C, > > C++, Fortran, or Java (and, I would highly suspect, VB and C#). But > > apparently the available GUI builders aren't as good for Python - > > having not done a whole lot of GUI building in general, I'll leave this > > for more experienced people to judge. > > > > From 30 years of application development experience I will tell you > NOT HUMBLY, that Python is easily the most productive, the most > read-write and the most elegant of any of the above. Handsdown > better than Java, the runner up in that group. Agreed! > Now let me explain somthing about "GUI buiders" or IDE's, from some > experience, Visual Studio being the worst. > > The IDE takes a picture of what they think you want to do, they then ask > you some questions about the components, and they afford you the > opportunity to modify the properties of the objects. > Then they store all this info in tables and build code at > buildtime. The tables are rarely documented well and sometimes > have very confusing layouts. So you usually go back to the > IDE to make changes and if the changes are compilcated and there > are interconnected events to consider, you better know what you are > doing. > > I consider it a nightmare of hiding code from the programmer. > The IDE is taking on the burden of a couple layers of abstraction > and the IDE ain't that smart. "A nightmare of hiding code from the programmer" Hmmhh! Well, it certainly does hide a lot of code! More precisely, it removes the need for a lot of hand coding work that should be automated. Do I want to spend 95% of my coding/debugging efforts on a consistent user interface or would I rather spend the bulk of my efforts on the business problem that needs solving and just *have* an attractive and consistent user interface. > You would be wise, if you choose Python to choose Tkinter or WxWindows > and learn the properties of a radio button and how to trigger events. > Writing simple GUIs is not that hard. Then after you know what is > going on behind the scenes, a BOA Constructor will not be as > mysterious or dangerous. Writing simple user interfaces may not be hard but "simple" user interfaces rarely serve well. More to the point is that programs are much better when they have idiot proof (and idiot easy!) user interfaces where the programmer hasn't the need to cope with the 1001 ways a user can louse up input or need to write an encyclopeadia of documentation on how one interacts with his particular program. You are quite correct to point out how much better it is to know what is going on behind the scenes. But heck, once you know how to extract square roots - you need to let the computer do it! GUI interfaces should be the same deal! Thomas Bartkus From sjmachin at lexicon.net Fri Jun 24 08:15:56 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 24 Jun 2005 22:15:56 +1000 Subject: Sorting part of a list In-Reply-To: <3i29tfFjgph8U1@news.dfncis.de> References: <3i29tfFjgph8U1@news.dfncis.de> Message-ID: <42BBF97C.7090602@lexicon.net> Sibylle Koczian wrote: > Hello, > > I thought I understood list slices, but I don't. I want to sort only the > last part of a list, preferably in place. If I do > > >>> ll = [3, 1, 4, 2] > >>> ll[2:].sort() It may help in unravelling any bogglement to point out that this is equivalent to temp = ll[2:]; temp.sort(); del temp > >>> ll > [3, 1, 4, 2] > > ll isn't changed, because ll[2:] is a copy of the last part of the list, > and this copy is sorted, not the original list. Right so far? Quite correct. > > But assignment to the slice: > > >>> ll[2:] = [2, 4] > >>> ll > [3, 1, 2, 4] > > _does_ change my original ll. Quite correct. > > What did I misunderstand? What misunderstanding? You have described the behaviour rather precisely. Which of the two cases is boggling you? From xah at xahlee.org Fri Jun 24 03:04:29 2005 From: xah at xahlee.org (xah at xahlee.org) Date: 24 Jun 2005 00:04:29 -0700 Subject: tree functions daily exercise: Table In-Reply-To: <42bb0c54$0$2392$ed2619ec@ptn-nntp-reader02.plus.net> References: <1115969822.361451.100620@g47g2000cwa.googlegroups.com> <87r7gbr1rg.fsf@sefirot.ii.uib.no> <1116236529.172707.174570@g47g2000cwa.googlegroups.com> <1118613721.423843.39090@g43g2000cwa.googlegroups.com> <1118616214.185026.125240@z14g2000cwz.googlegroups.com> <1119075460.194633.144820@g14g2000cwa.googlegroups.com> <1119344096.341769.66760@f14g2000cwb.googlegroups.com> <42bb0c54$0$2392$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <1119596669.315196.251930@o13g2000cwo.googlegroups.com> Dear Dr Jon D Harrop, ?List Comprehension? is a special concise syntax form that generates lists, as a way to save typing such as for loops. It is primarily a jargon bandied about by programers which have contributed huge misunderstandings and miscommunications. The extensiveness of this particular jargon's harm has also encroached into functional programing languages as to cause irregular syntax and less powerful semantics. The utility of ?list comprehension? is just a (normal) function designed to generate list. References: ? A exposition of list comprehension in Python. http://xahlee.org/perl-python/list_comprehension.html ? Jargons of Info Tech Industry http://xahlee.org/UnixResource_dir/writ/jargons.html Xah xah at xahlee.org ? http://xahlee.org/ Jon Harrop wrote: > David Hopwood wrote: > > That's consistent with the behaviour of list comprehensions in other > > languages -- including "set/tuple formers" in SETL > > , which I believe was the > > first language to support them. I don't know of any language where > > a list comprehension with multiple loops creates nested lists. > > I'm not entirely sure what a list comprehension is, but Mathematica might be > an example of a language in which multiple loops create nested lists. > > -- > Dr Jon D Harrop, Flying Frog Consultancy > http://www.ffconsultancy.com From bob at greschke.com Mon Jun 27 22:09:34 2005 From: bob at greschke.com (Bob Greschke) Date: Mon, 27 Jun 2005 20:09:34 -0600 Subject: Text() tags and delete() Message-ID: Does Text.delete(0.0, END) delete all of the tags too? Everything says it does not delete marks, but nothing about tags. Thanks! Bob From skip at pobox.com Thu Jun 16 21:38:08 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 16 Jun 2005 20:38:08 -0500 Subject: PEP 304 "Controlling Generation of Bytecode Files" - patch updated Message-ID: <17074.10624.578497.392072@montanaro.dyndns.org> I updated the patch that supports PEP 304, "Controlling Generation of Bytecode Files" to apply cleanly against current CVS. I've tested it on Mac OS X (straight Unix build only). I'd appreciate it if some Linux, Windows and Mac framework folks could apply the patch, rebuild, then run the tests (there is a "testbcb" target in the Makefile that should give Windows people an idea what to do). The patch is attached to http://python.org/sf/677103 Now that I think about it, there is probably a file in the Windows build tree (equivalent of pyconfig.h?) that still needs to be updated. The text of the PEP has not been updated in awhile. I will try to look at that in the next couple of days. I'd appreciate some critical review by people with Windows filesystem experience. There was a comment ages ago about problems with this scheme due to Windows multi-rooted directory tree that I can no longer find (and failed to record in the PEP at the time). I'd like to see if the problem can be resurrected then addressed. Thanks, Skip From onfrek at yahoo.com Thu Jun 2 04:19:35 2005 From: onfrek at yahoo.com (Michael Onfrek) Date: 2 Jun 2005 01:19:35 -0700 Subject: How to restrict lenght of entry widget to certain number of character In-Reply-To: References: <1117396149.334908.238580@g14g2000cwa.googlegroups.com> Message-ID: <1117700375.764690.305820@g44g2000cwa.googlegroups.com> import Tkinter as tk Hi! Can you explain what line above mean? I also found : http://effbot.org/zone/tkinter-entry-validate.htm It works for me, but I not really understand how? :) Thanks for help! From nyamatongwe+thunder at gmail.com Sun Jun 5 17:34:04 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 05 Jun 2005 21:34:04 GMT Subject: error in usin list with boost In-Reply-To: <1117952030.199906.326130@g47g2000cwa.googlegroups.com> References: <1117952030.199906.326130@g47g2000cwa.googlegroups.com> Message-ID: GujuBoy: > i have created a "cpp" file which has the followin code and when i try > to compile it..it does not know what "list" is..it says its > undefined..i also tried using #include I would have expected this (except the cstdint.h line which may not be needed but it was in the code I copied from) to already be in your code if you are using Boost Python: #include #include using namespace boost::python; Have you read the Tutorial Introduction? http://www.boost.org/libs/python/doc/tutorial/doc/html/index.html Neil From __peter__ at web.de Sat Jun 18 03:19:42 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Jun 2005 09:19:42 +0200 Subject: Loop until condition is true References: <1119074614.700809@yasure> Message-ID: Donn Cave wrote: > If?you?look?at?C?code,?at?least?in?my?experience?the > "until" loop is quite rarely used.??(I?don't?see?it?once?in?the?source > to Python 2.4, for example.) Long time no C? 'until' in C is actually do statement while (expression); I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for (" in the Python 2.4 source, so using these rough estimates do-while still qualifies as "rarely used". Peter From kent37 at tds.net Mon Jun 20 13:38:19 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Jun 2005 13:38:19 -0400 Subject: binary file In-Reply-To: <556d8$42b6b8c2$9117fe9b$19867@news2.tudelft.nl> References: <42b6af4f$1_3@newspeer2.tds.net> <556d8$42b6b8c2$9117fe9b$19867@news2.tudelft.nl> Message-ID: <42b6fe7a$1_2@newspeer2.tds.net> Nader Emami wrote: > Kent Johnson wrote: > >> Nader Emami wrote: >> >>> L.S., >>> >>> I have used the profile module to measure some thing as the next >>> command: >>> >>> profile.run('command', 'file') >>> >>> But this make a binary file! How can I write the result of 'profile' >>> in a ascii file? Others how can I read (or convert) the binary file >>> to am ascii file? >> >> >> >> Use an instance of pstats.Stats to interpret the results: >> >> from pstats import Stats >> s = Stats('file') >> s.print_stats() >> >> etc. >> http://docs.python.org/lib/profile-stats.html >> >> Kent > > I got the same result as the execution of command. But I would like to > write to the an external 'ascii' file! Oh, I get it, pstats.Stats doesn't have a way to send the output to a file. That's surprising! One option would be to write a program that outputs what you want, then redirect the output in the shell. Alternatively take a look a the source for print_stats() and write your own that outputs to a file. Kent From mandus at gmail.com Sat Jun 25 15:19:44 2005 From: mandus at gmail.com (Mandus) Date: Sat, 25 Jun 2005 19:19:44 +0000 (UTC) Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Sun, 26 Jun 2005 04:36:51 +1000 skrev Steven D'Aprano: > On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote: > >> On 6/25/05, Mandus wrote: >>> It is really a consensus on this; that >>> removing map, filter, reduce is a good thing? It will render a whole lot >>> of my software unusable :( >> >> I think you'll be able to use "from __past__ import map, filter, >> reduce" or something like that :) They don't have to be built-in. > > More likely they will be moved to something like itertools than "__past__". > > Or just define them yourself: > > def map(f, seq): > return [f(x) for x in seq] > > def filter(p, seq): > return [x for x in seq if p(x)] > > def reduce(f, seq, zero): > r = zero > for x in seq: r = f(r, x) > return r sure - that will be possible. But the main point (for me) is to avoid the horrible slow for-loop in python (reduce...). By using the builtin reduce, I move the for-loop into the c-code which performs better. map and filter with list-comprehensions is probably ok - I use list-comprehensions a lot, but somehow like the syntax of map/filter better. When it comes to lambdas, I am not so sure. I use them all the time, and I will certainly miss them, and I have used lambdas in ways which at least take som tinkering to translate to normal def's (or rather closures). But I am not sure yet whether I have cases which are impossible to translate (hey, nothing is impossible, some things just take a bit more time). Oh, and by the way, I use python to solve PDEs :) But as someone else said, this will take some time. And I can always put the c-function back in my self when that time comes. Another important point, which it seems Guido does not fancy very much, is that Python can be an ok functional style language for those who like it. I very much enjoy the concept of using different programming styles within the same language. It is mostly a convenience - I admit that - but it makes me more productive. I'll be very sorry if we take that away from python. Maybe I am to late to change Guido on this - but if we are many, maybe we can! -- Mandus - the only mandus around. From lycka at carmen.se Fri Jun 10 05:42:23 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 10 Jun 2005 11:42:23 +0200 Subject: DB API 2.0 and transactions In-Reply-To: References: Message-ID: You might have spotted a fairly nasty bug there! Christopher J. Bottaro wrote: > Hi, > Why is there no support for explicit transactions in the DB API? I mean > like transaction() to start the trans and commit() and rollback() would end > the trans or something. To quote from Date & Darwen "A Guide to the SQL Standard, 4th ed.": "An SQL-transaction is initiated when the relevant SQL-agent executes a 'transaction-initiating' SQL statement (...) and the SQL-agent does not already have an SQL transaction in progress. Note, therefore, that (...) SQL-transactions can't be nested. Note too that transaction initiation is always implicit--there is no explicit 'BEGIN TRANSACTION' statement." The Python DB-API standard matches the SQL standard, and that seems reasonable. > This gets weird when using the Python DB API to interact with Postgres > because a transaction gets started in 3 places: connection, commit, > rollback. That's not how it's supposed to work! Are you sure that you don't implicitly start transactions by SELECTs etc? PostgreSQL violates the SQL standards by running in autocommit mode unless you explicitly perform its non-standard BEGIN command. If you are right about the behaviour you describe, the PostgreSQL binding for Python that you use may have taken the easy route, and performs a "BEGIN" on connect and after every commit or rollback. If so, this is a serious bug, and should be reported as one. The correct thing to do is to insert the BEGIN just before the first SQL statement that is affecting transactions. Of course, this means that the binding needs to keep track of transaction state, and this makes it a little bit more complicated. You'd need something like this in the binding: class connection: def __init__(...): ... self.inTxn = False def commit(...): ... self.inTxn = False def rollback(...): ... self.inTxn = False def execute(...): ... if not self.inTxn: perform the BEGIN command against the backend self.inTxn = True ... Actually, this isn't perfect either, because not all SQL commands (should) initate transactions, but it's a lot closer to what we want. This bug has implications far beyond timestamps. Imagine two transaction running with isolation level set to e.g. serializable. Transaction A updates the AMOUNT column in various rows of table X, and transaction B calculates the sum of all AMOUNTS. Lets say they run over time like this, with | marking begin and > commit (N.B. ASCII art, you need a fixed font): ...|--A-->.......|--A-->........ ...........|-B->.........|-B->.. This works as expected...but imagine transactions implicitly begin too early: |-----A-->|---------A-->|------- |------------B->|----------B->|- This will cause the aggregations in B to show "delayed" results. Not at all what one might expect... For more about isolation levels, see e.g. here: http://pgsqld.active-venture.com/transaction-iso.html From cookedm+news at physics.mcmaster.ca Thu Jun 9 11:54:27 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 09 Jun 2005 11:54:27 -0400 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> <3gpsl0Fdhq0mU1@individual.net> Message-ID: Greg Ewing writes: > Rocco Moretti wrote: > > > This gives the wacky world where >> "[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't. > > To solve that, I would suggest a fourth category of "arbitrary > ordering", but that's probably Py3k material. We've got that: use hash(). [1+2j, 3+4j].sort(key=hash) Using the key= arg in sort means you can do other stuff easily of course: by real part: import operator [1+2j, 3+4j].sort(key=operator.attrgetter('real')) by size: [1+2j, 3+4j].sort(key=abs) and since .sort() is stable, for those numbers where the key is the same, the order will stay the same. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From kay.schluehr at gmx.net Sun Jun 12 03:28:17 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 12 Jun 2005 00:28:17 -0700 Subject: Dealing with marketing types... In-Reply-To: References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <1118561296.976993.76560@o13g2000cwo.googlegroups.com> Drazen Gemic wrote: > With Java I depend very little on customers IT staff, sysadmins, etc. If > I need additional functionality in form library, extension, whatever, all > I need is to drop another JAR in, and that does it. Maybe this is for you? http://peak.telecommunity.com/DevCenter/PythonEggs Kay From xnews2 at fredp.lautre.net Wed Jun 8 07:00:37 2005 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 08 Jun 2005 11:00:37 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) References: Message-ID: "Tim Golden" said : > Just wanted to say thank you to Simon and all the > other people who have edited the Python-URL! weekly > digest over the years. Despite my being a pretty much > constant reader of c.l.py and various blogs and other > on-line sources, I still look forward to to its weekly > arrival. > That's both because of the mild editorial introductions > and also because it will almost certainly pick up > something I've missed (sometimes because it's a gem > buried deep within a thread which I've long since given > up on!) Same here : thanks for letting us get away with being lazy(er) ! :-) -- YAFAP : http://www.multimania.com/fredp/ From tim.golden at viacom-outdoor.co.uk Mon Jun 13 11:53:43 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 13 Jun 2005 16:53:43 +0100 Subject: [OT ?] (Pythonic) detection word protected files Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8CA@vogbs009.gb.vo.local> [Gilles Lenfant] | I'm building an utility that makes a catalog of M$ word files | in a giant | directory tree. The password protected files must be marked, and I | didn't find how to guess which files are password protected and which | ones are not. | | I can't use the COM interface for this because the utility | must run on a | Linux Samba server. | | I didn't find anything satisfying in M$ related sites (like msdn) or | forums or google. This page looks like it might be useful: http://wvware.sourceforge.net/wvInfo.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From passion_to_be_free at hotmail.com Thu Jun 16 13:25:13 2005 From: passion_to_be_free at hotmail.com (passion_to_be_free at hotmail.com) Date: 16 Jun 2005 10:25:13 -0700 Subject: log in to a website Message-ID: <1118942713.133261.258480@o13g2000cwo.googlegroups.com> I'm learning python, and my goal is to write a script that will log into a website for me. The site uses HTTPS, the form uses the "POST" method. >From what I've been able to find so far, it looks like i need to use the urllib2 module...does anyone know where I can find some good sample code to read up on how to do this? -Thx From waldemar.osuch at gmail.com Tue Jun 7 13:10:30 2005 From: waldemar.osuch at gmail.com (waldemar.osuch at gmail.com) Date: 7 Jun 2005 10:10:30 -0700 Subject: School Administration Software References: Message-ID: <1118164230.283656.16980@o13g2000cwo.googlegroups.com> Greg Lindstrom wrote: > Hello- > [snip] > So...do any of you have experience with any of this software? This is > for a small (~400 students k-12), private school that is not swimming in > taxpayer dollars and I would rather use Open Source because we will > probably need to customize some reports, etc. Any advice you have would > be welcome. > > Thanks, > --greg > > -- > Greg Lindstrom 501 975.4859 (office) > Senior Programmer 501 219-4455 (fax) > NovaSys Health greg.lindstrom at novasyshealth.com > Little Rock, Arkansas > Schooltool ? http://www.schooltool.org/ > "We are the music makers, and we are the dreamers of dreams." W.W. From datacide at gmail.com Wed Jun 8 07:49:53 2005 From: datacide at gmail.com (datacide) Date: 8 Jun 2005 04:49:53 -0700 Subject: Create our own python source repository In-Reply-To: <1118170303.568984.242610@z14g2000cwz.googlegroups.com> References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> <1118156654.634103.186390@o13g2000cwo.googlegroups.com> <1118170303.568984.242610@z14g2000cwz.googlegroups.com> Message-ID: <1118231393.450388.14570@o13g2000cwo.googlegroups.com> Hello, I use MoinMoin (a python wiki) desktop edition to collect and sort code snippets and classes. It runs standalone (comes with its own webserver) and does the job just fine. regards dc From twic at urchin.earth.li Thu Jun 30 13:48:31 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 30 Jun 2005 18:48:31 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> Message-ID: On Thu, 30 Jun 2005, Simon Brunning wrote: > On 29 Jun 2005 15:34:11 -0700, Luis M. Gonzalez wrote: > >> What's exactly the "cockney" accent? Is it related to some place or >> it's just a kind of slang? > > The cockney accent used to be pretty distinct, but these days it's > pretty much merged into the "Estuary English" accent common throughout > the South East of England. I grew up in Colchester, in the heart of Essex, the homeland of Estuary English; i was recently told by a couple of Spanish colleagues that i sounded just another colleague who has a Cockney accent. Although, in fact, my parents aren't Essexen, and i left the county seven years ago, so my accent is weird hybrid of Estuary and RP, and the colleague isn't a real Cockney - i think he's from east-north-eastern London - but he does overcompensate pronounciation-wise, so i don't know what it all means. It's also complicated by the fact that Essex actually has two completely different accents - the town accent, which is Estuary and is pretty much derived from emigrants from East London, and the country accent, which is indigenous, and very similar to the Suffolk and Norfolk accents. I grew up in a village and went to school (and went drinking etc) in the nearby town, so i was exposed to a different accents at different times of day! >> I'm not sure, but I think that I read somewhere that it is common in >> some parts of London, and that it is a sign of a particular social >> class, more than a regionalism. Is that true? > > Cockney was London's working class accent, pretty much, thought it was > frequently affected by members of the middle classes. Estuary English > has taken over its position as the working class accent these days, > but with a much wider regional distribution. blimey guvnor you is well dahn on ar muvver tung, innit? > How off topic is this? Marvellous! Spike Milligan did an excellent sketch in the style of a TV pop-anthropology documentary visiting the strange and primitive Cockanee people of East London. It was part of one of his Q series; i'm not sure which, but if it was Q5, then it would have had a direct impact on the Monty Python team, since that series basically beat them to the punch with the format they'd planned to use, forcing them to switch to the stream-of-consciousness style that became their trademark and which is the basis for python's indentation-based block structure. Therefore, if it hadn't been for the quirks of the Cockney accent, we'd all be using curly brackets and semicolons. FACT. tom -- I know you wanna try and get away, but it's the hardest thing you'll ever know From s4somesh at gmail.com Thu Jun 2 01:01:54 2005 From: s4somesh at gmail.com (Shrii) Date: 1 Jun 2005 22:01:54 -0700 Subject: Unicode string in exec() Message-ID: <1117687496.341548.117760@g14g2000cwa.googlegroups.com> 1.I read a unicode file by using codec 2.I want to pass that string to exec() statement 3.But one of my character (U+0950) in that string is not showing properly in the output got by that exec() statement could anyone help me to get proper output. ? somesh From karthish at gmail.com Mon Jun 13 15:50:00 2005 From: karthish at gmail.com (Karthish) Date: 13 Jun 2005 12:50:00 -0700 Subject: Access Database Using Python Message-ID: <1118692200.684123.317750@g14g2000cwa.googlegroups.com> I'm writing a script to look through DNA sequences in a database and select sequences I require. So far, my code looks like this for authentication: import os import Bio.Clustalw from Bio.Alphabet import IUPAC import pdb import sys import os import urllib import urllib2 import urllib userid = 'kmdawg' password = 'kmdawgyeah' location = 'index.html' params = urllib.urlencode({'user': userid, 'password': password, 'request_uri': location}) f = urllib2.urlopen("http://www.gene-regulation.com/login?%s" % params) print f.read() When I run the program, I see the following: ______________ Redirect

Please stand by, you will be redirected toindex.html...

________________ The code works as it is. How would I modify this script to display the page "http://www.gene-regulation.com/cgi-bin/pub/databases/transfac/getTF.cgi?AC=R00077"? I can't figure out how to authenticate and then load a page, since the page requires cookies for authentication. Thanks. From steve at REMOVETHIScyber.com.au Tue Jun 21 11:09:11 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 22 Jun 2005 01:09:11 +1000 Subject: Nested lists [was Re: tree functions daily exercise: Table] References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> Message-ID: Removing cross-posts to java and scheme lists. On Tue, 21 Jun 2005 01:54:40 -0700, Xah Lee wrote: > here's the Python spec for the Table function: > > '''Table(f,[iStart,iEnd,iStep]) returns a list of f applied to the > range range(iStart,iEnd,iStep). > Example: Table(f,[3,10,2]) returns [f(3),f(5),f(7),f(9)] > Table(f,[iStart,iEnd,iStep], [jStart,jEnd,jStep], ...) returns a nested > list of f(i,j,...) applied thru the iterators. > Example: Table(f,[1,3,1],[2,6,2]) returns [f(3),f(5),f(7),f(9)]''' Xah's specifications doesn't make sense. He says that Table(f, ilist, jlist, ...) should return a nested list, but then contradicts himself in the example, which is not a nested list. He also doesn't explain what i and j are supposed to be. Since his specs make no sense to me, I'll simply ignore them and use my own. This demonstrates some interesting features of Python, in particular, the way it can pack and unpack multiple arguments and how to produce nested lists. def table(f, start, end=None, step=1): """Returns a list of f applied to the range(start, end, step). Like range(), table() accepts defaults for start and step (zero and one respectively). """ if end is None: # syntactic sugar allowing us to use a single # argument for end start, end = 0, start return [f(x) for x in range(start, end, step)] def table_nested(f, *args): """Returns a nested list of lists of f applied in turn to each set of arguments. Each argument is expected to be a list of no more than three int arguments, suitable to use as arguments to range(). Example: table_nested(f, [0, 3, 1], [3, 10, 2]) returns [[f(0), f(1), f(2)], [f(3), f(5), f(7), f(9)]] """ L = [] for arg in args: L.append(table(f, *arg)) return L py> nested_table(str, [4], [3, 7], [3, 10, 2]) [['0', '1', '2', '3'], ['3', '4', '5', '6'], ['3', '5', '7', '9']] > Another issue noted is that the so-called "list comprehension" > syntax construction in Python actually also contained a semantic > irregularity. That is to say, when the loops are nested inside a > list-comprehension, it still produced a flat list, instead of a nested > list. Wrong. Nesting list comprehensions two deep (list of lists) is simple. py> [[x, x**2, 2**x] for x in range(4)] [[0, 0, 1], [1, 1, 2], [2, 4, 4], [3, 9, 8]] py> [range(n) for n in range(5)] [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]] py> [range(n, n+4) for n in range(0, 16, 4)] [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]] Nesting three or more deep is harder, but not impossible. def inner(n): return [[x, x**2] for x in range(1, n+1)] def outer(n): return [[x, inner(x)] for x in range(1, n+1)] py> outer(0) [] py> outer(1) [[1, [[1, 1]]]] py> outer(2) [[1, [[1, 1]]], [2, [[1, 1], [2, 4]]]] At the risk of making hard-to-maintain code, we can turn outer into a single list comprehension: def outer2(n): return [[x, [[y, y**2 ] for y in range(1, x+1)]] for x in range(1, n+1)] py> outer2(2) [[1, [[1, 1]]], [2, [[1, 1], [2, 4]]]] > This is quite a pain. I didn't realize this until i completed my code > and realized the result is a flat list. Here's the "wrong" code as a > result: Well, at least he realises that his code is wrong. > def Table2(fun, *itrs): > dim=len (itrs) > dummies = ['i'+repr(i) for i in Range(0,dim-1)] > ll = [ (dummies[i],itrs[i][0],itrs[i][1],itrs[i][2]) for i in > Range(0,dim-1)] > funString='f(' > for i in dummies: funString += i + ',' > funString = funString[0:len(funString)-1] > funString += ')' > loopStr= '[ ' + funString > for i in range(0,dim): > loopStr += ' for ' + dummies[i] + ' in Range(' + > repr(itrs[i][0])+','+repr(itrs[i][1])+','+repr(itrs[i][2]) + ') ' > loopStr += ' ]' > print loopStr > return eval(loopStr) What an awful mess. > I was happy thinking that i'm done until am really dismayed by a > realization of this semantic irregulary. Both syntax irregularity and > semantic irregularity are ubiquitous in imperative languages. A poor craftsman blames his tools. -- Steven. From fredrik at pythonware.com Wed Jun 29 09:15:09 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Jun 2005 15:15:09 +0200 Subject: XMLRPC and non-ascii characters References: <1120051367.9425.4.camel@localhost.localdomain> Message-ID: Joxean Koret wrote: > I'm having troubles to make my XMLRPC application working with non > ASCII characters. you cannot just pass in 8-bit strings in arbitrary encodings and expect the XML- RPC layer to automagically figure out what you're doing. you can either use the encoding option to the ServerProxy constructor to tell the proxy what encoding to assume for 8-bit strings: proxy = ServerProxy(uri, encoding="iso-8859-1") (see http://www.python.org/doc/current/lib/module-xmlrpclib.html for details) or you can do things the right way and use Unicode strings for non-ASCII text. From rem642b at Yahoo.Com Mon Jun 27 01:28:07 2005 From: rem642b at Yahoo.Com (Robert Maas, see http://tinyurl.com/uh3t) Date: Sun, 26 Jun 2005 22:28:07 -0700 Subject: A Module on Time & Date References: <20050510093620.35902.qmail@web61108.mail.yahoo.com> Message-ID: > From: Sakesun Roykiattisak > import datetime > print datetime.datetime.now() That doesn't work here: % python Python 2.2.2 (#1, Feb 17 2003, 21:01:54) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime Traceback (most recent call last): File "", line 1, in ? ImportError: No module named datetime By comparison, import os works just fine, for example: http://www.rawbw.com/~rem/HelloPlus/hellos.html#python1 From rex.eastbourne at gmail.com Wed Jun 29 11:45:03 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 29 Jun 2005 08:45:03 -0700 Subject: Debugger Confusion In-Reply-To: References: Message-ID: <1120059903.248536.135970@o13g2000cwo.googlegroups.com> Also, when I try running pdb in my Emacs shell, I get very weird behavior: for instance, I'll hit 'h' and enter twenty times with no output. Then, all of a sudden, twenty output messages will pop up. From desertgarden at netscape.com Thu Jun 16 16:02:19 2005 From: desertgarden at netscape.com (Brian) Date: Thu, 16 Jun 2005 20:02:19 GMT Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') In-Reply-To: <1118943794.041570.45670@o13g2000cwo.googlegroups.com> References: <1118943794.041570.45670@o13g2000cwo.googlegroups.com> Message-ID: Here's a site that provides an easy, *beginners* example of how to do threading. You might find this useful too... :-) http://www.codesampler.com/python.htm (Look for the "Spawning Threads" section.) Brian --- wittempj at hotmail.com wrote: > see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 for a > useful recipe on how to do threading > From flupke at nonexistingdomain.com Tue Jun 7 02:15:51 2005 From: flupke at nonexistingdomain.com (flupke) Date: Tue, 07 Jun 2005 06:15:51 GMT Subject: poker card game revisited (code included) Message-ID: Hi, i've included the code so interested people can take a look. I've tried to expand on the thread of 26/05/2005 on "Checking for a full house". Code is suboptimal as I coded it rather quickly. I've added the "normal" classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere "straight" detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like "deuces wild", what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen ===================== CODE ===================== """ Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger """ import random class Card(object): """ Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace """ suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] rankList = [ "narf", "narf", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, suit=0, rank=0): """ Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) """ self.suit = suit self.rank = rank def __str__(self): """ Pretty print a card """ return self.rankList[self.rank] + " of " + self.suitList[self.suit] def __cmp__(self, other): """ Compare 2 cards @type other: card @param other: the card to compare with """ # check the suits if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 # suits are the same... check ranks if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): """ Represents a deck of cards. We can have different decks of cards """ DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): """ Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) """ self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): """ Pretty print the deck """ for card in self.cards: print card def __str__(self): """ Pretty print the deck """ s = "" for i in range(len(self.cards)): s = s + " "*i + str(self.cards[i]) + "\n" return s def sort(self,rank=True,suit=False): """ Sort the deck """ def sortonrank(x,y): if x.rank > y.rank: return 1 if x.rank < y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit > y.suit: return 1 if x.suit < y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): """ Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle """ import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print " shuffle %s " % shuffle for i in range(nCards): j = random.randrange(i, nCards) [self.cards[i], self.cards[j]] = [self.cards[j], self.cards[i]] def removecard(self, card): """ Removes a card from the deck. Do not use this function if you want to keep playing with the same deck afterwards! @type card: card @param card: card you want to remove """ if card in self.cards: self.cards.remove(card) return 1 else: return 0 def removecardindex(self,index): """ Remove a card at the given index. You get the card so you can return it to the deck later """ if ( index >= 0 and index <= len(self) ): return self.cards.pop(index) def addcard(self,card): """ Add the card back to the bottom of the deck @type card: card @param card: card you want to add to the deck """ self.cards.append(card) def popcard(self): """ Get the top card and deal it """ return self.cards.pop() def isempty(self): """ Is the deck empty? """ return (len(self.cards) == 0) def deal(self, hands, ncards=999): """ Deal a number of cards to the hands. ncards are dealt to each hand. @type hands: list @param hands: list of hands to deal to @type ncards: int @param ncards: number of cards to deal to each hand """ nhands = len(hands) for hand in hands: for i in range(ncards): if self.isempty(): break # break if out of cards card = self.popcard() # take the top card # hand = hands[i % nhands] # whose turn is next? hand.addcard(card) # add the card to the hand # print " deal card %s to %s " % (card,hand) def __len__(self): """ How many cards are there in the deck? """ return len(self.cards) class Hand(Deck): """ A hand is a kind of deck that contains cards """ def __init__(self, name=""): """ Make a hand of cards @type name: string @param name: hand belongs to person with this name """ self.cards = [] self.name = name """ def addcard(self,card) : self.cards.append(card) """ def __str__(self): """ Pretty print the hand """ s = "Hand " + self.name if self.isempty(): s = s + " is empty\n" else: s = s + " contains\n" return s + Deck.__str__(self) class CardGame(object): """ A card game """ def __init__(self): """ Start a card game by taking a deck of cards and shuffling it """ self.deck = Deck() self.deck.shuffle() class Rank(object): def __init__(self,rnk,name): self.rnk = rnk self.name = name def __str__(self): return self.name class HandComparator(object): pass class HandEvaluator(object): RANK_NOTHING = Rank(1,"High card") RANK_PAIR = Rank(2,"Pair") RANK_DOUBLEPAIR = Rank(3,"Double Pair") RANK_THREEOFAKIND = Rank(4,"Three of a Kind") RANK_STRAIGHT = Rank(5,"Straight") RANK_FLUSH = Rank(6,"Flush") RANK_FULLHOUSE = Rank(7,"Full House") RANK_FOUROFAKIND = Rank(8,"Four of a Kind") RANK_STRAIGHTFLUSH = Rank(9,"Straight Flush") RANK_FIVEOFAKIND = Rank(10,"Five of a Kind") def __init__(self): print "Ready to evaluate hands" def is_straight(self,hand,numwildcards=0): """Checks for a five card straight Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games). Outputs: highest card in a five card straight or 0 if not a straight. Original list is not mutated. Ace can also be a low card (i.e. A2345). >>> is_straight([14,2,3,4,5]) 5 >>> is_straight([14,2,3,4,6]) 0 >>> is_straight([10,11,12,13,14]) 14 >>> is_straight([2,3,5], 2) 6 >>> is_straight([], 5) 14 >>> is_straight([2,4,6,8,10], 3) 12 >>> is_straight([2,4,4,5,5], 2) 6 """ hand = set(hand) if 14 in hand: hand.add(1) for low in (10,9,8,7,6,5,4,3,2,1): needed = set(range(low, low+5)) if len(needed & hand) + numwildcards >= 5: lhand = [x for x in hand] ind = lhand.index(low+4) str = lhand[ind-4:ind+1] return low+4 return -1 def is_group(self,hand,numwildcards=0): """Checks for pairs, threes-of-kind, fours-of-a-kind, and fives-of-a-kind Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games) Output: tuple with counts for each value (high cards first) for example (3, 14), (2, 11) full-house Aces over Jacks for example (2, 9), (2, 7) two-pair Nines and Sevens Maximum count is limited to five (there is no seven of a kind). Original list is not mutated. >>> groups([11,14,11,14,14]) [(3, 14), (2, 11)] >>> groups([7, 9, 10, 9, 7]) [(2, 9), (2, 7)] >>> groups([11,14,11,14], 1) [(3, 14), (2, 11)] >>> groups([9,9,9,9,8], 2) [(5, 9), (2, 8)] >>> groups([], 7) [(5, 14), (2, 13)] """ result = [] counts = [(hand.count(v), v) for v in range(2,15)] for count, value in sorted(counts, reverse=True): newcount = min(5, count + numwildcards) # Add wildcards upto five numwildcards -= newcount - count # Wildcards remaining if newcount > 1: result.append((newcount, value)) return result def is_flush(self,hand,numwildcards=0): result = [] counts = [(hand.count(v), v) for v in range(0,4)] for count, suit in sorted(counts, reverse=True): newcount = min(5, count + numwildcards) # Add wildcards upto five numwildcards -= newcount - count # Wildcards remaining if newcount >= 5: # we have a flush, return the flush suit # result.append((newcount, value)) return suit return -1 def is_straightflush(self,hand,numwildcards=0): return -1 def getrank(self,hand,numwildcards=0): result_group = None result_straight = None result_flush = None result_sf = None nrofresult = 0 rank = None cardranks = [card.rank for card in hand.cards] cardsuits = [card.suit for card in hand.cards] # check for groups result_group = self.is_group(cardranks,numwildcards) rank = self.__rankgroup(result_group) # if rank is lower than a four of a kind, a straight flush is # still better """ if (rank[0] < HandEvaluator.RANK_FIVEOFAKIND): result_sf = is_straightflush(hand """ # if rank is lower than a fullhouse, a flush might be higher if (rank[0] < HandEvaluator.RANK_FULLHOUSE): result_flush = self.is_flush(cardsuits,numwildcards) if ( result_flush > -1 ): return self.__rankflush(result_flush) # if rank is lower than a straight, it's useful to check for a # straight if (rank[0] < HandEvaluator.RANK_STRAIGHT): result_straight = self.is_straight(cardranks,numwildcards) if ( result_straight > -1 ): return self.__rankstraight(result_straight) # return the rank return rank def __namerank(self,rank): return Card.rankList[rank] def __namesuit(self,suit): return Card.suitList[suit] def __rankgroup(self,group): pair = 0 trips = 0 ranks = [] if (len(group) == 0 ): return (HandEvaluator.RANK_NOTHING,ranks) for count,rank in group: ranks.append(self.__namerank(rank)) if ( count >= 5 ): return (HandEvaluator.RANK_FIVEOFAKIND,ranks) elif ( count == 4 ): return (HandEvaluator.RANK_FOUROFAKIND,ranks) elif ( count == 3 ): trips += 1 elif ( count == 2 ): # can lead to a double pair # check to see if we have a next pair pair += 1 # Full house? if ( trips >= 2 ): return (HandEvaluator.RANK_FULLHOUSE,ranks) if ( trips == 1 and pair >= 1 ): return (HandEvaluator.RANK_FULLHOUSE,ranks) # Trips if ( trips >= 1 ): return (HandEvaluator.RANK_THREEOFAKIND,ranks) # Check for a pair or a double pair if ( pair >= 2 ): return (HandEvaluator.RANK_DOUBLEPAIR,ranks) elif ( pair == 1 ): return (HandEvaluator.RANK_PAIR,ranks) def __rankflush(self,suit): ranks = [] ranks.append(self.__namesuit(suit)) return (HandEvaluator.RANK_FLUSH,ranks) def __rankstraight(self,highcard): ranks = [] ranks.append(self.__namerank(highcard)) return (HandEvaluator.RANK_STRAIGHT,ranks) def getprintablerank(self,handeval): rank = handeval[0] cards = handeval[1] what = "" if ( rank == HandEvaluator.RANK_PAIR or rank == HandEvaluator.RANK_THREEOFAKIND or rank == HandEvaluator.RANK_FOUROFAKIND or rank == HandEvaluator.RANK_FIVEOFAKIND ): what = "%s of %s's " % (rank, cards[0]) elif ( rank == HandEvaluator.RANK_FULLHOUSE ): what = "%s, %s's over %s's" % (rank, cards[0], cards[1]) elif ( rank == HandEvaluator.RANK_DOUBLEPAIR ): what = "%s, %s's and %s's" % (rank, cards[0], cards[1]) elif ( rank == HandEvaluator.RANK_NOTHING ): what = "%s" % rank elif ( rank == HandEvaluator.RANK_STRAIGHT ): what = "%s, %s high" % (rank,cards[0]) elif ( rank == HandEvaluator.RANK_FLUSH ): what = "%s of %s" % (rank,cards[0]) return what if __name__ == "__main__": # Deal to 5 players, first 3 cards, then 1 and another 3 todeal = [] for hnd in range(0,5): todeal.append(Hand("Player %s" % (hnd + 1) )) d = Deck() d.shuffle(3) print " Dealing 2 cards to all players " d.deal(todeal,3) print " Dealing 1 cards to all players " d.deal(todeal,1) print " Dealing 2 cards to all players " d.deal(todeal,3) print " What are the hands of the players " ev = HandEvaluator() for hand in todeal: print "%s" % hand rank = ev.getrank(hand) print "%s" % ev.getprintablerank(rank) print "*"*40 print " What's left in the deck?" print "%s" % d print " %s cards left in the deck " % len(d) From me at privacy.net Tue Jun 14 07:59:31 2005 From: me at privacy.net (Dan Sommers) Date: 14 Jun 2005 07:59:31 -0400 Subject: Resume after exception References: Message-ID: On Tue, 14 Jun 2005 10:09:30 +0100, "Richard Lewis" wrote: > Hi there, > Is it possible to have an 'except' case which passes control back to the > point after the exception occurred? Not that I can think of. [ example of "interrupting" a file-reading function in order to ask the user if they really want to read a locked file ] I would rewrite that this way (untested, and without error checking): def open_file(file_name, read_if_locked=False): f = file(file_name) [read first line] if first_line == "FILE LOCKED" and read_if_locked == FALSE: return False [read the rest] return True def open_command(): if open_file("foo.bar") == False: [ask the user what to do] if ans == tkMessageBox.YES: open_file("foo.bar", True ) Regards, Dan -- Dan Sommers From lycka at carmen.se Wed Jun 22 11:34:57 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 22 Jun 2005 17:34:57 +0200 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: Thomas Bartkus wrote: > If you are writing strictly for the MS Windows platform > And > If the database is running single user with a "locally stored database" on a > Windows workstation. > Then > The MS Access file based (.mdb) system is hard to argue with. I disagree. What does .mdb/jet without Access offer you that you don't get from e.g. SQLite except vendor lock-in and horrible deviations from the SQL standard? Ok, it does give you somewhat stronger typing, which you might possibly want, but if that's an issue, I'd suggest embedded firebird (if we want serverless). I'm not entirely sure something SQLish is the way to go though. Also, the best ODBC adaper for Python, mxODBC, isn't free. Last time I used adodbapi, it was a bit buggy, and pure ADO or DAO solutions don't follow the Python standard DB-API 2. From mwm at mired.org Thu Jun 30 17:41:34 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 30 Jun 2005 17:41:34 -0400 Subject: script fichiers binaires lecture =?iso-8859-1?q?=E9criture?= References: <1120122593.162554.71410@g14g2000cwa.googlegroups.com> <1120123333.646354.125080@z14g2000cwz.googlegroups.com> <42c3c8ba$0$23824$626a14ce@news.free.fr> Message-ID: <86oe9na5f5.fsf@bhuda.mired.org> bruno modulix writes: >> Be aware that I'm >> using pyhton 1.5, > Err... latest is 2.4.1, and the language has really, really changed. You > should consider upgrading... > >> unfortunately... > > BTW, in 1.5.x, you can use the String module instead of string class > methods: In python 1.5.x, string objects didn't have methods. That's why he's getting the error. He has to use the string module instead. I agree with bruno - you *really* should upgrade. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From guy.lateur at b-b.be Thu Jun 2 05:50:55 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 02 Jun 2005 09:50:55 GMT Subject: how to retrieve info about print jobs Message-ID: <3EAne.108100$xW2.6437935@phobos.telenet-ops.be> Hi all, We have several printers in our company network. I would like to know if it is possible to check the current print jobs/queues for each of them. That way, if a user wants to print something (big), I could give her a hint as to which printer would get the job done first. We're using win2k and xp, btw. Any ideas? I'm pretty new to python, I'm afraid.. TIA, g From flamesrock at gmail.com Mon Jun 6 03:39:06 2005 From: flamesrock at gmail.com (flamesrock) Date: 6 Jun 2005 00:39:06 -0700 Subject: easiest way to split a list into evenly divisble smaller lists, and assign them to variables? In-Reply-To: <7xekbgj6y2.fsf@ruckus.brouhaha.com> References: <1118040724.644534.259460@g44g2000cwa.googlegroups.com> <7xekbgj6y2.fsf@ruckus.brouhaha.com> Message-ID: <1118043546.195468.87720@g44g2000cwa.googlegroups.com> hmmm..that makes much more sense. thanks :) From lambacck at gmail.com Tue Jun 28 19:24:34 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Tue, 28 Jun 2005 19:24:34 -0400 Subject: Embedding python in C In-Reply-To: <200506281709.58266.philippecmartin@sbcglobal.net> References: <3Qfwe.519$Ox3.92@newssvr12.news.prodigy.com> <200506281653.46932.philippecmartin@sbcglobal.net> <200506281709.58266.philippecmartin@sbcglobal.net> Message-ID: pyrex can be used for embedding too. http://www.freenet.org.nz/python/embeddingpyrex/ On 6/28/05, Philippe C. Martin wrote: > Actually maybe not ... looking at the doc: > > I have modules already coded in Python, and I need a C wrapper so C > applications may link with it. > > Regards, > > Philippe > > > > On Tuesday 28 June 2005 04:53 pm, Philippe C. Martin wrote: > > Sounds like it, thanks. > > > > Philippe > > > > On Tuesday 28 June 2005 09:10 pm, Chris Lambacher wrote: > > > Pyrex might be what you are looking for: > > > http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/ > > > > > > -Chris > > > > > > On 6/28/05, Philippe C. Martin wrote: > > > > Hi, > > > > > > > > Is there a program out there that would generate the C code to > > > > instantiate objects and call them: > > > > > > > > ex: miracle.exe -i mymodule.py -o module_internface.c ? > > > > > > > > I seem to recall a _yes_ to that but I got a memory overflow :-) > > > > > > > > Thanks, > > > > > > > > Philippe > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > -- > ************************************* > Philippe C. Martin > SnakeCard, LLC > www.snakecard.com > +1 405 694 8098 > ************************************* > -- Christopher Lambacher lambacck at computer.org From sigzero at gmail.com Mon Jun 13 19:37:19 2005 From: sigzero at gmail.com (sigzero at gmail.com) Date: 13 Jun 2005 16:37:19 -0700 Subject: win32evtlog Message-ID: <1118705839.260490.13140@z14g2000cwz.googlegroups.com> Is anyone versed in pulling out information from the Windows (2000) event log? I have looked at the docs and I am in the dark as to how to do it. Do what? I am looking to pull out all events with "error" as the type. Robert From erchamion.beren at gmail.com Fri Jun 10 11:25:32 2005 From: erchamion.beren at gmail.com (sinan ,) Date: Fri, 10 Jun 2005 18:25:32 +0300 Subject: about accessing mysql In-Reply-To: <59dfa14505061008211c41fe1@mail.gmail.com> References: <59dfa14505061008211c41fe1@mail.gmail.com> Message-ID: <59dfa14505061008251f34412@mail.gmail.com> oh my system is debian - sarge with python 2.3 From fairwinds at eastlink.ca Mon Jun 27 23:13:09 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Tue, 28 Jun 2005 00:13:09 -0300 Subject: Python JavaScript solution to hold vertical scroll bar In-Reply-To: <1119796512.220953.233900@g14g2000cwa.googlegroups.com> Message-ID: <8DE5844C-E782-11D9-9AD1-000A27B3B070@eastlink.ca> Hi. I am putting together a database application on Zope. I have built a pager for my records (20 per page) but do not want the browser scroll bars to reset to the top of the browser each time the pager is advanced to the previous or next page. The normal behavior is fine for everything but the anchor tags I am using for the pager. Instead of resetting when a new page is sellected, I want the vertical scrollbar to maintain its position so when the link is clicked, the vertical scrollbar position is passed to the next page (so the page does not jerk to the top but stay in the same position). I am using css to style anchor tags as buttons and am currently passing the record start position for the page to the next page. ie 2 I am assuming the best way of handling this would be to pass the current vertical scroll position as a parameter to a JavaScript. Does anyone have such a solution or other advice for solving this? Regards, David From jan.danielsson at gmail.com Sun Jun 5 19:10:05 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Mon, 06 Jun 2005 01:10:05 +0200 Subject: "Opposite" of splitting? Message-ID: <42a38506$1@griseus.its.uu.se> Hello all, I have a list of integers: q = [ 1, 2, 4, 7, 9 ] which I would like to convert to a string: "1,2,4,7,9" This is *very* easy to do with a simple while loop.. But I suspect that there is a more elegant way to do it in Python. Is there? If so: How? From mfranklin1 at gatwick.westerngeco.slb.com Fri Jun 10 08:51:54 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 10 Jun 2005 13:51:54 +0100 Subject: SMTP Test Rig ( SMTPRIG.PY v1.0 ) In-Reply-To: <002f01c56dba$601ff960$ccbefea9@twilliams> References: <002f01c56dba$601ff960$ccbefea9@twilliams> Message-ID: Tim Williams wrote: > After a few posts recently, I have put together an SMTP test rig that will > receive emails and either store them to a file, write them to a console, or > both. > > Does anyone have any suggestions on where I can get it hosted as a utility > for general public use? > > TIA > > Tim > Python cookbook perhaps? http://aspn.activestate.com/ASPN/Python/Cookbook/ Martin From lycka at carmen.se Thu Jun 23 03:36:29 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 23 Jun 2005 09:36:29 +0200 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> <3tiue.27$jv6.1568@news.uswest.net> Message-ID: Cameron Laird wrote: > OK, I'm with you part of the way. Typical "Access" developers > are *always* involved with DLL hell, right? You're surely not > saying that Python worsens that frustration, are you? I think Dan was commenting on flaws in Microsoft's products, not in Python. As I understand it, he was suggesting to use something else than Access with Python, not something else than Python with Access. The O.P. wanted a database for his Python app, and Thomas Bartkus suggested Access. From wookiz at hotmail.com Thu Jun 9 21:33:03 2005 From: wookiz at hotmail.com (wooks) Date: 9 Jun 2005 18:33:03 -0700 Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: <1118367183.769655.216760@g43g2000cwa.googlegroups.com> Thank you. I have taken on board your input. The link is to an item on ebay entitled the Python Developers Handbook by Andre Lessa. The starting price of the auction is 5 pounds and costs 5 pounds to shipping as it weighs 1.6kg. The book was published in 2000, it's ISBN is 0672319942 RRP $44.99. It is unread and in like new condition. I am the making the post as the seller. Finally I am not making a commercial announcement as I do not sell books for a living. I am selling items from my personal library as I have not had work for quite some time. I have done my best to correct the errors you pointed out and address the issues you raised. From der.rudi at planet-dot-nl.no-spam.invalid Thu Jun 30 05:21:48 2005 From: der.rudi at planet-dot-nl.no-spam.invalid (DeRRudi) Date: Thu, 30 Jun 2005 09:21:48 +0000 (UTC) Subject: Open running processes References: Message-ID: > Tim Goldenwrote: > If you wanted to send over arbitrary data from another application, > then this is certainly a way to do it. (Another way might be to use a > Windows pipe, for example). My point was only that if you are signalling > an event as a wake-up call plus an atom of extra information saying > "max" or "min", and you weren't considering any expansion of this > vocabulary to include other commands, then two distinct events might > be simpler, one signalling "maximize", the other "minimize". > > Please don't take this as any criticism of your work: there's no one > right design decision here; I was merely curious as to the reasons > behind yours. > > TJG > Thanx for thinking with me! It really helps to have some other opinions! It might look simpeler to make two distinct events. But reading out the mm is really easy to do. So i didn't make more events for maximizing and minimizing. But further on i'm gonna use it. I think by now i have all the thing's i need to solute my problems. Thnx Rudi From twic at urchin.earth.li Wed Jun 15 06:52:12 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Wed, 15 Jun 2005 11:52:12 +0100 Subject: implicit variable declaration and access In-Reply-To: <42aeddf7$1@nntp0.pdx.net> References: <42aeddf7$1@nntp0.pdx.net> Message-ID: On Tue, 14 Jun 2005, Scott David Daniels wrote: > Tom Anderson wrote: >> ... If it's not, try: >> x = "myVarName" >> y = "myVarValue" >> locals()[x] = y > > Sorry, this works with globals(), but not with locals(). Oh, weird. It works when i tried it. Aaaah, i only tried it at the interactive prompt. If i actually try writing a function which does, that, yes, i get: >>> def foo(): ... locals()["myvar"] = 42 ... print myvar ... >>> foo() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in foo NameError: global name 'myvar' is not defined >>> My bad. tom -- Gens una summus. From smitty_one_each at bigfoot.com Fri Jun 24 18:07:16 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Fri, 24 Jun 2005 17:07:16 -0500 Subject: Office COM automatisation - calling python from VBA References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <87d5qb76jv.fsf@bigfoot.com> >>>>> "guy" == guy lateur writes: guy> Hi all, I am trying to write some code (macro's, if you like) guy> to glue together our Office applications (mainly Word, Excel guy> and Outlook). We have a lot of different projects going on guy> simultaneously. The idea is to develop a centralized guy> framework (starting point, common interface) for my users to guy> view/control their documents/correspondence, on a per project guy> basis. guy> As an example, I'd like to have a control (button, menu guy> entry) in Outlook that allows my users to bring up, say, an guy> email for a certain contact (architect, owner, engineer, ..) guy> on a certain project, with certain attachments, .. Currently, guy> I have a 'public folder' in OL (Exchange) that reflects our guy> project structure. guy> I'll be using COM, and I could probably make an application guy> that controls Outlook (externally). But I'd also like to have guy> this functionality exposed in OL itself. So I guess I'll need guy> to use VBA, but I don't really like VBA - relax, please, it's guy> just an opinion.. ;) guy> So, ideally, I'd like to program as much as possible in guy> python (I'm pretty new to that, too, btw), and only use VBA guy> if needed - say, to call python objects/methods (+ wxGUI, guy> please). guy> Would that be an easy, a hard, or an insane strategy? Maybe guy> there are some tutorials on this (searched the list, but guy> didn't quite find any). If anyone happens to have any guy> xp/tips on this, please, fire away! guy> Best regards, g You can have VBA code invoke a python script asynchronously without much trouble. If you peruse MSDN, you can find some examples that will let you have VBA block while waiting on a python script. Serious interaction? I'd probably persue VisualStudio and IronPython, if ActiveState's PythonWin isn't going to be enough. Maybe PythonWin can make Python a COM server; never researched it. Hope these ideas help, Chris From agriff at tin.it Tue Jun 7 18:29:07 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 07 Jun 2005 22:29:07 GMT Subject: time consuming loops over lists References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> <292ca1h01uhj0jfsehvs50i0t6vcaaun01@4ax.com> Message-ID: On Tue, 07 Jun 2005 23:38:29 +0200, "Diez B. Roggisch" wrote: >> I don't see a "break" so why the "/2" ? also IIUC the > >That was the assumption of an equal distribution of the data. In >O-notationn this would be O(n) of course. It was a joke ... the issue is that there was no break statement :-) i.e. your code kept searching even after finding the proper range! Actually that break (with 10 bins) is not terribly important because the cost of the comparision is small compared to the cost of append. The timings I got are.. your code 1.26 sec adding break 0.98 sec direct index computation 0.56 sec 10 bins are so few that with just low-level speedups (i.e. precomputing a list of ranges and str(j)) the code that does a linear scan requires just 0.60 seconds. Hand optimizing the direct computation code the execution time gets down to 0.3 seconds; the inner loop i used is: for i, x in enumerate(data): j = int((x - dmin)/rng) tkns[i] = tks + js[j] with data = range(20, 123120) Andrea From simon.brunning at gmail.com Thu Jun 9 08:09:26 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 9 Jun 2005 13:09:26 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) In-Reply-To: References: Message-ID: <8c7f10c605060905091cc9ff50@mail.gmail.com> On 6/9/05, Joal Heagney wrote: > Great community resource. (Are the old weekly URL's stored somewhere > other than the newsgroup archives?) - but that requires a subscription. I tend to pick up my Dr. Dobbs from a newsagent, so I just use Google Groups. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From gsakkis at rutgers.edu Sun Jun 26 09:47:40 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 26 Jun 2005 06:47:40 -0700 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> <11bsgfo2r2oei42@news.supernews.com> Message-ID: <1119793660.343060.45680@o13g2000cwo.googlegroups.com> "Steven D'Aprano" wrote: > You are welcome to change the specifications of findall() and turn it into > an iterator which returns each match one at a time instead of all at once, > but then the name is misleading, wouldn't you agree? The regex module has since 2.2 a function (and method for regex objects) called finditer that does exactly that. Perhaps str (and unicode) should have it too for consistency ? George From lambacck at gmail.com Wed Jun 8 14:03:34 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Wed, 8 Jun 2005 14:03:34 -0400 Subject: Allocating an array.array of a specific length in pyrex Message-ID: Hi, I have to do some data manipulation that needs to be fast. I had a generator approach (that was faster than a list approch) which was taking approximately 5 seconds to run both encode and decode. I have done a conversion to pyrex and have gotten it down to about 2 seconds to run both encode and decode. An an excerpt from the pyrex code is included below. My question is, is there a better way to allocate the memory for the array.array object than: a = array.array('B', [0] * (pixels * 2)) I already know what the lenght is going to be do I have to give it a sequence(in this case a list of zeros) or is there a C interface that I can use to tell array to allocate memory for pixels*2 unsigned chars. I would prefer to not get into using Numeric or Numarray(I know I can do it with them). Yes the algorithm is functionally correct. I know I am throwing away data. Rest assured that the entropy has been changed such that the data thrown away does not matter (too much). Thanks -Chris import array cdef extern from "Python.h": int PyObject_AsWriteBuffer(object obj, void **buffer, int *buffer_len) int PyObject_AsReadBuffer(object obj, void **buffer, int *buffer_len) cdef int get_w_buffer(obj, unsigned char **data, int *length) except -1: cdef int result cdef void *vd # use a void * result = PyObject_AsWriteBuffer(obj, &vd, length) data[0] = vd return result cdef int get_r_buffer(obj, unsigned char **data, int *length) except -1: cdef int result cdef void *vd # use a void * result = PyObject_AsReadBuffer(obj, &vd, length) data[0] = vd return result def encode(int w, int h, in_a): cdef unsigned int pixels, a_off, str_off cdef int res, inlen, buffer_len cdef unsigned char *in_str, *out_str res = get_r_buffer(in_a, &in_str, &inlen) if res: raise Exception, "Could not get a readable buffer from the input" pixels = w * h a = array.array('B', [0] * (pixels * 2)) res = get_w_buffer(a, &out_str, &buffer_len) if res: raise Exception, "Could not get a writeable buffer to write to" str_off = 0 a_off = 0 while a_off < buffer_len and str_off < inlen: out_str[a_off] = in_str[str_off] out_str[a_off+1] = (in_str[str_off+1] + in_str[str_off+4])/2 out_str[a_off+2] = in_str[str_off+3] out_str[a_off+3] = (in_str[str_off+2] + in_str[str_off+5])/2 str_off = str_off + 6 a_off = a_off + 4 return a -- Christopher Lambacher lambacck at computer.org From ivan at ivan-herman.net Wed Jun 29 11:57:05 2005 From: ivan at ivan-herman.net (Ivan Herman) Date: Wed, 29 Jun 2005 17:57:05 +0200 Subject: PIL question: keeping metadata Message-ID: <42c2c4ca$0$8490$dbd41001@news.euronet.nl> A question on using the PIL library. If I take a jpg file then, say, resize it and save it somewhere else, all metadata that is part of the jpg file is lost. This is a pity: digital cameras routinely add metainformation, so does, for example, Photoshop. Is there any way of keeping this info in PIL? Alternatively, is there a simple image processing package that does it? Ivan From dedTUNIA at yahoo.com Fri Jun 10 03:08:16 2005 From: dedTUNIA at yahoo.com (dedTUNIA NEWS) Date: Fri, 10 Jun 2005 09:08:16 +0200 Subject: dedTUNIA: Gegen kreisrunden Haarausfall - Against circular loss of hair - Contre Alopécie Areata Message-ID: GO: www.dedTUNIA.com Betroffen von Alopecia Areata: dedTUNIA hilft auch Ihnen Affected by Alopecia Areata: dedTUNIA can help you too ! Affect? par l?Alop?cie Areata: dedTUNIA peut vous aider ! Website in: Deutsch - English - Francais GO: www.dedTUNIA.com From claudio.grondi at freenet.de Sat Jun 11 19:53:01 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 11 Jun 2005 23:53:01 -0000 Subject: What is different with Python ? References: Message-ID: <3h14quFeqbr8U1@individual.net> > 4) Yes I agree a mix ("... well spiced soup ...") > seems to be the answer but > my brain somehow wants to formalize it. Here one further suggestion trying to point out, that it probably can't generally be formalized, because the experience one developes after going through the story of "assembly, basic, cobol, lisp, JAVA, c, c++, perl, Tcl, Java, JavaCard" has in my opinion a vital impact on shortcuts one uses and the way of doing things. I mean, that the concept of Python has raised from such experience, so anyone who went through all this, will get the core ideas implemented in Python without any effort, because they were already there as a kind of meta-language used in thinking, unconsciously looking for the chance of beeing expressed in formalized form as a new programming language. To support my thesis I can mention here, that from my experience, Python seems not to be the language of choice for the very beginners, who prefere another approaches which are mostly variants of Basic. Claudio "Philippe C. Martin" schrieb im Newsbeitrag news:GhIqe.3677$%j7.513 at newssvr11.news.prodigy.com... > Thanks , > I have gotten many answers already, some not posted. > > 1) Typing is not the issue - even with RT-Kernels, people use C++ > 2) Yes I find dynamic binding very nice > 3) "... you didn't give many examples of what you did for the > last 18 years (except that that also included RT kernels). ...." assembly > (losts) , basic, cobol, lisp, JAVA, c, c++, perl, Tcl, Java, JavaCard ..... > > I know the "interactive" aspect helps also, the runtime error/exception > checking, the many libraries/tools, the responsiveness of the people on > this newsgroup, the "introspectiveness" of the system, the cross-platform > it deals with, the way it "pushes" people to code in a clean way, the GUI > support, the stability, the extensibility (in and out) .... I'm sure you'll > agree none of that can explain why after 1 week of playing with, I was more > productive in Python than C/C++ just as I know my product (I will not > describe it here as I am not marketing) would not exist today were it not > for Python. > 4) Yes I agree a mix ("... well spiced soup ...") seems to be the answer but > my brain somehow wants to formalize it. > > Regards, > > Philippe > > > > > > Philippe C. Martin wrote: > > > I apologize in advance for launching this post but I might get enlightment > > somehow (PS: I am _very_ agnostic ;-). > > > > - 1) I do not consider my intelligence/education above average > > - 2) I am very pragmatic > > - 3) I usually move forward when I get the gut feeling I am correct > > - 4) Most likely because of 1), I usually do not manage to fully explain > > 3) when it comes true. > > - 5) I have developed for many years (>18) in many different environments, > > languages, and O/S's (including realtime kernels) . > > > > > > Yet for the first time I get (most) of my questions answered by a language > > I did not know 1 year ago. > > > > As I do try to understand concepts when I'm able to, I wish to try and > > find out why Python seems different. > > > > Having followed this newsgroup for sometimes, I now have the gut feeling > > (see 3)) other people have that feeling too. > > > > > > Quid ? > > > > Regards, > > > > Philippe > From cyril.bazin at gmail.com Tue Jun 14 08:12:35 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Tue, 14 Jun 2005 14:12:35 +0200 Subject: Geometry library Message-ID: Hello, I am looking for a geometry library for Python. I want to make some computations like: -distance between vertex and polygon, vertex and polyline, vertex and segment, etc -if a point is inside a polygon, if a polyline intersect a polygon, etc Thanks for your help, Cyril -------------- next part -------------- An HTML attachment was scrubbed... URL: From projecktzero at yahoo.com Tue Jun 28 10:21:40 2005 From: projecktzero at yahoo.com (projecktzero) Date: 28 Jun 2005 07:21:40 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: <1119901432.218536.289030@g47g2000cwa.googlegroups.com> References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> Message-ID: <1119968500.454561.305590@g43g2000cwa.googlegroups.com> I'll 2nd the vote for Pychecker. From paddy3118 at netscape.net Sat Jun 4 02:08:14 2005 From: paddy3118 at netscape.net (Paddy) Date: 3 Jun 2005 23:08:14 -0700 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: <1117865294.079503.51230@o13g2000cwo.googlegroups.com> If you still must have something like the c preprocessor then unix has m4 (and it seems there is a windows version http://gnuwin32.sourceforge.net/packages/m4.htm). The start of the doc reads: GNU M4 ****** GNU `m4' is an implementation of the traditional UNIX macro processor. It is mostly SVR4 compatible, although it has some extensions (for example, handling more than 9 positional parameters to macros). `m4' also has builtin functions for including files, running shell commands, doing arithmetic, etc. Autoconf needs GNU `m4' for generating `configure' scripts, but not for running them. - Paddy. From lbates at syscononline.com Thu Jun 30 17:10:39 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 30 Jun 2005 16:10:39 -0500 Subject: Python for everything? In-Reply-To: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: <3radnVbQrOpNwlnfRVn-3w@comcast.com> Short answer is yes. Longer answer: You will still need C for device drivers and other applications that have high performance demands. Calling C from Python is quite easy. Python can be used from short "shell" scripting to projects that very large (see Zope, Plone, ReportLab, etc). Other than C, Python is the only language that I've been able to write Windows Services (or *nix daemons), COM objects, GUI programs, text programs, and headless programs (e.g. programs that produce no console output). I'm much more productive with Python. By choosing Python you commit to learning one language extremely well instead of jumping all over with different languages that you can remember only poorly. When new version of Python ships, you just learn what is new. If you try to keep up with C, C++, Visual Basic, ... it gets to be impossible. Hope information helps. Larry Bates xeys_00 at yahoo.com wrote: > I posted a article earlier pertaining programming for my boss. Now I am > gonna ask a question about programming for myself. I just finished my > first C++ Class. Next semester is a class on encryption(and it's > probably gonna be a math class too). And finally back in programming in > the fall with C++ and Java 1. The C++ will cover pointers, and linked > lists, sorting algorithms, etc... I run linux and OS X. I have read in > the old days that C was used for everything. It was a systems > programming language, and also did a lot of the same stuff Bash scripts > and perl do now. So, in that era, C did it all, from short to tall. My > question is, can Python "do it all"? I am wondering what to learn as my > scripting language. I have read that perl is good up to about 250 > lines, and after that it gets kind of hairy. However, from what little > I have heard about Python, it's very well suited for readability due to > the whitespace requirements of the language, and very good for large > projects due to it's large amount of modules and it's object oriented > structure. I would like opinions as to the suitability of Python as a > general purpose language for programming unix, everything from short > scripts to muds. Thanks for your patience, opinions, and comments. > > Xeys > From lsumnler at uniqueinsuranceco.com Sat Jun 4 11:42:38 2005 From: lsumnler at uniqueinsuranceco.com (LenS) Date: 4 Jun 2005 08:42:38 -0700 Subject: Newbie Python & XML Message-ID: <1117899758.058056.291670@g47g2000cwa.googlegroups.com> I have a situation at work. Will be receiving XML file which contains quote information for car insurance. I need to translate this file into a flat comma delimited file which will be imported into a software package. Each XML file I receive will contain information on one quote only. I have documentation on layout of flat file and examples of XML file (lot of fields but only container tags and field tags no DTD's,look easy enough). I am just starting to learn python and have never had to work with XML files before. Working in MS Windows environment. I have Python 2.4 with win32 extensions. 1. What else do I need 2. Any examples of program doing the same. 3. Have read some stuff that indicates I may need ? schema of XML layout ???? The rating company will ftp a quote realtime to a dir on my system. the python program will then have to poll the dir for new files and automaticly translate and initiate import. Any help appreciated Len Sumnler From peterbe at gmail.com Fri Jun 17 18:13:47 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 17 Jun 2005 15:13:47 -0700 Subject: ANN: IssueTrackerProduct 0.6.9 with AJAX and Reports References: <1119039397.722318.243960@g49g2000cwa.googlegroups.com> Message-ID: <1119046427.954079.135610@z14g2000cwz.googlegroups.com> Oops! John points out that comp.lang.python.announce is where these things belong. Sorry guys. My fault. From roy at panix.com Wed Jun 29 08:35:37 2005 From: roy at panix.com (Roy Smith) Date: Wed, 29 Jun 2005 08:35:37 -0400 Subject: Is there something similar to ?: operator (C/C++) in Python? References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <86y88um4y3.fsf@bhuda.mired.org> <42c1ecaf$1@nntp0.pdx.net> Message-ID: Andrew Durdin wrote: > Corrected version: > > result = [(lambda: expr0), lambda: expr1][bool(cond)]() I'd go one step further. Most people expect the first item to correspond to True and the second one to correspond to False. So: result = [(lambda: expr0), lambda: expr1][bool(not cond)]() or perhaps even better: result = [(lambda: expr0), lambda: expr1][1 - bool(cond)]() or, if you prefer a slightly more deranged version: result = [(lambda: expr0), lambda: expr1][bool(cond) - 1]() From twic at urchin.earth.li Mon Jun 13 12:29:31 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 13 Jun 2005 17:29:31 +0100 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <5q5qa1lotp0fbjru7i4492lloec251664v@4ax.com> Message-ID: On Mon, 13 Jun 2005, Roy Smith wrote: > O(2) behavior Um ... > Lisp, of course, expanded my mind in ways that only Lisp can (the same > could be said for many things I tried back in those days). Surely you're not saying you experimented with ... APL? > I think it's probably just as important for a CS major to play with > those mind-altering languages as it is to worry about bytes and pointers > and memory locations. But you can't start everywhere, and if you've got > to start someplace, Python let's you concentrate on the real universal > fundamentals of data structures, algorithms, and control flow without > getting bogged down in details. Ah, so you've cleaned yourself up with Guido's Twelve-Step Plan. Amen to that, brother! tom -- Why do we do it? - Exactly! From roccomoretti at hotpop.com Mon Jun 6 11:22:21 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 06 Jun 2005 10:22:21 -0500 Subject: Lost in the inheritance tree... In-Reply-To: References: Message-ID: Adam Munoz Lopez wrote: > Can anyone help with this code... I have infinite > recursion but since I'm pretty new to Python (and > programming in general) I can't find where I did the > mistake. It really does help to start removing things trying to get the minimal code which causes the problem. (untested snippage follows) > ************************************************* > import Tkinter > class RootFrame(Tkinter.Frame): > def __init__(self,parent=None,myHeight=600,myWidth=800,myBd=3,\ > myRelief=Tkinter.RIDGE): > self.createFrames() > > def createFrames(self): > textFrame=TextFrame(self,300,600) > > > class TextFrame(RootFrame): > def __init__(self,parent,myHeight,myWidth): > RootFrame.__init__(self,parent,myHeight,myWidth) > > rootFrame=RootFrame() It appears you create a RootFrame, which creates a TextFrame, which initilizes as a RootFrame, thus creating a TextFrame which initilizes as a RootFrame, thus creating a TextFrame which.... From drool.galz at gmail.com Fri Jun 24 05:25:02 2005 From: drool.galz at gmail.com (Aditi) Date: 24 Jun 2005 02:25:02 -0700 Subject: suggestions invited In-Reply-To: References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119552092.000448.10230@g47g2000cwa.googlegroups.com> <1119555027.087947.100970@g43g2000cwa.googlegroups.com> Message-ID: <1119605102.006033.153490@f14g2000cwb.googlegroups.com> Thank You All for your valuable suggestions. You people definitely eased out my problem and now I can start my work with an eclectic of all of your solutions. Greetings Aditi. From dalke at dalkescientific.com Thu Jun 9 03:51:32 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 09 Jun 2005 07:51:32 GMT Subject: Incorrect number of arguments References: <42A7CDB0.4030703@REMOVEMEcyber.com.au> <42A7D1D1.7040704@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > *eureka moment* > > I can use introspection on the function directly to see > how many arguments it accepts, instead of actually > calling the function and trapping the exception. For funsies, the function 'can_call' below takes a function 'f' and returns a new function 'g'. Calling 'g' with a set of arguments returns True if 'f' would take the arguments, otherwise it returns False. See the test case for an example of use. import new def noop(): pass def can_call(func): # Make a new function with the same signature # code(argcount, nlocals, stacksize, flags, codestring, constants, names, # varnames, filename, name, firstlineno, lnotab[, freevars[, cellvars]]) code = func.func_code new_code = new.code(code.co_argcount, code.co_nlocals, noop.func_code.co_stacksize, code.co_flags, noop.func_code.co_code, # don't do anything code.co_consts, code.co_names, code.co_varnames, code.co_filename, "can_call_" + code.co_name, code.co_firstlineno, noop.func_code.co_lnotab, # for line number info code.co_freevars, # Do I need to set cellvars? Don't think so. ) # function(code, globals[, name[, argdefs[, closure]]]) new_func = new.function(new_code, func.func_globals, "can_call_" + func.func_name, func.func_defaults) # Uses a static scope def can_call_func(*args, **kwargs): try: new_func(*args, **kwargs) except TypeError, err: return False return True try: can_call_func.__name__ = "can_call_" + func.__name__ except TypeError: # Can't change the name in Python 2.3 or earlier pass return can_call_func #### test def spam(x, y, z=4): raise AssertionError("Don't call me!") can_spam = can_call(spam) for (args, kwargs) in ( ((1,2), {}), ((1,), {}), ((1,), {"x": 2}), ((), {"x": 1, "y": 2}), ((), {"x": 1, "z": 2}), ((1,2,3), {}), ((1,2,3), {"x": 3}), ): can_spam_result = can_spam(*args, **kwargs) try: spam(*args, **kwargs) except AssertionError: could_spam = True except TypeError: could_spam = False if can_spam_result == could_spam: continue print "Failure:", repr(args), repr(kwargs) print "Could I call spam()?", could_spam print "Did I think I could?", can_spam_result print print "Done." > Still a good question though. Why is it TypeError? My guess - in most languages with types, functions are typed not only on "is callable" but on the parameter signature. For example, in C dalke% awk '{printf("%3d %s\n", NR, $0)}' tmp.c 1 2 int f(int x, int y) { 3 } 4 5 int g(int x) { 6 } 7 8 main() { 9 int (*func_ptr)(int, int); 10 func_ptr = f; 11 func_ptr = g; 12 } % cc tmp.c tmp.c: In function `main': tmp.c:11: warning: assignment from incompatible pointer type % 'Course the next question might be "then how about an ArgumentError which is a subclasss of TypeError?" Andrew dalke at dalkescientific.com From gaz082 at gmail.com Mon Jun 27 18:38:59 2005 From: gaz082 at gmail.com (Inkiniteo) Date: 27 Jun 2005 15:38:59 -0700 Subject: Plain text email? Message-ID: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Hi guys. I have a script that sends the info by email, but i'd like to avoid the convertion to HTML by the email client or Gmail, because it ruins all the formatting i did (with tabs, mostly). Briefing, i wanna be able to send SMTP mail and the receiver only get it in plain text. From bronger at physik.rwth-aachen.de Fri Jun 17 03:17:17 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 17 Jun 2005 09:17:17 +0200 Subject: Unbound names in __del__ References: Message-ID: Hall?chen! "Terry Reedy" writes: > "Torsten Bronger" wrote: > >> Is there a way to detect whether the program is being terminated? > > See atexit module to register cleanup functions that run *before* > the interpreter starts haphazardly deleting stuff. So I could register a function that sets a global variable called "shutdown_has_begun" to "True". Then I say def __del__(self): if shutdown_has_begun: return ... Alternatively, I could enclose every __del__ contents block with a "try" whithout catching anything, just to suppress the error messages. However, all of this is not pretty pythonic in my opinion. Is it that exotic to want to call functions from within __del__? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From mrmaple at gmail.com Thu Jun 9 08:56:28 2005 From: mrmaple at gmail.com (James Carroll) Date: Thu, 9 Jun 2005 08:56:28 -0400 Subject: help In-Reply-To: <1d7.3db374ed.2fd07bad@aol.com> References: <1d7.3db374ed.2fd07bad@aol.com> Message-ID: > When i try to open IDLE(python GUI) it says that i have a socket error: > conection refused what do i do to fix this if you're on linux, try making sure that localhost (the lo interface) is up and running if you do an ifconfig you should see one paragraph for the lo interface, and if you do an ifup lo or ifconfig lo up it should restart it. -Jim From bkhl at stp.ling.uu.se Sun Jun 19 07:45:46 2005 From: bkhl at stp.ling.uu.se (=?utf-8?q?Bj=C3=B6rn_Lindstr=C3=B6m?=) Date: Sun, 19 Jun 2005 13:45:46 +0200 Subject: oddness in super() References: <42B4B22F.1090204@lexicon.net> <42b558b1$0$1153$5402220f@news.sunrise.ch> Message-ID: <87psuish79.fsf@lucien.dreaming> "Martin Blume" writes: > A great analysis, but what's a "pogo stick" and where can I get one? http://search.ebay.com/pogo-stick -- Bj?rn Lindstr?m Student of computational linguistics, Uppsala University, Sweden From ali.jan at gmail.com Thu Jun 23 02:49:21 2005 From: ali.jan at gmail.com (Ali) Date: 22 Jun 2005 23:49:21 -0700 Subject: Allowing only one instance of a script? Message-ID: <1119509361.208748.247400@g49g2000cwa.googlegroups.com> Hi, I have a script which I double-click to run. If i double-click it again, it will launch another instance of the script. Is there a way to allow only one instance of a script, so that if another instance of the script is launched, it will just return with an error. Thanks Regards, Ali From jzgoda at gazeta.usun.pl Thu Jun 23 15:38:15 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 23 Jun 2005 21:38:15 +0200 Subject: formatted xml output from ElementTree inconsistency In-Reply-To: References: Message-ID: Matthew Thorley napisa?(a): > The output I get shows xmla as nicely formatted text, with elements on > different lines and everything all tabbed and pretty. Inverly, xmlb is > one long string on one line. > > Is that because the some_file.xml is already nicely formatted? I thought > that the formatting was ignored when creating new elements. Why want you to read an XML document "by hand"? It's a "machine related" data chunk. Document formatting should be done by means of CSS and/or XSL stylesheet. -- Jarek Zgoda http://jpa.berlios.de/ From peter at engcorp.com Tue Jun 21 08:12:27 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Jun 2005 08:12:27 -0400 Subject: FAQ: __str__ vs __repr__ In-Reply-To: References: <42b021ba$1@griseus.its.uu.se> Message-ID: Simon Brunning wrote: > On 6/15/05, Peter Hansen wrote: >>__repr__ shouldn't be anything, if you don't have an actual need for it. >> Neither should __str__. > > Oh, I don't know. __str__ is so frequently useful in debugging and > logging that I always try and do something useful with it. Interesting: for the same purpose, I would define __repr__. But I still define it only when I actually care about the details, since otherwise the default __repr__ is always there. Spending time figuring out a potentially more useful __str__/__repr__ (how nice that we've confused the issue of which to use, again! ;-) ) is not my idea of a good use of time, what with YAGNI and all from XP... -Peter From philippe at philippecmartin.com Mon Jun 20 11:18:58 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 15:18:58 GMT Subject: Python choice of database Message-ID: Hi, I am looking for a stand-alone (not client/server) database solution for Python. 1) speed is not an issue 2) I wish to store less than 5000 records 3) each record should not be larger than 16K As I start with Python objects, I thought of using shelve, but looking at the restrictions (record size + potential collisions) I feel I should study my options a bit further before I get started. Regards, Philippe From mkb at incubus.de Fri Jun 3 19:53:28 2005 From: mkb at incubus.de (Matthias Buelow) Date: Sat, 04 Jun 2005 01:53:28 +0200 Subject: What are OOP's Jargons and Complexities? In-Reply-To: <1117830051.520099.129930@g44g2000cwa.googlegroups.com> References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <1117003340.900449.124180@o13g2000cwo.googlegroups.com> <1117264336.229771.245070@g49g2000cwa.googlegroups.com> <1117532688.513061.162750@f14g2000cwb.googlegroups.com> <1117830051.520099.129930@g44g2000cwa.googlegroups.com> Message-ID: <3gc8neFblp70U1@news.dfncis.de> Xah Lee wrote: > to be continued tomorrow. Please don't... mkb. From b at b.b Sun Jun 5 20:40:11 2005 From: b at b.b (Roose) Date: Mon, 06 Jun 2005 00:40:11 GMT Subject: random module question Message-ID: Can I rely on the random.py module to produce the same series of numbers for future/past versions of Python, given the same seed? Can I rely on it across different architectures and operating systems? I looked at the docs and couldn't find this stated anywhere. My feeling is yes, but it's a fairly big claim so I want to make sure. R From philippe at philippecmartin.com Thu Jun 9 08:43:19 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 09 Jun 2005 12:43:19 GMT Subject: Generating HTML from python Message-ID: Hi, I wish to use an easy way to generate reports from wxPython and feel wxHtmlEasyPrinting could be a good solution. I now need to generate the HTML wxHtmlEasyPrinting can print: I need to have a title followed by lines of text that do not look too ugly. If possible I would like to use an existing module. Q1) Is there such a module ? Q2) Is my approach fairly good ? Regards, Philippe From peter at engcorp.com Fri Jun 10 13:10:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Jun 2005 13:10:38 -0400 Subject: unittest and XML output In-Reply-To: References: Message-ID: <5PedndlpY71OVzTfRVn-3A@powergate.ca> James Jeffers wrote: > I couldn't find any resource that addresses output from the unittest package > in python 2.4.x. I can't beleive that there isn't an output formatter/test > runner for the unittest package.. surely some needed this before. > > Is there a working group or package maintainer for these kinds of features? It's unclear whether or not you are actually aware of this, from the docs: """A test runner is an object that provides a single method, run(), which accepts a TestCase or TestSuite object as a parameter, and returns a result object. The class TestResult is provided for use as the result object. PyUnit provide the TextTestRunner as an example test runner which reports test results on the standard error stream by default. Alternate runners can be implemented for other environments (such as graphical environments) without any need to derive from a specific class.""" Does that help? Clearly there *is* a test runner for the unit test package, and clearly one can create one's own that does something different (as numerous people already have). -Peter From philippe at philippecmartin.com Sat Jun 25 15:59:25 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sat, 25 Jun 2005 19:59:25 GMT Subject: Big problem fetching members from dynamically loaded module References: Message-ID: OK Peter, first of all thanks. You seem to be German and although I leave in the states, I'm French and your english is clearly far more advanced than mine: I have yet to understand a few of your comments ;-) > Care to provide the traceback? Traceback (most recent call last): File "SC_Shell.py", line 1095, in ? l_d = SC_Shell() File "SC_Shell.py", line 326, in __init__ self.__Make_Menu_Area() File "SC_Shell.py", line 828, in __Make_Menu_Area l = inspect.getmembers(eval(c)) File "", line 0, in ? NameError: name 'BC' is not defined > What happened in lines 1 through 22? My guess would be just import inspect and after that .... QUID ? Thanks and regards, Philippe Peter Otten wrote: > Philippe C. Martin wrote: > >> l?=?inspect.getmembers(eval('BC'))?#THIS?CRASHES?-?the?class?exists > > Care to provide the traceback? > >> In [23]:from SC.CARDS.BC import * >> >> In [24]:l = inspect.getmembers(eval('BC')) > > What happened in lines 1 through 22? My guess would be > > In [13]:from SC.CARDS import * > > Be that as is may, eval("BC") can be simplified to BC, > > from module import * > > is the last roadhouse en route to chaos and an unqualified > > try ... except > > shows you are willing to drive with defunct brakes. By introducing exec > and eval() you are throwing the steering wheel out of the window. > > Seriously, try to make do with __import__() and getattr() to clean up your > code a bit. > > Driving-analogies-well-beyond-the-abyss-ly yours > Peter From b at b.b Sun Jun 5 20:53:31 2005 From: b at b.b (Roose) Date: Mon, 06 Jun 2005 00:53:31 GMT Subject: Destructive Windows Script References: Message-ID: My guess would be: extremely, extremely easy. Since you're only writing 30 bytes for each file, the vast majority of the data will still be present on disk, just temporarily inaccessible because of the del command. And more than likely it will be possible to recover 100% if they are using a journaling file system like NTFS, which Windows XP does. If you are honestly trying to destroy your own data, go out and download a free program that will do it right. If you're trying to write some kind of trojan, well you've got a lot of learning to do. :) R rbt wrote: > How easy or difficult would it be for a computer forensics expert to > recover data that is overwritten in this manner? This is a bit > off-topic for comp.lang.python, but I thought some here would have > some insight into this. > > Warning: **This code is destructive**. Do not run it unless you fully > understand what you're doing!!! > > os.chdir('/temp') > for root, dirs, files in os.walk('.'): > for f in files: > try: > print f > > data = ['0', 'a', '1', 'b', '2', 'c',\ > '3', 'd', '4', 'e', '5', 'f',\ > '6', 'g', '7', 'h', '8', 'i',\ > '9', 'j', '~', '!', '@', '#',\ > '$', '%', '^', '&', '*', ';'] > > fp = file(os.path.join(root,f), 'w') > random.shuffle(data) > garble = ''.join(data) > fp.write(garble) > fp.close() > > fs = os.popen("del /f /q /s *") > fs.read() > fs.close() > > except Exception, e: > print e > time.sleep(1) > continue From wesleyhenwood at hotmail.com Thu Jun 30 16:01:01 2005 From: wesleyhenwood at hotmail.com (Wesley Henwood) Date: 30 Jun 2005 13:01:01 -0700 Subject: python commmand line params from c++ In-Reply-To: References: <1120143124.925422.290980@g44g2000cwa.googlegroups.com> Message-ID: <1120159198.673751.251580@g43g2000cwa.googlegroups.com> Thanks Denis. PySys_SetArgv should do the trick. The nested function calls are there because the FILE structrure produced by fopen is not always compatible with the FILE structure produced by the Python C++ functions. Something do with the Python C being built with different version ofthe c run-time libs. The FILE problem is a bit strange and should be adressed, it's documented somewhere on the Python site, but no solution is given. That I had to find by trial and error. Even better would be a function such as PyRun_File(char *filename), and do away with handling the FILE structure altogether. From ptmcg at austin.rr.com Tue Jun 21 12:17:17 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 Jun 2005 09:17:17 -0700 Subject: use a regex or not? In-Reply-To: <1119363495.274573.131630@g14g2000cwa.googlegroups.com> References: <1119363495.274573.131630@g14g2000cwa.googlegroups.com> Message-ID: <1119370637.678188.289650@g49g2000cwa.googlegroups.com> Here's a hybrid solution, using pyparsing to parse your input pattern string (p), and transforming it into a regexp string. Then uses re.match using the regexp to process string (s), and then builds a dictionary from the matched groups. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul =================== import re from pyparsing import Word,OneOrMore previousKeys = [] def createUpperKey(s,l,t): if t[0] not in previousKeys: ret = "(?P<%s>.*)" % t[0] previousKeys.append(t[0]) else: ret = "(?P=%s)" % t[0] return ret lowers = "abcdefghijklmnopqrstuvwxyz" uppers = lowers.upper() lowerLetter = Word(lowers,max=1) upperLetter = Word(uppers,max=1).setParseAction(createUpperKey) pattern = OneOrMore( lowerLetter | upperLetter ) def fill(s,p): # reset keys found in p-patterns del previousKeys[:] # create regexp by running pyparsing transform regexp = pattern.transformString(p) + "$" # create dict from re-matched groups match = re.match(regexp,s) if match: ret = dict( [ (k,match.group(k)) for k in previousKeys ] ) else: ret = dict() return ret tests = [ ('ab','aA'), ('ab','Ab'), ('bb','Aa'), ('aa','Aa'), ('aa','Ab'), ('abb','aA'), ('aba','aAa'), ('abbba','aAa'), ('abbbaba','aAa'), ('abb','aAa'), ('abab','aAaA'), ('abac','aAaA'), ('abac','aAaB'), ] for t in tests: print t,fill( *t ) ================ Gives: ('ab', 'aA') {'A': 'b'} ('ab', 'Ab') {'A': 'a'} ('bb', 'Aa') {} ('aa', 'Aa') {'A': 'a'} ('aa', 'Ab') {} ('abb', 'aA') {'A': 'bb'} ('aba', 'aAa') {'A': 'b'} ('abbba', 'aAa') {'A': 'bbb'} ('abbbaba', 'aAa') {'A': 'bbbab'} ('abb', 'aAa') {} ('abab', 'aAaA') {'A': 'b'} ('abac', 'aAaA') {} ('abac', 'aAaB') {'A': 'b', 'B': 'c'} From utabintarbo at gmail.com Fri Jun 17 13:31:37 2005 From: utabintarbo at gmail.com (utabintarbo at gmail.com) Date: 17 Jun 2005 10:31:37 -0700 Subject: Help implementing an idea In-Reply-To: References: Message-ID: <1119029497.705154.318510@o13g2000cwo.googlegroups.com> Take a look at: http://dirssync.sourceforge.net/ See if that gives you any direction. From eurleif at ecritters.biz Wed Jun 1 09:40:57 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 01 Jun 2005 13:40:57 GMT Subject: working with pointers In-Reply-To: References: Message-ID: Duncan Booth wrote: > The constant integers are created in advance, not when you do the > assignment. But that's just an optimization, not Python's defined behavior. It seems more useful to me to think of all integers as being created at assignment time, even if CPython doesn't actually do that. From dalke at dalkescientific.com Sun Jun 12 01:54:10 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 12 Jun 2005 05:54:10 GMT Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> <7xekb84rsa.fsf@ruckus.brouhaha.com> <7x7jh0l5kg.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin replied to me: > If you're running a web site with 100k users (about 1/3 of the size of > Slashdot) that begins to be the range where I'd say LAMP starts > running out of gas. Let me elaborate a bit. That claim of 100K from me is the entire population of people who would use bioinformatics or chemical informatics. It's the extreme upper bound of the capacity I ever expect. It's much more likely I'll only need to handle a few thousand users. > I believe > LiveJournal (which has something more like a million users) uses > methods like that, as does ezboard. There was a thread about it here > a year or so ago. I know little about it, though I read at http://goathack.livejournal.org/docs.html ] LiveJournal source is lots of Perl mixed up with lots of MySQL I found more details at http://jeremy.zawodny.com/blog/archives/001866.html It's a bunch of things - Perl, C, MySQL-InnoDB, MyISAM, Akamai, memcached. The linked slides say "lots of MySQL usage." 60 servers. I don't see that example as validating your statement that LAMP doesn't scale for mega-numbers of hits any better than whatever you might call "printing press" systems. > As a simple example, that article's advice of putting all fine grained > session state into the database (so that every single browser hit sets > off SQL queries) is crazy. To be fair, it does say "database plus cache" though the author suggests the place for the cache is at the HTTP level and not at the DB level. I would have considered something like memcached perhaps backed by an asychronous write to a db if you want the user state saved even after the cache is cleared/reset. How permanent though does the history need to be? Your approach wipes history when the user clears the cookie and it might not be obvious that doing so should clear the history. In any case, the implementation cost for this is likely higher than what you did. I mention it to suggest an alternative. > As for "big", hmm, I'd say as production web sites go, 100k users is > medium sized, Slashdot is "largish", Ebay is "big", Google is huge. I'ld say that few sites have >100k users, much less daily users with personalized information. As a totally made-up number, only few dozens of sites (maybe a couple hundred?) would need to worry about those issues. If that's indeed the case then I'll also argue that each of them is going to have app-specific choke points which are best hand-optimized and not framework optimized. Is there enough real-world experience to design a EnterpriseWeb-o-Rama (your "printing press") which can handle those examples you gave any better than starting off with a LAMP system and hand-caching the parts that need it? Andrew dalke at dalkescientific.com From peter at engcorp.com Mon Jun 20 11:35:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Jun 2005 11:35:46 -0400 Subject: Python choice of database In-Reply-To: References: Message-ID: <0NGdnc53GtLifyvfRVn-uw@powergate.ca> John Abel wrote: > Gadfly > PySQLite ( requires SQLite library ) I want to clarify this parenthetical comment, for the record. When I first downloaded PySQLite I had already gone and installed SQLite, thinking it was a prerequisite in that sense. In fact, the PySQLite install includes a .pyd which contains a statically linked version of the complete SQLite library. No additional installation is required, making it an even simpler solution than I thought at first. -Peter From kasimov at i.com.ua Tue Jun 7 15:13:52 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Tue, 07 Jun 2005 22:13:52 +0300 Subject: different time tuple format In-Reply-To: References: Message-ID: Rick Holbert wrote: > Like the last poster said, use %Z. On my Mandriva Linux system I get the > following results: > > >>>>time.localtime() > > (2005, 6, 7, 15, 7, 12, 1, 158, 1) > >>>>time.strptime("2005-06-07 15:07:12 EDT", "%Y-%m-%d %H:%M:%S %Z") > (2005, 6, 7, 15, 7, 12, 1, 158, 1) does not work at all: "ValueError: format mismatch" i've check the value of time.tzname: ('EET', 'EEST') and get the following (again): >>> time.strptime("2005-06-07 15:07:12 EET", "%Y-%m-%d %H:%M:%S %Z") (2005, 6, 7, 15, 7, 12, 6, 1, 0) -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From jarrod.roberson at gmail.com Wed Jun 29 01:42:36 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 28 Jun 2005 22:42:36 -0700 Subject: Boss wants me to program In-Reply-To: <1119988656.668457.202660@g43g2000cwa.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119988656.668457.202660@g43g2000cwa.googlegroups.com> Message-ID: <1120023756.137822.304780@g14g2000cwa.googlegroups.com> you need to find another place to work From nephish at xit.net Sat Jun 11 10:00:39 2005 From: nephish at xit.net (nephish at xit.net) Date: 11 Jun 2005 07:00:39 -0700 Subject: cgi script runs under Opera, but not firefox Message-ID: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> Hey there, i have a python cgi script that prints out html just fine in the Opera browser but doesnt print at all under FireFox. weird, eh? i am getting nothing in the apache logs about any error. perhaps its a firefox issue, but i doubt it. any suggestions. simple script here.. From steve at REMOVETHIScyber.com.au Thu Jun 2 12:48:48 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 03 Jun 2005 02:48:48 +1000 Subject: Two questions References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: On Thu, 02 Jun 2005 06:45:18 -0700, qscomputing wrote: > Hi, > > I've developed in several other languages and have recently found > Python and I'm trying to use it in the shape of the PythonCard > application development tool. > > My two questions: > > 1. What is the easiest way to create a for loop in the style I'm used > to from Delphi ie: > for I:=0 to 2 do begin > //code > end; Use Delphi. If you insist on using Python (and why wouldn't you?), then I'm afraid you will have to create for loops in the Python style: for i in range(3): do_something Notice the small gotcha: if you want to loop over the values 0, 1, and 2, you have to use range(3), NOT range(2). This may seem strange now, but it is actually very useful and prevents a lot of off-by-one errors. > 2. Philospohy(sp?) aside, Philosophy. > I could potentially want to create a > binary-only distribution of my finished apps. I noticed the > documentation on .pyc files: how do I create these In PythonCard? I have no idea. Sorry. In ordinary Python? When you run or import a Python module, the Python interpreter first looks for a .pyc file of the same name that is more recent than the .py file. If it doesn't find one, it compiles the .py file into byte-code, stores the byte-code in the .pyc file, and runs that. In other words, to create your .pyc file, just run your .py file and Python will do it automatically. > and, aside from > being basically read-only, are they used just like ordinary .py source > files? And can they be easily reverse-engineered? Yes, they can be easily reverse-engineered. The short answer is, Python has not been designed to hide your code. If that's what you are trying to do, perhaps you need to think about _why_ you want to go to all that extra effort to keep your software secret, rather than just _how_ to keep it secret. I can think of a number of reasons why somebody might want to hide their code. In no particular order: (1) You are ashamed of the quality of your buggy code, and don't want people to see how bad it is. If so, learn to write better code, and the best way of doing that is to let people see your code and give you advice. (2) You have stolen somebody else's code, and are trying to keep that fact secret. If so, pay the licence fee, or legally reverse-engineer the code, or use OpenSource software that allows copying. If the code you have stolen is valuable enough, the legal owners will find out, even without the source code. (3) You have create an incredibly valuable piece of code that will be worth millions, but only if nobody can see the source code. Yeah right. (4) "It's MY CODE, nobody is allowed to use it unless I SAY SO!!!" Fine, whatever you say, there are tens or hundreds of thousands of OpenSource software packages competing with your software without those restrictions. Good luck. (5) Your code has security holes and you hope that the bad guys won't find them without access to the source code. Be prepared for serious embarrassment, because the crackers WILL crack your code, source code or no source code. Obscurity is no substitute for security. (6) You are worried about people copying the code for their friends without paying you for it. How does keeping the source code secret stop them from copying the .pyc files and giving them to their friends? (7) You are using secret programs licenced from another programmer or company, and the conditions of use are that the source code isn't made available. Good luck, I hope it works out for you. (8) You are programming a game or puzzle, and you don't want players to cheat by reading the source code. Consider pulling out the information they need to cheat and putting it in an encrypted data file instead. There may be other reasons for wanting to keep the code secret. Some of them might even be good reasons, for some value of "good". The reality is, the more valuable your code is, the more effort people will put into reverse-engineering it. People will find out how it works, if they care enough, and the more valuable your program, the more they will care. On the other hand, there are incredible advantages to making your code available to the users of your software. I'm sure you already know those advantages: you are learning Python, which is based on those principles of openness. If you want to discuss these issues further, please feel free. If you really what to hide your code, you might like to think about using C-extensions instead. -- Steven From steven.bethard at gmail.com Sat Jun 4 11:43:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 09:43:48 -0600 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Ilpo Nyyss?nen wrote: > How about this instead: > > with locking(mutex), opening(readfile) as input: > ... > I don't like the ambiguity this proposal introduces. What is input bound to? The return value of locking(mutex).__enter__() or the return value of opening(readfile).__enter__()? Seems ambiguous to me. And is the file opened with the mutex held, or not? Sure, all of these questions can be answered with an arbitrary decision. But the point is that, whatever decision you make, I now have to *memorize* that decision. Note that if I wrote: with locking(mutex): with opening(readfile) as input: ... it's clear that input is the return value of opening(readfile).__enter__(), and that the mutex is held while the file is opened. I don't need to memorize these things; they are explicit in the syntax. I can see making the with-statement proposal more complex if you had some very good motivating examples for wanting the multiple-expressions extension. But you have yet to provide a real-world use case. Go search your codebase, and find some examples of where you would actually use this. For the complexity that you want to add to the with-statement, you need to show that there's a *large* advantage to a *variety* of use cases in *real-world* code. STeVe From peter at engcorp.com Sun Jun 12 17:19:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 12 Jun 2005 17:19:06 -0400 Subject: case/switch statement? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote: >>If the case values are constants known to the compiler, it can generate O(1) >>code to take the correct branch. >>It is precisely this behavior that is desired in many situations. > > Agreed. I certainly don't object to sensible optimizations! But the number > of if...elif statements which can be optimised are a vanishingly small > subset of the number of possible if...elif statements. > > And you can bet your last dollar that many people will use case statements > even when doing so gives no advantage, in a mistaken opinion that it will > be somehow magically faster. Case statements are actually more suitable in many cases even when performance is not a goal for reasons of *readability*. When reading an if statement, you have to scan down through effective each statement attempting to find the case in which you are interested. Some cases can be compound. The nested ifs can get confused with the surrounding ones (in Python or a language with explicit block delimiters). The cases are often not written in any particular order, or they are ordered *for* performance reasons, but in ways that make it harder to "scan". A case statement, on the other hand, can be a message from the programmer, saying in effect "here's code that represents a series of _simple_ conditionals, ordered (usually) in a sensible way (e.g. ascending numerical order), so just jump to the case you want and carry on maintaining this nice code." In current Python the equivalent approach is, of course, a dictionary of some kind, though it's arguable whether this is as clean in many cases as a case statement would be. -Peter From usenet at zabiello.com Fri Jun 10 10:10:18 2005 From: usenet at zabiello.com (JZ) Date: Fri, 10 Jun 2005 16:10:18 +0200 Subject: Perl s/ To Python? References: Message-ID: <150e7uha8wt38$.wsnjzb0472n3$.dlg@40tude.net> Dnia Fri, 10 Jun 2005 14:57:21 +0100, John Abel napisa?(a): > $testVar =~ s#/mail/.*$##g > > The only way I can think of doing it, is: > > mailPos = testVar.find( "mail" ) > remainder = testVar[ :mailPos ] > > Any ideas would be appreciated. I'm iterating over a lot of entries, > and running these lines for each entry. import re testVar = re.compile(r'/mail/.*$').sub('', testVar) -- JZ From jmdeschamps at cvm.qc.ca Fri Jun 10 00:11:42 2005 From: jmdeschamps at cvm.qc.ca (jean-marc) Date: 9 Jun 2005 21:11:42 -0700 Subject: Python as CGI on IIS and Windows 2003 Server In-Reply-To: <1118338442.024062.24150@o13g2000cwo.googlegroups.com> References: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> <1118338442.024062.24150@o13g2000cwo.googlegroups.com> Message-ID: <1118376702.458747.309710@g14g2000cwa.googlegroups.com> Some bits are coming back to me: the problems stemmed from adresses - getting the root of IIS was different so accessing files didn't work the same way. I'm also quite positive that my desktop (developement version) was IIS 5.1 which comes with XP Pro compared to 6.0 for IIS Server. I changed the way I was dealing with file adresses. Maybe there is a hint of direction for your own investigation... Jean-Marc From gsakkis at rutgers.edu Mon Jun 20 12:01:30 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 20 Jun 2005 09:01:30 -0700 Subject: Couple functions I need, assuming they exist? References: <8cadnbiar_RkfyvfRVn-3A@comcast.com> Message-ID: <1119283290.501825.300210@g49g2000cwa.googlegroups.com> > I assume you mean translating something like '1000000' to '1,000,000'? > I don't know of an existing function that does this, but here's a > relatively simple implementation: > > py> import itertools as it > py> def add_commas(s): > ... rev_chars = it.chain(s[::-1], it.repeat('', 2)) > ... return ','.join(''.join(three_digits) > ... for three_digits > ... in it.izip(*[rev_chars]*3))[::-1] > ... Or for an equivalent less cryptic (IMHO) recipe: def num2str(num): '''Return a string representation of a number with the thousands being delimited. >>> num2str(65837) '65,837' >>> num2str(6582942) '6,582,942' >>> num2str(23) '23' >>> num2str(-1934) '-1,934' ''' parts = [] div = abs(num) while True: div,mod = divmod(div,1000) parts.append(mod) if not div: if num < 0: parts[-1] *= -1 return ','.join(str(part) for part in reversed(parts)) Regards, George From nidoizo at yahoo.com Sat Jun 25 15:44:14 2005 From: nidoizo at yahoo.com (Nicolas Fleury) Date: Sat, 25 Jun 2005 15:44:14 -0400 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > One of the things I liked in Pascal was the "with" keyword. You could > write something like this: > > with colour do begin > red := 0; blue := 255; green := 0; > end; > > instead of: > > colour.red := 0; colour.blue := 255; colour.green := 0; > > Okay, so maybe it is more of a feature than a trick, but I miss it and it > would be nice to have in Python. > With PEP343 (I guess in Python 2.5), you will be able to do something like: with renamed(colour) as c: c.red = 0; c.blue = 255; c.green = 0 I think however it is bad. Better solutions to me would be: colour.setRgb(0, 255, 0) or c = myVeryLongNameColour c.red = 0; c.blue = 255; c.green = 0 Regards, Nicolas From bj_666 at gmx.net Wed Jun 15 16:22:24 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 15 Jun 2005 22:22:24 +0200 Subject: Tiff Image Reader/writer References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> <1118697529.173406.134460@g44g2000cwa.googlegroups.com> Message-ID: In , Robert Kern wrote: > PyPK wrote: >> One reason why I don't want to use PIL is it seems very slow for tiff >> images of very large sizes(2400x4800). So I am looking for a better >> tool than does the right job faster. > > This isn't fast enough? > > In [8]: %time img2 = Image.open('foo.tiff') > CPU times: user 0.00 s, sys: 0.01 s, total: 0.01 s > Wall time: 0.03 > > In [9]: img2.size > Out[9]: (2400, 4800) It's fast enough to open the file and read the meta-data. The OP wants to decode the actual pixels. Ciao, Marc 'BlackJack' Rintsch From skip at pobox.com Tue Jun 21 09:44:52 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 21 Jun 2005 08:44:52 -0500 Subject: FAQ: __str__ vs __repr__ In-Reply-To: <8c7f10c6050621023518890fa4@mail.gmail.com> References: <42b021ba$1@griseus.its.uu.se> <8c7f10c6050621023518890fa4@mail.gmail.com> Message-ID: <17080.6612.831917.345749@montanaro.dyndns.org> >> __repr__ shouldn't be anything, if you don't have an actual need for >> it. Neither should __str__. Simon> Oh, I don't know. __str__ is so frequently useful in debugging Simon> and logging that I always try and do something useful with it. And sometimes __repr__ inherited from a base class doesn't tell you much. If you inherit from gobject (the basic object in PyGtk), the repr is something like That is, it identifies the class name, its inheritance hierarchy (Future -> Base -> __main__ in this case) and its memory address. That's perhaps useful by itself in some contexts, and I can understand that the PyGtk folks couldn't really stuff more specific info in there, but it does nothing to distinguish one instance's state from that of another. Skip From dalke at dalkescientific.com Sun Jun 12 17:52:48 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 12 Jun 2005 21:52:48 GMT Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> <7xekb84rsa.fsf@ruckus.brouhaha.com> <7x7jh0l5kg.fsf@ruckus.brouhaha.com> <7xwtp09jh3.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Andrew Dalke writes: ... >> I found more details at >> http://jeremy.zawodny.com/blog/archives/001866.html >> >> It's a bunch of things - Perl, C, MySQL-InnoDB, MyISAM, Akamai, >> memcached. The linked slides say "lots of MySQL usage." 60 servers. > > LM uses MySQL extensively but what I don't know is whether it serves > up individual pages by the obvious bunch of queries like a smaller BBS > might. I have the impression that it's more carefully tuned than that. The linked page links to a PDF describing the architecture. The careful tuning comes in part from a high-performance caching system - memcached. >> I don't see that example as validating your statement that >> LAMP doesn't scale for mega-numbers of hits any better than >> whatever you might call "printing press" systems. > > What example? Slashdot? Livejournal. You gave it as a counter example to the LAMP architecture used by /. ] It seems to me that by using implementation methods that ] map more directly onto the hardware, a site with Slashdot's ] traffic levels could run on a single modest PC (maybe a laptop). ] I believe LiveJournal (which has something more like a million ] users) uses methods like that, as does ezboard. Since LJ uses a (highly hand-tuned) LAMP architecture, it isn't an effective counterexample. > It uses way more hardware than it needs to, > at least ten servers and I think a lot more. If LJ is using 6x as > many servers and taking 20x (?) as much traffic as Slashdot, then LJ > is doing something more efficiently than Slashdot. I don't know where the 20x comes from. Registered users? I read /. but haven't logged into it in 5+ years. I know I hit a lot /. more often than I do LJ (there's only one diary I follow there). The use is different as well; all people hit one story / comments page, and the comments are ranked based on reader-defined evaluations. LJ has no one journal that gets anywhere as many hits and there is no ranking scheme. >> I'ld say that few sites have >100k users, much less >> daily users with personalized information. As a totally made-up >> number, only few dozens of sites (maybe a couple hundred?) would >> need to worry about those issues. > > Yes, but for those of us interested in how big sites are put together, > those are the types of sites we have to think about ;-). My apologies since I know this sounds snide, but then why didn't you (re)read the LJ architecture overview I linked to above? That sounds like something you would have been interested in reading and would have directly provided information that counters what you said in your followup. The "ibm-poop-heads" article by Ryan Tomayko gives pointers to several other large-scale LAMP-based web sites. You didn't like the Google one. I checked a couple of the others: IMDB - http://www.findarticles.com/p/articles/mi_zdpcm/is_200408/ai_ziff130634 As you might expect, the site is now co-located with other Amazon.com sites, served up from machines running Linux and Apache, but ironically, most of the IMDb does not use a traditional database back end. Its message boards are built on PostgreSQL, and certain parts of IMDb Pro-including its advanced search-use MySQL, but most of the site is built with good old Perl script. del.icio.us Took some digging but I found http://lists.del.icio.us/pipermail/discuss/2004-November/001421.html "The database gets corrupted because the machine gets power-cycled, not through any fault of MySQL's." The point is that LAMP systems do scale, both down and up. It's a polemic against "architecture astronauts" who believe the only way to handle large sites (and /., LJ, IMDB, and del.icio.us are larger than all but a few sites) is with some spiffy "enterprise" architecture framework. > I'd say > there's more than a few hundred of them, but it's not like there's > millions. And some of them really can't afford to waste so much > hardware--look at the constant Wikipedia fundraising pitches for more > server iron because the Wikimedia software (PHP/MySQL, natch) can't > handle the load. Could that have, for example, bought EnterpriseWeb-O-Rama and done any better/cheaper? Could they have even started the project had they gone that route? > Yes, of course there is [exprience in large-scale web apps]. > Look at the mainframe transaction systems of the 60's-70's-80's, for > example. Look at Google. For the mainframe apps you'll have to toss anything processed in batch mode, like payrolls. What had the customization level and scale comparable to 100K+ sites of today? ATMs? Stock trading? Google is a one-off system. At present there's no other system I know of - especially one with that many users - where a single user request can trigger searches from hundreds of machines. That's all custom software. Or should most servers implement what is in essence a new distributed operating system just to run a web site? > Then there's the tons of experience we all have with LAMP systems. By > putting some effort into seeing where the resources in those things go, > I believe we can do a much better job. In particular, those sites like > Slashdot are really not update intensive in the normal database sense. > They can be handled almost entirely with some serial log files plus some > ram caching. At that point almost all the SQL overhead and a lot of the > context switching can go away. Is /. an appropriate comparable? I get the idea that it hasn't changed much in the last, say, 5 years and the user base hasn't grown much either. What you propose requires programming effort. If the system doesn't need work, if money in > money out (even with expensive hardware), and if the extra work doesn't get much benefit, then is it worthwhile to them to rearchitect the system? Perhaps in a couple years it'll run on two machines (one as the backup), with no change to the code, and simply because the hardware is good enough and cheap enough. Andrew dalke at dalkescientific.com From peter at engcorp.com Mon Jun 20 11:33:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Jun 2005 11:33:30 -0400 Subject: Python choice of database In-Reply-To: References: Message-ID: <0NGdnc93GtJrfCvfRVn-uw@powergate.ca> Philippe C. Martin wrote: > I am looking for a stand-alone (not client/server) database solution for > Python. > > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K > > As I start with Python objects, I thought of using shelve, but looking at > the restrictions (record size + potential collisions) I feel I should study > my options a bit further before I get started. You don't say whether you want *pure* Python solutions, so I'll suggest pysqlite which wraps the SQLite embedded database in a pretty much totally transparent fashion and is highly effective, fast, compact, reliable (so far, in my experience), and clean. You also don't say whether you want a SQL database, so if you are free to try anything, you might look at ZODB or Durus (think of it as a lighter-weight ZODB). I believe Durus is pure Python, but it might have some C code for performance (like ZODB). It's not SQL, and should perhaps be thought of (as it describes itself) as an object persistence solution, rather than a "database". -Peter From news at NOwillmcguganSPAM.com Sun Jun 5 12:42:28 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Sun, 05 Jun 2005 17:42:28 +0100 Subject: maybe a bug in python In-Reply-To: References: Message-ID: <42a32b75$0$16470$db0fefd9@news.zen.co.uk> flyaflya wrote: > > >>> a = {1: ("a")} > >>> a[1] > 'a' > why not ('a')? when > >>> a = {1: ((("a")))} > >>> a[1] > 'a' > the result is 'a' too,not ((("a"))).but when use["a"] or ("a","b"),the > tuple is longer than 1, it's no problem. > > ("a") is just a simple expression. You need to add a comma so that Python knows you want a tuple. Thusly... ("a",) Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From kveretennicov at gmail.com Mon Jun 20 18:13:53 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 00:13:53 +0200 Subject: Python and encodings drives me crazy In-Reply-To: <6f7b52d05062014292f25e8a9@mail.gmail.com> References: <6f7b52d05062013545cbc435d@mail.gmail.com> <6f7b52d05062014292f25e8a9@mail.gmail.com> Message-ID: <4660fe3005062015135c516cbc@mail.gmail.com> On 6/20/05, Oliver Andrich wrote: > Does the following code write headline and caption in > MacRoman encoding to the disk? > > f = codecs.open(outfilename, "w", "macroman") > f.write(headline) It does, as long as headline and caption *can* actually be encoded as macroman. After you decode headline from utf-8 it will be unicode and not all unicode characters can be mapped to macroman: >>> u'\u0160'.encode('utf8') '\xc5\xa0' >>> u'\u0160'.encode('latin2') '\xa9' >>> u'\u0160'.encode('macroman') Traceback (most recent call last): File "", line 1, in ? File "D:\python\2.4\lib\encodings\mac_roman.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u0160' in position 0: character maps to - kv From JOHNWUN at aol.com Tue Jun 7 15:58:17 2005 From: JOHNWUN at aol.com (Grooooops) Date: 7 Jun 2005 12:58:17 -0700 Subject: split up a list by condition? In-Reply-To: <3gma9rFd6jmpU1@individual.net> References: <3gjpk0FcrnknU1@individual.net> <1118125802.096110.167820@g49g2000cwa.googlegroups.com> <3gma9rFd6jmpU1@individual.net> Message-ID: <1118174296.967243.235100@z14g2000cwz.googlegroups.com> > vees, cons = [], [] > [(vees, cons)[ch in vocals].append(ch) for ch in wlist] Wow, that's horribly twisted Reinhold... I spent about an hour last night trying something similar, to no end... :) Neat tricks people... I like Duncan's use of "or" to solve it. I didn't see that in the python docs on list comprehension. Very cool. There is a special place in my heart for obfuscated Python, but of course, not in production code if there is a clearer solution available. From noreply at gcgroup.net Wed Jun 22 10:55:48 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 22 Jun 2005 14:55:48 GMT Subject: 'custom' events ? Message-ID: I am trying to create a Python UI in Tkinter and have several (frame) widgets that display various data fields. I am trying to create a 'changed' event that each widget can trigger when they have been edited. I see lots of references that suggest that 'custom' events can be created, but haven?t found any that give me a clue as to how. Also, can parent or sibling widgets capture the 'custom' event (similar to using )? Thanks, ill From tjreedy at udel.edu Fri Jun 24 15:54:41 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Jun 2005 15:54:41 -0400 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: "Tom Anderson" wrote in message news:Pine.LNX.4.62.0506241625460.14603 at urchin.earth.li... > sometimes in python. No, it's not really possible in a typeless language, > and yes, there are implementations based on decorators, but frankly, > they're awful. Python has strongly typed objects. Only names are typeless. Terry J. Reedy From barney.dalton at gmail.com Wed Jun 8 17:36:46 2005 From: barney.dalton at gmail.com (barney) Date: 8 Jun 2005 14:36:46 -0700 Subject: file permissions on windows XP (home) In-Reply-To: References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> <1118178009.923372.160210@g44g2000cwa.googlegroups.com> Message-ID: <1118266606.590200.118970@g44g2000cwa.googlegroups.com> Thanks, I will go the win32security.SetFileSecurity route. It seems a pity that I can't use platform independant code to sort this out but I guess you're saying that I've managed to get my files into a non standard state that needs non standard code to sort it out. I wonder how winamp/itunes manage to bypass it. Barney From ptmcg at austin.rr.com Mon Jun 27 10:52:49 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Jun 2005 07:52:49 -0700 Subject: Beginner question: Converting Single-Element tuples to list References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> Message-ID: <1119883969.197756.22140@f14g2000cwb.googlegroups.com> David - I'm not getting the same results. Run this test program: --------------- import pyparsing as pp import sys def test(s): results = pp.OneOrMore( pp.Word(pp.alphas) ).parseString( s ) print repr(s),"->",list(results) print "Python version:", sys.version print "pyparsing version:", pp.__version__ test("abc def") test("abc") --------------- The output I get is: Python version: 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] pyparsing version: 1.3.1 'abc def' -> ['abc', 'def'] 'abc' -> ['abc'] What versions of pyparsing and Python are you using? -- Paul From steven.bethard at gmail.com Sat Jun 25 18:34:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Jun 2005 16:34:10 -0600 Subject: python-dev Summary for 2005-05-01 through 2005-05-15 Message-ID: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-05-01_2005-05-15.html] ===================== Summary Announcements ===================== ---------------------------------------------- PEP 340 Episode 2: Revenge of the With (Block) ---------------------------------------------- This fornight's Python-Dev was dominated again by another nearly 400 messages on the topic of anonymous block statements. The discussion was a little more focused than the last thanks mainly to Guido's introduction of `PEP 340`_. Discussion of this PEP resulted in a series of other PEPs, including * `PEP 342`_: Enhanced Iterators, which broke out into a separate PEP the parts of `PEP 340`_ that allowed code to pass values into iterators using ``continue EXPR`` and yield-expressions. * `PEP 343`_: Anonymous Block Redux, a dramatically simplified version of `PEP 340`_, which removed the looping nature of the anonymous blocks and the injection-of-exceptions semantics for generators. * `PEP 3XX`_: User Defined ("with") Statements, which proposed non-looping anonymous blocks accompanied by finalization semantics for iterators and generators in for loops. Various details of each of these proposals are discussed below in the sections: 1. `Enhanced Iterators`_ 2. `Separate APIs for Iterators and Anonymous Blocks`_ 3. `Looping Anonymous Blocks`_ 4. `Loop Finalization`_ At the time of this writing, it looked like the discussion was coming very close to a final agreement; `PEP 343`_ and `PEP 3XX`_ both agreed upon the same semantics for the block-statement, the keyword had been narrowed down to either ``do`` or ``with``, and Guido had agreed to add back in to `PEP 343`_ some form of exception-injection semantics for generators. .. _PEP 340: http://www.python.org/peps/pep-0340.html .. _PEP 342: http://www.python.org/peps/pep-0342.html .. _PEP 343: http://www.python.org/peps/pep-0343.html .. _PEP 3XX: http://members.iinet.net.au/~ncoghlan/public/pep-3XX.html [SJB] ========= Summaries ========= ------------------ Enhanced Iterators ------------------ `PEP 340`_ incorporated a variety of orthogonal features into a single proposal. To make the PEP somewhat less monolithic, the method for passing values into an iterator was broken off into `PEP 342`_. This method includes: * updating the iterator protocol to use .__next__() instead of .next() * introducing a new builtin next() * allowing continue-statements to pass values into iterators * allowing generators to receive values with a yield-expression Though these features had seemed mostly uncontroversial, Guido seemed inclined to wait for a little more motivation from the co-routiney people before accepting the proposal. Contributing threads: - `Breaking off Enhanced Iterators PEP from PEP 340 `__ [SJB] ------------------------------------------------ Separate APIs for Iterators and Anonymous Blocks ------------------------------------------------ `PEP 340`_ had originally proposed to treat the anonymous block protocol as an extension of the iterator protocol. Several problems with this approach were raised, including: * for-loops could accidentally be used with objects requiring blocks, meaning that resources would not get cleaned up properly * blocks could be used instead of for-loops, violating TOOWTDI As a result, both `PEP 343`_ and `PEP 3XX`_ propose decorators for generator functions that will wrap the generator object appropriately to match the anonymous block protocol. Generator objects without the proposed decorators would not be usable in anonymous block statements. Contributing threads: - `PEP 340 -- loose ends `__ - `PEP 340 -- concept clarification `__ [SJB] ------------------------ Looping Anonymous Blocks ------------------------ A few issues arose as a result of `PEP 340`_'s formulation of anonymous blocks as a variation on a loop. Because the anonymous blocks of `PEP 340`_ were defined in terms of while-loops, there was some discussion as to whether they should have an ``else`` clause like Python ``for`` and ``while`` loops do. There didn't seem to be one obvious interpretation of an ``else`` block though, so Guido rejected the ``else`` block proposal. The big issue with looping anonymous blocks, however, was in the handling of ``break`` and ``continue`` statements. Many use cases for anonymous blocks did not require loops. However, because `PEP 340`_ anonymous blocks were implemented in terms of loops, ``break`` and ``continue`` acted much like they would in a loop. This meant that in code like:: for item in items: with lock: if handle(item): break the ``break`` statement would only break out of the anonymous block (the ``with`` statement) instead of breaking out of the for-loop. This pretty much shot-down `PEP 340`_; there were too many cases where an anonymous block didn't look like a loop, and having it behave like one would have been a major stumbling block in learning the construct. As a result, both `PEP 343`_ and `PEP 3XX`_ were proposed as non-looping versions of `PEP 340`_. Contributing threads: - `PEP 340: Else clause for block statements `__ - `PEP 340 -- loose ends `__ - `PEP 340 -- concept clarification `__ - `PEP 340: Breaking out. `__ - `PEP 340: Non-looping version (aka PEP 310 redux) `__ - `PEP 340 - Remaining issues `__ - `PEP 340: Deterministic Finalisation (new PEP draft, either a competitor or update to PEP 340) `__ - `Merging PEP 310 and PEP 340-redux? `__ - `PEP 343 - Abstract Block Redux `__ [SJB] ----------------- Loop Finalization ----------------- Greg Ewing pointed out that a generator with a yield inside a block-statement would require additional work to guarantee its finalization. For example, if the generator:: def all_lines(filenames): for name in filenames: with open(name) as f: for line in f: yield line were used in code like:: for line in all_lines(filenames): if some_cond(line): break then unless the for-loop performed some sort of finalization on the all_lines generator, the last-opened file could remain open indefinitiely. As a result, `PEP 3XX`_ proposes that for-loops check for a __finish__() method on their iterators, and if one exists, call that method when the for-loop completes. Generators like all_lines above, that put a yield inside a block-statement, would then acquire a __finish__() method that would raise a TerminateIteration exception at the point of the last yield. The TerminateIteration exception would thus cause the block-statement to complete, guaranteeing that the generator was properly finalized. Contributing threads: - `PEP 340 - For loop cleanup, and feature separation `__ - `PEP 340: Deterministic Finalisation (new PEP draft, either a competitor or update to PEP 340) `__ - `PEP 343 - Abstract Block Redux `__ [SJB] ---------------------------- Breaking out of Nested Loops ---------------------------- As a result of some of the issues of looping anonymous blocks, a few threads discussed options for breaking out of nested loops. These mainly worked by augmenting the ``break`` statement with another keyword (or keywords) that would indicate which loop to break out of. One proposal suggested that ``break`` be followed with ``for`` or ``while`` to indicate which loop to break out of. But ``break for`` would only really be useful in a while-loop nested within a for-loop, and ``break while`` would only really be useful in a for-loop nested within a while-loop. That is, because loops could only be named by type, the proposal was only useful when loops of different types were mixed. This suggestion was thus discarded as not being general enough. A few other suggestions were briefly discussed: adding labels to loops, using an integer to indicate which "stack level" to break at, and pushing breaks onto a "break buffer", but Guido killed the discussion, saying, `"Stop all discussion of breaking out of multiple loops. It ain't gonna happen before my retirement." `__ Contributing threads: - `PEP 340: Breaking out. `__ - `PEP 340: Deterministic Finalisation (new PEP draft, either a competitor or update to PEP 340) `__ [SJB] ------------------------ The future of exceptions ------------------------ Ka-Ping Yee suggested that instead of passing (type, value, traceback) tuples in exceptions it would be better to put the traceback in value.traceback. Guido had also suggested this (in the `PEP 340`_ murk) but pointed out that this would not work as long as string exceptions exist (as there is nowhere to put the traceback). Guido noted that there are no concrete plans as to when string exceptions will be deprecated and removed (other than in 3.0 at the latest); he indicated that it could be sooner, if someone wrote a PEP with a timeline (e.g. deprecated in 2.5, gone in 2.6). Brett C. volunteered to write a PEP targetted at Python 3000 covering exception changes (base inheritance, standard attributes (e.g. .traceback), reworking the built-in exception inheritance hierarchy, and the future of bare except statements). Contributing threads: - `Tidier Exceptions `__ .. _PEP 340: http://www.python.org/peps/pep-0340.html [TAM] ----------------------------------- Unifying try/except and try/finally ----------------------------------- Reinhold Birkenfeld submitted a Pre-PEP to allow both except and finally clauses in try blocks. For example, a construction like:: try: except Ex1: else: finally: would be exactly the same as the legacy:: try: try: except Ex1: else: finally: Guido liked this idea (so much that he wanted to accept it immediately), and recommended that it was checked in as a PEP. However, Tim Peters pointed out that this functionality was removed from Python (by Guido) way back in 0.9.6, seemingly because there was confusion about exactly when the finally clause would be called (explicit is better than implicit!). Guido clarified that control would only pass forward, and indicated that he felt that since this is now available in Java (and C#) fewer people would be confused. The main concern about this change was that, while the cost was low, it seemed to add very little value. Contributing threads: - `Pre-PEP: Unifying try-except and try-finally `__ [TAM] ----------------- Decorator Library ----------------- Michele Simionato asked whether a module for commonly used decorators, or utilities to create decorators, was planned. Raymond Hettinger indicated that while this was likely in the long term, he felt that it was better if these first evolved via wikis, recipes, or mailing lists, so that a module would only be added once best practices and proven winners had emerged. In the meantime, there is both a `Decorator Library wiki page`_ and you can try out `Michele's library`_ [zip]. To assist with decorator creation, Michele would like a facility to copy a function. Phillip J. Eby noted that the informally-discussed proposal is to add a mutable __signature__ to functions to assist with signature preserving decorators. Raymond suggested a patch adding a __copy__ method to functions or a patch for the copy module, and Michele indicated that he would also like to subclass FunctionType with an user-defined __copy__ method. Contributing threads: - `my first post: asking about a "decorator" module `__ - `The decorator module `__ .. _Decorator Library wiki page: http://www.python.org/moin/PythonDecoratorLibrary .. _Michele's library: http://www.phyast.pitt.edu/~micheles/python/decorator.zip [TAM] --------------------- Hooking Py_FatalError --------------------- Errors that invoke Py_FatalError generally signify that the internal state of Python is in such a poor state that continuing (including raising an exception) is impossible or unwise; as a result, Py_FatalError outputs the error to stderr and calls abort(). m.u.k. would like to have a callback to hook Py_FatalError to avoid this call to abort(). The general consensus was that effort would be better directed to fixing the causes of fatal errors than hooking Py_FatalError. m.u.k.'s use case was for generating additional logging information; a `callback system patch`_ (revised by James William Pye) is available for those interested. Contributing threads: - `Need to hook Py_FatalError `__ .. _callback system patch: http://python.org/sf/1195571 ------------------- Chaining Exceptions ------------------- Ka-Ping Yee suggested adding information to exceptions when they are raised in the handler for another exception. For example:: def a(): try: raise AError except: raise BError raises an exception which is an instance of BError. This instance could have an attribute which is instance of AError, containing information about the original exception. Use cases include catching a low-level exception (e.g. socket.error) and turning it into a high-level exception (e.g. an HTTPRequestFailed exception) and handling problems in exception handling code. Guido liked the idea, and discussion fleshed out a tighter definition; however it was unclear whether adding this now was feasible - this would perhaps be best added in Python 3000. Contributing threads: - `Chained Exceptions `__ [TAM] ------------------------ Py_UNICODE Documentation ------------------------ Nicholas Bastin started a series of threads discussing an inconsistency between the Py_UNICODE docs and the behavior on some RedHat systems. The docs say that Py_UNICODE should be an alias for wchar_t when wchar_t is available and has 16 bits, but Nick found that pyconfig.h still reports PY_UNICODE_TYPE as wchar_t, even when PY_UNICODE_SIZE is 4. An extensive discussion between Nick, Marc-Andre Lemburg and Martin v. L?wis suggests that the possible Python-internal representations for Py_UNICODE are: * 4-byte wchar_t encoded as UTF-32 (UCS-4) * 2-byte wchar_t encoded as UTF-16 * unsigned short encoded as UTF-16 Python defaults to 2-byte mode, using wchar_t if available (and has 16 bits) and using unsigned short otherwise. You may end up with the 4-byte mode if TCL was built for UCS-4 (this overrides the defaults) or if you explicitly request it with --enable-unicode=ucs4. To get UCS-2 when TCL was built for UCS-4, you must explicitly request --enable-unicode=ucs2. Of course, this will mean that _tkinter can't be built anymore. Also noted by this discussion was that even with --enable-unicode=ucs2, Python continues to support surrogate pairs in the BMP. So for example, even with a UCS-2 build, u"\U00012345" encodes as a sequence of two characters; it does not produce a UnicodeError. At the time of this posting, it did not appear that there was a documentation patch available yet. Contributing threads: - `Py_UNICODE madness `__ - `New Py_UNICODE doc `__ - `Python's Unicode width default (New Py_UNICODE doc) `__ [SJB] =============== Skipped Threads =============== - `Keyword for block statements `__ - `PEP 340 - possible new name for block-statement `__ - `Generating nested data structures with blocks `__ - `PEP 340 -- Clayton's keyword? `__ - `PEP 340: Only for try/finally? `__ - `2 words keyword for block `__ - `anonymous blocks `__ - `"begin" as keyword for pep 340 `__ - `PEP 340: propose to get rid of 'as' keyword `__ - `PEP 340 keyword: after `__ - `PEP 340 keyword: Extended while syntax `__ - `PEP 340 - Remaining issues - keyword `__ - `PEP 340: Examples as class's. `__ - `Proposed alternative to __next__ and __exit__ `__ - `"with" use case: exception chaining `__ - `PEP 343: Resource Composition and Idempotent __exit__ `__ - `[Python-checkins] python/nondist/peps pep-0343.txt, 1.8, 1.9 `__ - `the current behavior of try: ... finally: `__ - `a patch to inspect and a non-feature request `__ - `Python 2.4 set objects and cyclic garbage `__ - `CHANGE BayPIGgies: May *THIRD* Thurs `__ - `Python continually calling sigprocmask() on FreeBSD 5 `__ - `Weekly Python Patch/Bug Summary `__ - `problems with memory management `__ - `Adding DBL_MANTISSA and such to Python `__ - `python-dev Summary for 2005-04-16 through 2005-04-30 [draft] `__ - `Python Language track at Europython, still possibilities to submit talks `__ - `(no subject) `__ - `Kernel panic writing to /dev/dsp with cmpci driver `__ ======== Epilogue ======== ------------ Introduction ------------ This is a summary of traffic on the `python-dev mailing list`_ from May 01, 2005 through May 15, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the third summary written by the python-dev summary cabal of Steve Bethard, Tim Lesher, and Tony Meyer. To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tim Lesher (tlesher at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. I do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow me to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/ .. _original text file: http://www.python.org/dev/summary/2005-05-01_2005-05-15.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From sjmachin at lexicon.net Mon Jun 20 19:38:02 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 21 Jun 2005 09:38:02 +1000 Subject: Python and encodings drives me crazy In-Reply-To: References: <6f7b52d05062013545cbc435d@mail.gmail.com> <6f7b52d05062014292f25e8a9@mail.gmail.com> <4660fe3005062015135c516cbc@mail.gmail.com> Message-ID: <42B7535A.7000702@lexicon.net> Oliver Andrich wrote: > 2005/6/21, Konstantin Veretennicov : > >>It does, as long as headline and caption *can* actually be encoded as >>macroman. After you decode headline from utf-8 it will be unicode and >>not all unicode characters can be mapped to macroman: >> >> >>>>>u'\u0160'.encode('utf8') >> >>'\xc5\xa0' >> >>>>>u'\u0160'.encode('latin2') >> >>'\xa9' >> >>>>>u'\u0160'.encode('macroman') >> >>Traceback (most recent call last): >> File "", line 1, in ? >> File "D:\python\2.4\lib\encodings\mac_roman.py", line 18, in encode >> return codecs.charmap_encode(input,errors,encoding_map) >>UnicodeEncodeError: 'charmap' codec can't encode character u'\u0160' in position >> 0: character maps to > > > Yes, this and the coersion problems Diez mentioned were the problems I > faced. Now I have written a little cleanup method, that removes the > bad characters from the input By "bad characters", do you mean characters that are in Unicode but not in MacRoman? By "removes the bad characters", do you mean "deletes", or do you mean "substitutes one or more MacRoman characters"? If all you want to do is torch the bad guys, you don't have to write "a little cleanup method". To leave a tombstone for the bad guys: >>> u'abc\u0160def'.encode('macroman', 'replace') 'abc?def' >>> To leave no memorial, only a cognitive gap: >>> u'The Good Soldier \u0160vejk'.encode('macroman', 'ignore') 'The Good Soldier vejk' Do you *really* need to encode it as MacRoman? Can't the Mac app understand utf8? You mentioned cp850 in an earlier post. What would you be feeding cp850-encoded data that doesn't understand cp1252, and isn't in a museum? Cheers, John From rkern at ucsd.edu Wed Jun 8 03:53:12 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 08 Jun 2005 00:53:12 -0700 Subject: Matplotlib w/ TK Backend. In-Reply-To: References: Message-ID: Kenneth Miller wrote: > Hello All, > > I need a python module to do real time graphs so I chose Matplotlib. I > am trying to compile matplotlib at the moment and I have some problems, > well not really. It compiles fine, it's how it compiles that's the > problem. I am attempting to build it with the Tkinter backend as opposed > to the GTK+ backend. Whenever I build, install, and then try to import I > receive an error stating that my version of PyGTK needs to be updated. > Logically it shouldnt be looking for PyGTK if it is using the TKinter > backend? Any help would be appreciated. A. You will get better help on the matplotlib mailing list. B. Have you edited your .matplotlibrc to use the TkAgg backend? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From grante at visi.com Tue Jun 21 19:08:31 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 21 Jun 2005 23:08:31 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 Message-ID: <11bh7ffsps4ea3@corp.supernews.com> I finally figured out why one of my apps sometimes fails under Win32 when it always works fine under Linux: Under Win32, the pickle module only works with a subset of floating point values. In particular the if you try to dump/load an infinity or nan value, the load operation chokes: Under Linux: $ python Python 2.3.4 (#2, Feb 9 2005, 14:22:48) [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >> $ python pickletest.py (inf, nan) (inf, nan) Under Win32: $ python ActivePython 2.3.4 Build 233 (ActiveState Corp.) based on Python 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >> $ python pickletest.py Traceback (most recent call last): File "pickletest.py", line 8, in ? d = pickle.loads(s) File "C:\PYTHON23\lib\pickle.py", line 1394, in loads return Unpickler(file).load() File "C:\PYTHON23\lib\pickle.py", line 872, in load dispatch[key](self) File "C:\PYTHON23\lib\pickle.py", line 968, in load_float self.append(float(self.readline()[:-1])) ValueError: invalid literal for float(): 1.#INF I realize that this is probably due to underlying brokenness in the Win32 libc implimentation, but should the pickle module hide such platform-dependancies from the user? Best case, it would be nice if pickle could handle all floats in a portable way. Worst case, shouldn't the pickle module documentation mention that pickling floats non-portable or only partially implimented? On a more immediate note, are there hooks in pickle to allow the user to handle types that pickle can't deal with? Or, do I have to throw out pickle and write something from scratch? [NaN and Infinity are prefectly valid (and extremely useful) floating point values, and not using them would require huge complexity increases in my apps (not using them would probably at least triple the amount of code required in some cases).] -- Grant Edwards grante Yow! Yow! at visi.com From spam.csubich+block at block.subich.spam.com Wed Jun 8 20:56:34 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 20:56:34 -0400 Subject: Decimal Places Incorrect In-Reply-To: References: Message-ID: <1rMpe.66462$6k7.17188@bignews4.bellsouth.net> Tom Haddon wrote: > Hi Folks, > > When I run: > > print "%0.2f" % ((16160698368/1024/1024/1024),) > > I get 15.00 > > I should be getting 15.05. Can anyone tell me why I'm not? Short answer: Integer division. Long answer: Integer division. 16160698368/1024 = 15781932L 15781932L/1024 = 15412 15412/1024 = 15 Fix: >>> print "%.02f" % (float(16160698368)/1024/1024/1024,) 15.05 From csstevens at gmail.com Wed Jun 1 23:29:21 2005 From: csstevens at gmail.com (Svens) Date: 1 Jun 2005 20:29:21 -0700 Subject: Beginner question: Logs? Message-ID: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> Hey everyone! I'm a math student working on a short script involving logs. I have a function on my scientific calculator, and was wondering if there was a similar funtion in python. For example: (log65536)/(log4)= 8 I've searched around a bit and haven't been able to find anything. Thanks! -Christian From mkluwe at gmail.com Tue Jun 21 11:39:02 2005 From: mkluwe at gmail.com (Matthias Kluwe) Date: 21 Jun 2005 08:39:02 -0700 Subject: smtplib and TLS References: <1119034830.168876.26290@f14g2000cwb.googlegroups.com> <7xmzpoyusq.fsf@ruckus.brouhaha.com> Message-ID: <1119368342.884338.266040@g43g2000cwa.googlegroups.com> > From: "Paul Rubin" "http://phr.cx"@NOSPAM.invalid >> "Matthias Kluwe" writes: >> After getting a @gmail.com address, I recognized I had to use TLS in my >> python scripts using smtplib in order to get mail to the smtp.gmail.com >> server. >> [...] >> The server accepts and delivers my messages, but the last command >> raises >> socket.sslerror: (8, 'EOF occurred in violation of protocol') > [...] > Have you verified that its your end that is broken, not gmail's, do other > servers give the same response ? No, I have not -- I should have, as I know now: Connecting, starttls, login and sending mail works fine without the above mentioned error using my previous mail provider. Does that mean Gmail is in error here? I don't know... Regards, Matthias From tjreedy at udel.edu Sun Jun 12 12:47:40 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 12 Jun 2005 12:47:40 -0400 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net><200506102209.49469.hancock@anansispaceworks.com><7xekb84rsa.fsf@ruckus.brouhaha.com><7x7jh0l5kg.fsf@ruckus.brouhaha.com> <7xwtp09jh3.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xwtp09jh3.fsf at ruckus.brouhaha.com... > Andrew Dalke writes: >> If that's indeed the case then I'll also argue that each of >> them is going to have app-specific choke points which are best >> hand-optimized and not framework optimized. Is there enough >> real-world experience to design a EnterpriseWeb-o-Rama (your >> "printing press") which can handle those examples you gave >> any better than starting off with a LAMP system and hand-caching >> the parts that need it? > > Yes, of course there is. Look at the mainframe transaction systems of > the 60's-70's-80's, for example. Look at Google. Based on what I've read, if we could look at Google, we would see 150,000 to 200,000 servers (about half bought with IPO money). We would see a highly customized dynamic cluster computing infrastructure that can be utilized with high-level (Python-like) commands. The need to throw hundreds of machines at each web request strikes me as rather specialized, though definitely not limited to search. So while not LAMP, I don't see it as generic EWeboRama either. Terry J. Reedy From tim.golden at viacom-outdoor.co.uk Tue Jun 7 10:21:48 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 7 Jun 2005 15:21:48 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) Message-ID: <9A28C052FF32734DACB0A288A3533991EBB891@vogbs009.gb.vo.local> [Simon Brunning] | Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) [... snipped whole thing ...] Just wanted to say thank you to Simon and all the other people who have edited the Python-URL! weekly digest over the years. Despite my being a pretty much constant reader of c.l.py and various blogs and other on-line sources, I still look forward to to its weekly arrival. That's both because of the mild editorial introductions and also because it will almost certainly pick up something I've missed (sometimes because it's a gem buried deep within a thread which I've long since given up on!) Thanks, guys. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From http Wed Jun 8 15:04:07 2005 From: http (Paul Rubin) Date: 08 Jun 2005 12:04:07 -0700 Subject: Fast text display? References: Message-ID: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> Christopher Subich writes: > The third requirement is cross-platform-osity; if you won't hold it > against me I'll tell you that I'm developing under Cygwin in Win2k, > but I'd really like it if the app could run under 'nix and mac-osx > also. > > I'm pretty open to any graphical toolkit -- I have experience with > none of them, so I have little in the way of prejudice. Use tkinter if you care about cross-platform operation. Everything else requires downloading and installing separate toolkits. From tim.golden at viacom-outdoor.co.uk Thu Jun 30 10:26:51 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Jun 2005 15:26:51 +0100 Subject: Open the command line within a script Message-ID: <9A28C052FF32734DACB0A288A3533991EBB962@vogbs009.gb.vo.local> [Ivan Shevanski] | Hey this is probally a noob question but here goes. . .How | could I open the | command line inside of a python script? Would I have to use COM? (Assuming you're on Windows from your reference to COM). Depending on exactly what you want to do with it, you could just do: import os shell = os.environ['COMSPEC'] os.system (shell) # or os.startfile (shell) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tim.peters at gmail.com Thu Jun 23 14:54:09 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 23 Jun 2005 14:54:09 -0400 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: <200506231331.44796.hancock@anansispaceworks.com> References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> <200506231331.44796.hancock@anansispaceworks.com> Message-ID: <1f7befae05062311542773e959@mail.gmail.com> [Terry Hancock] > ... > I realize you've probably already made a decision on this, but this sounds > like a classic argument for using an *object DBMS*, such as ZODB: It > certainly does support transactions, and "abstracting the data into tables" > is a non-issue as ZODB stores Python objects more or less directly (you > only have to worry about ensuring that objects are of "persistent" types > -- meaning either immutable, or providing persistence support explicitly). ZODB can store/retrieve anything that can be pickled, regardless of whether it derives from Persistent. There are various space and time efficiencies that can be gained by deriving from Peristent, and ZODB automatically notices when a Persistent object mutates, but that's about it. Andrew Kuchling's intro to ZODB is still a good read (Andrew doesn't work on it anymore, but I take sporadic stabs at updating it): http://www.zope.org/Wikis/ZODB/FrontPage/guide/index.html From gratzel at gmail.com Wed Jun 8 20:40:57 2005 From: gratzel at gmail.com (gratzel at gmail.com) Date: 8 Jun 2005 17:40:57 -0700 Subject: file permissions on windows XP (home) References: <1118097199.228222.216190@g44g2000cwa.googlegroups.com> <2OmdnWpZh4O6EDjfRVn-pQ@powergate.ca> <1118178009.923372.160210@g44g2000cwa.googlegroups.com> <1118266606.590200.118970@g44g2000cwa.googlegroups.com> Message-ID: <1118277656.983871.142170@z14g2000cwz.googlegroups.com> I have noticed a bug that if I have a folder open for viewing in Windows Explorer with Thumbnail view enabled that I often run into inexplicable problems with modify permissions, say when I want to rename or delete an item. Changing the view to Detailed or rebooting seems to make the issue go away. From david.bear at asu.edu Wed Jun 1 14:37:49 2005 From: david.bear at asu.edu (David Bear) Date: Wed, 01 Jun 2005 11:37:49 -0700 Subject: creating a hex value Message-ID: <1285743.rKB6TKaXDy@teancum> I have a file that I need to parse. Items in it are delimited by a hex 15 (0x015). I know it must be trivial to assign a hex value to a variable but I'm not seeing it in my python essential ref. how can I do delim = 0x15 while: ln = file.read() if ln[0] == delim: do something I've looked at the hex function but it doesn't sound like what I want. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From tom at dtsam.com Wed Jun 1 11:52:17 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 1 Jun 2005 10:52:17 -0500 Subject: anygui,anydb, any opinions? References: Message-ID: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> "rzed" wrote in message news:Xns9667883C1D343jreeder at 63.223.7.253... > So what do you think? What's wrong with the picture? Why isn't > there a greater priority to work in this direction? > What's wrong with the picture? Just one teeny little item. The Python world lacks the phenomenally successful development models enjoyed by the now ancient Turbo Pascal, Delphi and Visual Basic. AND If the likes of Visual Basic can have it, then it becomes really, *really* hard to convince the world that Python is a serious, professional system. At some point, one has to break out of theory and produce! Or challenge the theory with some hard questions. Thomas Bartkus From sjmachin at lexicon.net Tue Jun 21 19:44:30 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 22 Jun 2005 09:44:30 +1000 Subject: utf8 silly question In-Reply-To: References: <1374382022.20050621191607@bounce-software.com> Message-ID: <42b8a65e@news.eftel.com> Jeff Epler wrote: > If you want to work with unicode, then write > us = u"\N{COPYRIGHT SIGN} some text" You can avoid almost all the wear and tear on your shift keys: >>> u"\N{copyright sign}" u'\xa9' ... you are stuck with \N for reasons that should be obvious :-) Cheers, John From andreas at kostyrka.org Tue Jun 14 04:02:02 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 14 Jun 2005 10:02:02 +0200 Subject: What is different with Python ? In-Reply-To: <3r4sa1dqi3qbdfqpepcg0p0imnbhg65c8b@4ax.com> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <3r4sa1dqi3qbdfqpepcg0p0imnbhg65c8b@4ax.com> Message-ID: <20050614080202.GA18911@heaven.kostyrka.org> On Tue, Jun 14, 2005 at 12:02:29AM +0000, Andrea Griffini wrote: > However I do not think that going this low (that's is still > IMO just a bit below assembler and still quite higher than > HW design) is very common for programmers. Well, at least one University (Technical University Vienna) does it this way. Or did it at least when I passed the courses ;) > > >Or how does one explain that a "stupid and slow" algorithm can be in > >effect faster than a "clever and fast" algorithm, without explaining > >how a cache works. And what kinds of caches there are. (I've seen > >documented cases where a stupid search was faster because all hot data > >fit into the L1 cache of the CPU, while more clever algorithms where > >slower). > > Caching is indeed very important, and sometimes the difference > is huge. I think anyway that it's probably something confined > in a few cases (processing big quantity of data with simple > algorithms, e.g. pixel processing). > It's also a field where if you care about the details the > specific architecture plays an important role, and anything > you learned about say the Pentium III could be completely > pointless on the Pentium 4. Nope. While it's certainly true that it's different from architecture to architecture, you need to learn the different types of caches, etc. so that one can quickly crasp the architecture currently in use. > Except by general locality rules I would say that everything > else should be checked only if necessary and on a case-by-case > approach. I'm way a too timid investor to throw in neurons > on such a volatile knowledge. It's not volatile knowledge. Knowledge what CPU uses what cache organisation is volatile and wasted knowledge. Knowledge what kinds of caches are common is quite useful ;) Easy Question: You've got 2 programs that are running in parallel. Without basic knowledge about caches, the naive answer would be that the programs will probably run double time. The reality is different. > >Or you get perfect abstract designs, that are horrible when > >implemented. > > Current trend is that you don't even need to do a > clear design. Just draw some bubbles and arrows on > a white board with a marker, throw in some buzzword > and presto! you basically completed the new killing app. Well, somehow I'm happy that it is this way. That ensures enough work for me, because with this approach somebody will call in the fire department when it doesn't work anymore ;) Or the startup goes belly up. > Real design and implementation are minutiae for bozos. > > Even the mighty python is incredibly less productive > than powerpoint ;-) > > >Yes. But for example to understand the memory behaviour of Python > >understanding C + malloc + OS APIs involved is helpful. > > This is a key issue. If you've the basis firmly placed > most of what follows will be obvious. If someone tells > you that inserting an element at the beginning of an array > is O(n) in the number of elements then you think "uh... ok, > sounds reasonable", if they say that it's amortized O(1) > instead then you say "wow..." and after some thinking > "ok, i think i understand how it could be done" and in > both cases you'll remember it. It's a clear *concrete* fact > that I think just cannot be forgot. Believe it can ;) But that's the idea why certain courses forced us to implement at least the most important data structures by ourselves. Because looking at it in a book is so much less intensive than doing it ;) Andreas From jhe13586 at bigpond.net.au Thu Jun 9 04:54:08 2005 From: jhe13586 at bigpond.net.au (Joal Heagney) Date: Thu, 09 Jun 2005 08:54:08 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 7) In-Reply-To: References: Message-ID: Ville Vainio wrote: >>>>>>"Fred" == Fred Pacquier writes: > > > Fred> Same here : thanks for letting us get away with being > Fred> lazy(er) ! :-) > > Ditto. As someone who's done a couple of p-url's, I can say it's quite > a bit of work to find the interesting tidbits from the depths of > 500-post threads where people can't be bothered to change the subject > line... > *grins* My computer hard-drive is FULL of emails/webpages/documents of python snippets that the Python-URL's have made me aware of. Great community resource. (Are the old weekly URL's stored somewhere other than the newsgroup archives?) Joal From ajikoe at gmail.com Tue Jun 14 04:58:06 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 14 Jun 2005 01:58:06 -0700 Subject: gobal var inside class without notice??? In-Reply-To: References: <1118738391.216206.142280@g47g2000cwa.googlegroups.com> Message-ID: <1118739486.835580.45150@g44g2000cwa.googlegroups.com> Thanks a lot. pujo From smitty_one_each at bigfoot.com Fri Jun 17 19:19:25 2005 From: smitty_one_each at bigfoot.com (Chris Smith) Date: Fri, 17 Jun 2005 18:19:25 -0500 Subject: Cause for using objects? References: Message-ID: <871x70bmgy.fsf@bigfoot.com> >>>>> "John" == John Heasly writes: John> Given: [{"mugshot": "nw_gradspeaker4_0608", "width": 67.0, John> "height": 96.0}, \ {"mugshot": "nw_gradspeaker2_0608", John> "width": 67.0, "height": 96.0}, \ {"freehand": John> "b1.developreport.0614", "width": 154.0, "height": 210.0}, \ John> {"graphic": "bz_cafeparadiso_0613", "width": 493.0, John> "height": 341.0}] John> Return: {"mugshot1": "nw_gradspeaker4_0608", John> "mugshot1.width": 67.0, "mugshot1.height": 96.0,\ John> "mugshot2": "nw_gradspeaker2_0608", "mugshot2.width": 67.0, John> "mugshot2.height": 96.0, \ "freehand1": John> "b1.developreport.0614", "freehand1.width": 154.0, John> "freehand1.width": 210.0, \ "graphic1": John> "bz_cafeparadiso_0613", "graphic1.width": 493.0, John> "graphic1.height": 341.0} John> I'm trying to teach myself some OOP. Does grinding the Given John> above into the Return seem like a good candidate? John> John H. Eugene, Ore. jheasly at guardnet dot com If your table of photo data has several types of photos, and you find yourself saying if is_mugshot: #something elif is_freehand: #something else: #something then OOP will help organize your code. If it's just a flat table of data, and you lay down a deeply nested hierarchy of stuff, you may have over-engineered. Best, Chris From grante at visi.com Wed Jun 22 22:53:23 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Jun 2005 02:53:23 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> Message-ID: <11bk913pvr240b2@corp.supernews.com> On 2005-06-22, Paul Rubin wrote: >>> Negative 0 isn't a NaN, it's just negative 0. >> >> Right, but it is hard to construct in standard C. > > Huh? It's just a hex constant. Yup. There are two ways to construct a NaN. One is to do something like (1e300*1e300)/(1e300*1e300) and hope for the best. The other is to assume IEEE 754 just use 7f800000 or 7fc00000 depending on whether you want a signalling or quiet NaN. -- Grant Edwards grante Yow! Don't hit me!! I'm in at the Twilight Zone!!! visi.com From saint.infidel at gmail.com Wed Jun 1 14:19:50 2005 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2005 11:19:50 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117647935.916469.164160@g47g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> Message-ID: <1117649990.028395.116640@f14g2000cwb.googlegroups.com> Ok, forget everything I've said. The more I think about this the less I understand it. I'm way out of my league here. sitting-down-and-shutting-up-ly y'rs, infi From maxm at mxm.dk Tue Jun 28 13:03:12 2005 From: maxm at mxm.dk (Max M) Date: Tue, 28 Jun 2005 19:03:12 +0200 Subject: Boss wants me to program In-Reply-To: References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119956464.362328.290370@o13g2000cwo.googlegroups.com> Message-ID: <42c1829a$0$246$edfadb0f@dread12.news.tele.dk> phil wrote: > You would be wise, if you choose Python to choose Tkinter or WxWindows > and learn the properties of a radio button and how to trigger events. > Writing simple GUIs is not that hard. Then after you know what is > going on behind the scenes, a BOA Constructor will not be as > mysterious or dangerous. I agree. The language is more important than the gui. It is not very hard to make good applikations in eg. Tkinter, and you will understand evey part of it. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From steve at REMOVETHIScyber.com.au Sat Jun 25 14:14:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 04:14:19 +1000 Subject: How does one write a function that increments a number? References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> Message-ID: On Fri, 24 Jun 2005 21:53:03 -0700, anonymousnerd at gmail.com wrote: > Apologies if this question seems stupid: How does one write a > function that increments a value in Python? When I tried, the variable > never changed. > The session went like this: >>>> def incr(counter): > counter = int(counter) > counter += 1 > >>>> counter = 1 >>>> incr(counter) >>>> print counter > 1 Why does it need to be a function? Why complicate matters? Isn't it simpler to just do this: counter = 1 counter += 1 print counter -- Steven From fphsml at gmail.com Thu Jun 16 16:34:07 2005 From: fphsml at gmail.com (James) Date: 16 Jun 2005 13:34:07 -0700 Subject: UML to Python/Java code generation In-Reply-To: References: Message-ID: <1118954047.845713.98450@z14g2000cwz.googlegroups.com> > Is there any UML tools that is able to take UML and generate Python codes? Dia2code generates Python from UML. Boa Constructor generates UML from Python. PyUt. Object Domain's UML Tool (Commercial) You need to use Google. From sbucking at gmail.com Thu Jun 9 09:16:43 2005 From: sbucking at gmail.com (sbucking at gmail.com) Date: 9 Jun 2005 06:16:43 -0700 Subject: splitting strings with python In-Reply-To: References: <1118308380.823382.146430@g47g2000cwa.googlegroups.com> Message-ID: <1118323003.467785.18780@o13g2000cwo.googlegroups.com> sorry, i should be more specific about the encoding it's euc-jp i googled alittle, and you can still use re.findall with the japanese kana, but i didnt find anything about kanji. From none at no.chance Wed Jun 29 14:49:10 2005 From: none at no.chance (Peter Tillotson) Date: Wed, 29 Jun 2005 18:49:10 +0000 Subject: importing packages from a zip file In-Reply-To: <42c2d483$1@nntp0.pdx.net> References: <42c2d483$1@nntp0.pdx.net> Message-ID: cheers Scott should have been from myZip.zip import base.branch1.myModule.py and no it didn't work, anyone know a reason why this syntax is not preferred ?? sorry posted the soln again, it works but feels nasty Scott David Daniels wrote: > Peter Tillotson wrote: > >> ... With the file system >> >> base/ >> __init__.py >> branch1/ >> __init__.py >> myModule.py >> >> At the same time its possible to store modules in a flat zip-file and >> import modules with the following. >> >> > > > Does this work for you? It gives me a syntax error. > > Typically, put the zip file on the sys.path list, and import modules > and packages inside it. If you zip up the above structure, you can use: > > sys.path.insert(0, 'myZip.zip') > import base.branch1.myModule > > --Scott David Daniels > Scott.Daniels at Acm.Org From edbiano at rocketmail.com Wed Jun 15 23:05:02 2005 From: edbiano at rocketmail.com (Eduardo Biano) Date: Wed, 15 Jun 2005 20:05:02 -0700 (PDT) Subject: Called function conditional testing (if) of form variables problem Message-ID: <20050616030502.77328.qmail@web41006.mail.yahoo.com> Hi, I have a problem making conditional testing (if) of a form variable "ans01"(refer generated error). When the form variable is tested (if) by a called function (foo) the value of "ans01" is not properly represented. def foo(request): ans01 = request.get_form_var("ans01") if ans01 == 4: ans_1 = 1 return ans_1 The browser returns a blank screen or ans_1 is blank. I tried to "return ans01" and the browser returned the number 4. I am quiet sure of the above code and searched python resources but found no solution. Please help. Thank you in advance. ************************** Below is a generated error to check the contents of submitted form. ___________________________ .................. NameError: ................... Form: ans01 4 ans02 1 ans03 1 ans04 1 ans05 1 ans06 1 ans07 1 comments headid 068A114 id 0646205 submit Submit ******************************* __________________________________ Discover Yahoo! Get on-the-go sports scores, stock quotes, news and more. Check it out! http://discover.yahoo.com/mobile.html From steven.bethard at gmail.com Mon Jun 20 10:35:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Jun 2005 08:35:29 -0600 Subject: import via pathname In-Reply-To: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> References: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> Message-ID: passion_to_be_free at hotmail.com wrote: > I know this is wrong syntax, but I think it demonstrates what I'm > trying to do: > > import myModule path = /modules/myModule > import myModule2 path = /modules/myModule2 > > Something like that. Is it possible? I would put your additional modules into a 'modules' directory with an __init__.py. For example: py> os.listdir('.') ['modules'] py> os.listdir('modules') ['my_module1.py', 'my_module2.py', '__init__.py'] py> file('modules/__init__.py').read() '' py> file('modules/my_module1.py').read() 'name = "module1"\n' py> file('modules/my_module2.py').read() 'name = "module2"\n' Then, if you place your python script in the same directory as the 'modules' directory, you can simply import the additional modules from the 'modules' package: py> import modules.my_module1 as module1 py> module1.name 'module1' py> import modules.my_module2 as module2 py> module2.name 'module2' Note that the 'modules' package needs to be at the same directory level as your Python module. If you want your 'modules' directory in a different location, you may want to go the way of Thomas G?ttler's suggestion and modify sys.path. But I probably wouldn't if you don't have to. STeVe From sjmachin at lexicon.net Sat Jun 18 01:09:10 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Jun 2005 15:09:10 +1000 Subject: extreme newbie In-Reply-To: <1119068711.730364.215290@g47g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> Message-ID: <42B3AC76.2060504@lexicon.net> Harlin Seritt wrote: > Am I the only one who wonders this: If Python at runtime runs > very much like Java and has generally about the same speed (or faster), > then why in the world isn't Java becoming more archaic and being > steadily replaced by Python? I ask this not as a rhetorical question, > but --really-- how come developers are still stuck on Java when Python > seems to be a far better language? Compare Sun's marketing budget with the PSF's. Why did IBM mainframes once rule the world? From greg at cosc.canterbury.ac.nz Wed Jun 8 23:00:42 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 15:00:42 +1200 Subject: Embedding: many interpreters OR one interpreter with many thread states ? In-Reply-To: <1118239578.831376.218370@o13g2000cwo.googlegroups.com> References: <1118239578.831376.218370@o13g2000cwo.googlegroups.com> Message-ID: <3gppn9FdnnldU1@individual.net> adsheehan at eircom.net wrote: > - creating many sub-interpreters (Py_NewInterpreter) with a thread > state each > > Or > > - creating one interpreter with many thread states (PyThreadState_New) My understanding is that using multiple interpeters isn't really supported properly, despite there being apparent support in the API. So I suggest using a single interpeter with multiple threads. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From jjeffers at accipiter.com Fri Jun 10 09:33:42 2005 From: jjeffers at accipiter.com (James Jeffers) Date: Fri, 10 Jun 2005 13:33:42 GMT Subject: unittest and XML output Message-ID: I couldn't find any resource that addresses output from the unittest package in python 2.4.x. I can't beleive that there isn't an output formatter/test runner for the unittest package.. surely some needed this before. Is there a working group or package maintainer for these kinds of features? Thanks in advance, James From michele.simionato at gmail.com Mon Jun 20 00:00:01 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 19 Jun 2005 21:00:01 -0700 Subject: "static" data descriptors and possibly spurious calls to __set__? In-Reply-To: References: Message-ID: <1119240001.775921.221640@z14g2000cwz.googlegroups.com> >...it's this last one that causes the problem. In the real code, the >call to type.__setattr__ referred to above seems to lead to a call to >something like cls.__base__.__dict__[attr].__set__(cls, value). Uhm ... sounds right, but I a bit confused. Could you please give us a doctest showing us what you get and what you would like to get? Michele Simionato Michele Simionato From rkern at ucsd.edu Sun Jun 19 01:21:27 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 18 Jun 2005 22:21:27 -0700 Subject: Extensions on Linux: import without underscore? In-Reply-To: References: Message-ID: James Carroll wrote: > Thanks Robert. > >>Call it bright.so . > > If I rename it bright.so, then I get the error: > ImportError: dynamic module does not define init function (initbright) Sorry, I should have been clearer. Just renaming the file won't help. The init function also needs to be appropriately named. > I'm using swig with the module declaration > %module bright > > I've looked at some other source, and it looks like there are some > good reasons to have a bright.py that passes calls on to _bright. Reread the SWIG documentation. If it is going to prepend an underscore to the extension name, it is usually also generating the appropriate bright.py . I suspect that this is why it "worked" on Windows but didn't work when you moved to Linux. >>If at all possible, you should use distutils to build Python extensions. > > Where can I find similar distutils C++ examples? Can it do most of > what Scons does? Even better, it will handle running SWIG, too. wxPython itself is an example, and one that you most certainly should emulate. >>If you must use Scons, read >> >> http://www.scons.org/cgi-bin/wiki/PythonExtensions > > Very nice, strange that didn't show up for all my googles of scons > python, etc. I like how it uses distutils to get flags... I'm > extending wxPython, so I'm using the wxWidgets > env.ParseConfig('wx-config --cppflags --libs') Technique... I'll > have to ponder using one or the other or both. Hmm.... If you're extending wxPython, cannibalize wxPython's build procedure. Any other way, there madness lies. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From claudio.grondi at freenet.de Sat Jun 11 18:31:40 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 11 Jun 2005 22:31:40 -0000 Subject: What is different with Python ? References: Message-ID: <3h104kFerk88U1@individual.net> Re: What is different with Python ? from my point of view, to be honest, nothing except mixing a well spiced soup of what was available within other programming languages. I think, that what currently makes a real difference is not the language as such, but the people using it, posting here and writing new modules for it. I can imagine, that with becoming more popular and less supported by the core development team (following a special kind of programming philosophy called "Pythonic way" of approaching things) this can change, so I can only hope, that this won't happen. Don't ask _me_ what "Pythonic way" is - I think, you have to feel it yourself in order to understand it (I haven't yet seen any definition of it different from what is already also known from other programming languages, but maybe someone can provide it?). by the way: I see a contradiction between > - 1) I do not consider my intelligence/education above average and > - 5) I have developed for many years (>18) in many different environments, > languages, and O/S's (including realtime kernels) . because - 5) is the story many of programmers choosing Python as a tool or programming language of their choice went through and because of the fact you are here asking that question. Claudio "Philippe C. Martin" schrieb im Newsbeitrag news:bXGqe.2582$751.2437 at newssvr30.news.prodigy.com... > I apologize in advance for launching this post but I might get enlightment > somehow (PS: I am _very_ agnostic ;-). > > - 1) I do not consider my intelligence/education above average > - 2) I am very pragmatic > - 3) I usually move forward when I get the gut feeling I am correct > - 4) Most likely because of 1), I usually do not manage to fully explain 3) > when it comes true. > - 5) I have developed for many years (>18) in many different environments, > languages, and O/S's (including realtime kernels) . > > > Yet for the first time I get (most) of my questions answered by a language I > did not know 1 year ago. > > As I do try to understand concepts when I'm able to, I wish to try and find > out why Python seems different. > > Having followed this newsgroup for sometimes, I now have the gut feeling > (see 3)) other people have that feeling too. > > > Quid ? > > Regards, > > Philippe > > > > > > > > > > From grante at visi.com Fri Jun 10 15:16:56 2005 From: grante at visi.com (Grant Edwards) Date: Fri, 10 Jun 2005 19:16:56 -0000 Subject: without shell References: <11aj9d3fga9or8b@corp.supernews.com> <11ajkap3isrmndf@corp.supernews.com> Message-ID: <11ajpp8jl828o30@corp.supernews.com> On 2005-06-10, Donn Cave wrote: >> Also, for each of these variants, on Unix, cmd may be a >> sequence, in which case arguments will be passed directly to >> the program without shell intervention (as with os.spawnv()). >> If cmd is a string it will be passed to the shell (as with >> os.system()). >> >> It's not exactly clear what "these variants" refer to, but I >> read it as referring to all of the the os.popen functions. >> >> Perhaps it only refers to os.popen[234]? > > Right. The paragraphs seem a little scrambled. Note > the use of "cmd" instead of "command" as the parameter > is named for popen(). Also note "These methods do not > make it possible to retrieve the return code from the > child processes", after the popen() paragraph above tells > you how to do it (using the better term "exit status".) > > Or one may look at the source. Or write a 3-line test to see how it really does works. :) -- Grant Edwards grante Yow! ... I don't like at FRANK SINATRA or his visi.com CHILDREN. From fperez.net at gmail.com Wed Jun 8 13:36:46 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 08 Jun 2005 11:36:46 -0600 Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <1118209749.248567.168700@g49g2000cwa.googlegroups.com> <1118233766.928467.261650@z14g2000cwz.googlegroups.com> <797fe3d405060810232eb2e85e@mail.gmail.com> Message-ID: Bill Mill wrote: > On 6/8/05, Fernando Perez wrote: >> Rahul wrote: >> >> > >> > Hi. >> > The reason is simple enough. I plan to do some academic research >> > related to computer algebra for which i need some package which i can >> > call as a library. Since i am not going to use the package >> > myself..(rather my program will)..it will be helpful to have a python >> > package since i wanted to write the thing in python. if none is >> > available then probably i will need to work on an interface to some >> > package written in some other language or work in that language itself. >> >> I've heard of people writing a Python MathLink interface to Mathematica, >> which >> essentially turns Mathematica into a Python module. But I don't have any >> references handy, sorry, and as far as I remember it was done as a private >> contract. But it's doable. >> > > What about http://library.wolfram.com/infocenter/MathSource/585/ ? > Seems to be non-proprietary, or something different, but does it work? > I don't have Mathematica, so I don't know. Mmh, not very promising. I just downloaded it, and it looks pretty dated: PYML is a python interface to Mathematica which uses MathLink. It allows the Python programmer to evaluate Mathematica expressions. Expressions are passed to PYML as a Python object, which is processed into MathLink calls. PYML calls MathLink to evaluate the expression and prints the result. Currently, PYML supports Mathematica 2.2 and 3.0. The program is evolving continuously. given that Mathematica is at v5.1, this may or may not work. It's from 1998, has no setup.py, etc. It might still work, and if nothing else it would be a perfect starting point and a nice project to revive. But I don't have the time nor the need for this right now, perhaps the OP might want to play with it. Thanks for the reference though, I didn't know abou it. Best, f From roy at panix.com Thu Jun 30 21:23:09 2005 From: roy at panix.com (Roy Smith) Date: Thu, 30 Jun 2005 21:23:09 -0400 Subject: map vs. list-comprehension References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: Terry Hancock wrote: > One of the strengths of Python has been that the language itself is > small (which it shares with C and (if I understand correctly, not being > a lisp programmer?) Lisp), but with all the syntax enhancements going > on, Python is getting pretty complicated. I have to wonder if new users > won't begin to find it just as intimidating as Perl or other big > languages. +1 Even some of the relatively recent library enhancements have been kind of complicated. The logging module, for example, seems way over the top. Look at what happened to C when it mutated into C++. In isolation, most of the features of C++ seem like good ideas. Taken together, it's a huge hairy mess that most people only understand increasingly larger subsets of. Fred Brooks called it the second system sy From jan.danielsson at gmail.com Wed Jun 15 08:46:04 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 15 Jun 2005 14:46:04 +0200 Subject: FAQ: __str__ vs __repr__ Message-ID: <42b021ba$1@griseus.its.uu.se> Sorry, but I Just Don't Get It. I did search the 'net, I did read the FAQ, but I'm too dumb to understand. As far as I can gather, __str__ is just a representation of the object. For instance: class ServerConnection: def __str__(self): buf = "Server: " + self.name + "\n" buf += "Sent bytes: " + str(self.sentBytes) + "\n" buf += "Recv bytes: " + str(self.recvBytes) + "\n" return buf However, I don't understand what __repr__ should be. There's a phrase in the documentation which makes it highly confusing for a beginner like me: "If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).". What does that mean? Does it mean that I should return: def __str__(self): buf = "self.name=" + self.name + "\n" buf += "self.sentBytes=" + str(self.sentBytes) + "\n" buf += "self.recvBytes=" + str(self.recvBytes) + "\n" return buf ..or is there some other "valid Python expression" format which I have yet to encounter? From peter at engcorp.com Sat Jun 11 21:52:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 11 Jun 2005 21:52:57 -0400 Subject: What is different with Python ? In-Reply-To: <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Philippe C. Martin wrote: > too. I'm actually pushing the few CS professors I know to use Python for CS > 101. Yet, many issues that a future software engineer should know are > mostly hidden by Python (ex: memory management) and that could be > detrimental. I think new CS students have more than enough to learn with their *first* language without having to discover the trials and tribulations of memory management (or those other things that Python hides so well). Simple concepts like variables, control structures, input and output are more than enough to start with. In fact, I suspect any course that attempts to teach with a language that requires things like manual memory management will be failing to provide an effective grounding in computer science because of all the noise. Seeing the forest for the trees and all that... -Peter From jan.danielsson at gmail.com Wed Jun 29 15:16:05 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 29 Jun 2005 21:16:05 +0200 Subject: Graphs/statistics using wxPython In-Reply-To: References: <42c2df8b$1@griseus.its.uu.se> <42c2e859$1@griseus.its.uu.se> Message-ID: <42c2f21a$1@griseus.its.uu.se> Robert Kern wrote: [---] > It's okay. Just about every Pythonista in the sciences has, at one time > or another, started a plotting library. It's a rite of passage. Welcome > to the club. :-) Question: I need to install SciPy in order to use matplotlib, but on the download page I see that there are versions for Python 2.2.x and 2.3.x. I use 2.4.1 -- will bad things happen if I try to use the build for 2.3.x? From averywarren at bellsouth.net Sun Jun 26 19:34:14 2005 From: averywarren at bellsouth.net (Avery Warren) Date: Sun, 26 Jun 2005 18:34:14 -0500 Subject: what is your opinion of zope? Message-ID: I am investigating converting a wiki site to plone. I am having a lot of difficulty finding good documentation programmatically accessing the ZODB API. A lot of the user feedback is centered on how difficult it is to get good documentation on developing using these technologies. My question to comp.lang.python is "what is your opinion of zope?" For those who don't know, zope is a web application server for python developers. From cam.ac.uk at mh391.invalid Sat Jun 25 10:26:41 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 25 Jun 2005 15:26:41 +0100 Subject: a dictionary from a list In-Reply-To: References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: Roy Smith wrote: > I just re-read the documentation on the dict() constructor. Why does it > support keyword arguments? > > dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"} > > This smacks of creeping featurism. Is this actually useful in real code? Personally, I use it all the time. It's a much more convenient literal for a dictionary. And before it was introduced I used this utility function: def mkdict(**kwargs): return kwargs -- Michael Hoffman From hancock at anansispaceworks.com Thu Jun 30 04:46:12 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 30 Jun 2005 03:46:12 -0500 Subject: Favorite non-python language trick? In-Reply-To: <1120103487.450255.18800@g44g2000cwa.googlegroups.com> References: <1120103487.450255.18800@g44g2000cwa.googlegroups.com> Message-ID: <200506300346.12614.hancock@anansispaceworks.com> On Wednesday 29 June 2005 10:51 pm, Paddy wrote: > Joseph Garvin wrote: > 'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > > I use constraints programming at work, Check out "System Verilog" or > OZ/Mozart. > > It would be great if this style of programming could be added to > Python. Check out: http://www.logilab.org/projects/python-logic/ In short, it has been already. This is something pretty new to me, so I can't comment on how well it would meet your expectations, but I see now that the site does mention OZ/Mozart as comparables. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From mccutchen at gmail.com Wed Jun 29 14:39:44 2005 From: mccutchen at gmail.com (Will McCutchen) Date: 29 Jun 2005 11:39:44 -0700 Subject: PIL question: keeping metadata References: <42c2c4ca$0$8490$dbd41001@news.euronet.nl> Message-ID: <1120070384.278692.11180@g47g2000cwa.googlegroups.com> > Is there any way of keeping this info in PIL? I don't think so... when I investigated in the past, I think I discovered that the PIL can't write EXIF data (I might be wrong, though, or my information might be outdated). > Alternatively, is there a simple image > processing package that does it? Try jpegtran: http://sylvana.net/jpegcrop/jpegtran/ You might also be interested in jhead: http://www.sentex.net/~mwandel/jhead/ Will. From rbt at athop1.ath.vt.edu Thu Jun 16 09:27:37 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 16 Jun 2005 09:27:37 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <42ae3411@news.eftel.com> References: <42ae3411@news.eftel.com> Message-ID: <1118928457.18452.13.camel@athop1.ath.vt.edu> On Tue, 2005-06-14 at 11:34 +1000, John Machin wrote: > rbt wrote: > > Here's the scenario: > > > > You have many hundred gigabytes of data... possible even a terabyte or > > two. Within this data, you have private, sensitive information (US > > social security numbers) about your company's clients. Your company has > > generated its own unique ID numbers to replace the social security numbers. > > > > Now, management would like the IT guys to go thru the old data and > > replace as many SSNs with the new ID numbers as possible. > > This question is grossly OT; it's nothing at all to do with Python. > However .... > > (0) Is this homework? No, it is not. > > (1) What to do with an SSN that's not in the map? Leave it be. > > (2) How will a user of the system tell the difference between "new ID > numbers" and SSNs? We have documentation. The two sets of numbers (SSNs and new_ids) are exclusive of each other. > > (3) Has the company really been using the SSN as a customer ID instead > of an account number, or have they been merely recording the SSN as a > data item? Will the "new ID numbers" be used in communication with the > clients? Will they be advised of the new numbers? How will you handle > the inevitable cases where the advice doesn't get through? My task is purely technical. > > (4) Under what circumstances will it not be possible to replace *ALL* > the SSNs? I do not understand this question. > > (5) For how long can the data be off-line while it's being transformed? The data is on file servers that are unused on weekends and nights. > > > > You have a tab > > delimited txt file that maps the SSNs to the new ID numbers. There are > > 500,000 of these number pairs. > > And what is the source of the SSNs in this file??? Have they been > extracted from the data? How? That is irrelevant. > > > What is the most efficient way to > > approach this? I have done small-scale find and replace programs before, > > but the scale of this is larger than what I'm accustomed to. > > > > Any suggestions on how to approach this are much appreciated. > > A sensible answer will depend on how the data is structured: > > 1. If it's in a database with tables some of which have a column for > SSN, then there's a solution involving SQL. > > 2. If it's in semi-free-text files where the SSNs are marked somehow: > > ---client header--- > surname: Doe first: John initial: Q SSN:123456789 blah blah > or > 123456789 > > then there's another solution which involves finding the markers ... > > 3. If it's really free text, like > """ > File note: Today John Q. Doe telephoned to advise that his Social > Security # is 123456789 not 987654321 (which is his wife's) and the soc > sec numbers of his kids Bob & Carol are .... > """ > then you might be in some difficulty ... google("TREC") > > > AND however you do it, you need to be very aware of the possibility > (especially with really free text) of changing some string of digits > that's NOT an SSN. That's possible, but I think not probably. From grante at visi.com Mon Jun 6 17:17:44 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 06 Jun 2005 21:17:44 -0000 Subject: Destructive Windows Script References: <868y1n8b1d.fsf@guru.mired.org> Message-ID: <11a9fboe4av8p25@corp.supernews.com> On 2005-06-06, rbt wrote: >> Just open the raw disk device (assuming your Unix has such), >> and start writing data to it. Keep going until the write fails >> at the end of the media. > > Wouldn't /dev/urandom or /dev/random on Linux systems work > better? Maybe. Last time I found an article on the subject (should have kept a copy), it suggested certain patterns for the initial passes, and then random data for the last passes. The data is converted into one of several RLL encodings (which encoding depends on the drive). The optimal erase patterns depended on the encoding used, so you have to use a several different patterns to cover all the bases. Googling for "secure disk erase pattern rll encoding"... Here's a good but somewhat old paper: http://www.cypherus.com/resources/docs/shred.htm and here's a newer one that deals more with secure deletion of individual files: http://www.usenix.org/events/sec01/full_papers/bauer/bauer_html/ and finally the US Navy's take on the issue: http://www.fas.org/irp/doddir/navy/5239_26.htm > It's the kernel's built in random number generator. It'd fill > the drive with random bits of data. The "really random" device will block when it runs out of entropy. It will probably take the kernel a _long_ time to generate a disk's worth of random data. The pseudo-random device won't block, but the results aren't quite as secure. > You could loop it too... in fact, I think many of the > pre-packaged *wipe* programs are mini Linux distros that do > just this. > > dd if=/dev/random of=/dev/your_hard_drive -- Grant Edwards grante Yow! I always liked FLAG at DAY!! visi.com From eloff777 at yahoo.com Sun Jun 12 16:49:13 2005 From: eloff777 at yahoo.com (eloff777 at yahoo.com) Date: 12 Jun 2005 13:49:13 -0700 Subject: How to test if an object IS another object? References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> <1118608093.758427.280220@g49g2000cwa.googlegroups.com> Message-ID: <1118609353.934316.109870@g49g2000cwa.googlegroups.com> Fascinating. With small strings, it uses the same object, and with small numbers like 3. With 300 they were different objects (why, shouldn't they both be ints still?) Mutable objects functioned differently as you suggested: >>>foo = [] >>>bar = [] >>>foo == bar True >>>foo is bar False Tuples (which are immutable) also appear to be reused >>>foo = () >>>bar = () >>>foo is bar True Thanks for your help, I know how to solve the problem now. -Dan From mwm at mired.org Sun Jun 12 04:57:48 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 12 Jun 2005 03:57:48 -0500 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> <7xekb84rsa.fsf@ruckus.brouhaha.com> <7x7jh0l5kg.fsf@ruckus.brouhaha.com> Message-ID: <86hdg42bqr.fsf@guru.mired.org> Andrew Dalke writes: > Paul Rubin replied to me: >> As for "big", hmm, I'd say as production web sites go, 100k users is >> medium sized, Slashdot is "largish", Ebay is "big", Google is huge. > I'ld say that few sites have >100k users, much less > daily users with personalized information. As a totally made-up > number, only few dozens of sites (maybe a couple hundred?) would > need to worry about those issues. I'd say quite a *lot* of sites have >100k users. A small client of mine was a (now defunct .com) that was focused on "community building". They had a user base of a couple of million people, and you've probably never heard of The Park. They ran six servers, thousands of simultaneous users, and it was all built on LAMP. If you go looking for sites that offer the same kinds of things they did - free web hosting, free web-based email, web-based chat, calendering services, etc., you'll find a lot of such sites, and they all probably have more than 100K users. Of course, when you're talking about millions of web sites, a "few sites" could be a a fairly large number of them. An article I read recently made the point that I think you're trying to make. The author argued that for most sites, scalability just wasn't that big an issue. Web sites are cheap enough that they are affordable to relatively small communities, and in many cases a service that would bomb if they tried to go global with it would be a big success in a small community. As such, he expects the web to be dominated by sites that are really only of interest to a small community. For those sites, LAMP will work just fine. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From deets at web.de Wed Jun 1 14:31:17 2005 From: deets at web.de (Diez B. Roggisch) Date: Wed, 01 Jun 2005 20:31:17 +0200 Subject: using builtin array In-Reply-To: <1117641183.057537.118020@z14g2000cwz.googlegroups.com> References: <1117641183.057537.118020@z14g2000cwz.googlegroups.com> Message-ID: shama.bell at gmail.com wrote: > Is it possible to join/append 2 arrays defined with different > typecodes? > > What typecode should i use to generate the following output. > > data1 = array('h', '\0', 6) > data2 = array('L', '\0', 25) > > for i in range( 6): > data1[0] = 0xFF > data2[1] = 0x00 > data1[2] = 0x00 > data1[3] = 0x00 > data1[4] = 0x00 > data1[5] = 0x00 > > for i in range( 2): > data2[0] = 0xF0F0F0F0 > data2[1] = 0xFFFFFFFF > > Output should be... > (0xFF 0x00 0x00 0x00 0x00 0x00 0xF0F0F0F0 0xFFFFFFFF) An arry has one typecode that applies to all its elements - so what you want can't be done. But you can use two lists and the module struct to create a string that resembles the memory layout you want. data1 = [0] * 6 data2 = [0L] * 25 struct.pack("b" * len(data1) + "l" * len(25), *(data1 + data2)) But I think you should give us more information on what you actually want to accomplish, as I've got the impression that you try to force things in awy that is not optimal. Diez From nid_oizo at yahoo.com_remove_the_ Wed Jun 15 18:06:22 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Wed, 15 Jun 2005 18:06:22 -0400 Subject: "also" to balance "else" ? In-Reply-To: References: Message-ID: Ron Adam wrote: > It occurred to me (a few weeks ago while trying to find the best way to > form a if-elif-else block, that on a very general level, an 'also' > statement might be useful. So I was wondering what others would think > of it. But the feature is already there: for x in : BLOCK1 if : ALSO-BLOCK break else: BLOCK2 If find "else" fine, since the only times I used it is in searches: for x in BLOCK1 if : break else: raise Exception('Not found') In that case, 'else' sounds like the good keyword. Regards, Nicolas From usenet.20.evilspam at spamgourmet.com Sun Jun 12 17:04:25 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 21:04:25 GMT Subject: How to get/set class attributes in Python In-Reply-To: <87k6kzgznf.fsf@hector.domek> References: <42ac6b5b$0$27173$626a14ce@news.free.fr> <87k6kzgznf.fsf@hector.domek> Message-ID: Peter Dembinski wrote: > Bruno Desthuilliers writes: > >>Nope. Python *is* typed. But it doesnt confuse implementation >>with semantic. > > > Python is typed. And its type system may look strange for anyone who > did only Java or C++ programming before :> Of course, in that Python is dynamically typed as opposed to the static typing of Java or C++. Please excuse my previous mis-wording :) Chris From martin.witte at gmail.com Wed Jun 8 15:16:15 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 8 Jun 2005 12:16:15 -0700 Subject: different time tuple format In-Reply-To: <42A707AC.9000405@i.com.ua> References: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> <1118239337.961657.242660@g49g2000cwa.googlegroups.com> <42A707AC.9000405@i.com.ua> Message-ID: <1118258175.128686.247400@g14g2000cwa.googlegroups.com> It is probably the best to calculate back to UTC. Assume "2005-06-07 15:07:12" the local time, then convert it as follows to UTC. Use the UTC time to store/manipulate/whatever you want to do. import time t = time.mktime(time.strptime("2005-06-07 15:07:12", "%Y-%m-%d %H:%M:%S")) print time.ctime(t) offset = time.timezone if time.daylight: offset = time.altzone t += offset print time.ctime(t) From gtog at _no___spam_myrealbox.com Wed Jun 22 04:34:29 2005 From: gtog at _no___spam_myrealbox.com (George) Date: Wed, 22 Jun 2005 10:34:29 +0200 Subject: Reading registry export files Message-ID: <42b92291$0$1334$5fc3050@dreader2.news.tiscali.nl> Hi, I have exported some registry-keys using Regedit to a number of .reg-files. I can open these files using any text editor. Now I wanted to write a simple Python script to concatenate all these files to one output file. (Please note that I'm a newbie). However, if I do something like: >>> f=open('c:/documents and settings/myname/desktop/test.reg','r') >>> r=f.read() >>> print r I get a lot of garbage with a lot characters which the Python shell cannot display (it display a square instead). The above code does work with ordinary text files. Should I open these reg-files in a different way, or treat them differently once read in Python? Thanks for any help. Kind regards, George From phark52 at yahoo.com Mon Jun 27 01:34:31 2005 From: phark52 at yahoo.com (fooooo) Date: 26 Jun 2005 22:34:31 -0700 Subject: Centering text in a wx.ListBox w/ wxPython Message-ID: <1119850471.692911.262850@g49g2000cwa.googlegroups.com> How do I center each item in the ListBox widget? Also, is it possible to change the color of the selected item? right now it uses the OSes color. I would like it to be consistant on every machine. From rkern at ucsd.edu Thu Jun 30 23:52:01 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 30 Jun 2005 20:52:01 -0700 Subject: How to run commands in command line from a script In-Reply-To: References: Message-ID: Ivan Shevanski wrote: > Alright well I'm quite a noob and when I run a simple command to change > the current directory, nothing happens. I made a little test script to > show it: > > import os > cwd = os.getcwd() > print cwd > os.system('cd = C:\Program Files') > print cwd > > then the result: > > C:\Python24\Python Scripts > C:\Python24\Python Scripts > > The cd never changed. . . Can somebody explain this? I think I need to > add something simple, i didnt quite get the example ' > os.system('./some --command') ' Read the documentation. os.system() opens up a new shell process. The command to change directories happens in that shell process, not python's process. Try another command. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rkern at ucsd.edu Sun Jun 12 19:49:25 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 12 Jun 2005 16:49:25 -0700 Subject: changing how instances are "created" In-Reply-To: <1118619382.878977.185960@g44g2000cwa.googlegroups.com> References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> <1118619382.878977.185960@g44g2000cwa.googlegroups.com> Message-ID: newseater wrote: > > Robert Kern wrote: > >>newseater wrote: >> >>>Hello. I need to be able to control how objects are created. Sometimes >>>when creating an object, i want to reuse another object instead. I've >>>searched for factory method implementations and singleton >>>implementations. They were too much of a hack! >>> >>>My first attempt of doing this was to play around with the __new__() >>>method. But i didn't quite succed. Then i came up with making a static >>>method which can create my instances or re-use other instances. >>>However, the below code I cannot get to work :( >>> >>>class Creator >>> def createInstance(cls, *args, **kwargs): >>> anewinstance = cls.__new__(cls, *args, **kwargs) >>> anewinstance.__init__(*args, **kwargs) >>> >>> return anewinstance >>> createInstance = staticmethod(createInstance) >> >>You want a classmethod, not a staticmethod. > > why do i want that? how should the code look like? currently the > objects fail to get initialized etc... A staticmethod does not take a cls argument. It is essentially just a function that is attached to a class. class Something(object): def foo(x, y, z): print x, y, z foo = staticmethod(foo) A classmethod does that a cls argument. class Creator(object): def createInstance(cls, *args, **kwds): pass createInstance = classmethod(createInstance) As for the desired content of the classmethod, I don't care to speculate. I usually just use the Borg pattern or a factory or any one of the Singleton implementations floating around. They are no more hacky than this, but they have the added benefit of working. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tjreedy at udel.edu Fri Jun 10 13:23:06 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 10 Jun 2005 13:23:06 -0400 Subject: Start application & continue after app exits References: <9G3qe.15862$TR5.692@news.edisontel.com> Message-ID: "Guy Lateur" wrote in message news:GXcqe.115625$Cx4.6765668 at phobos.telenet-ops.be... > To be honest, I don't really understand what it means to have the same > file open for writing by several processes. You don't want to modify data > which is already being modified by someone else, do you? I mean, how do > you determine what changes to apply first, and to what version? Or is the > file just constantly being overwritten on a first-come-first-served > basis? You have identified the reasons an operating system may not allow more than one process to open a file for writing. These are also a major issue with multiuser database systems and multiprogrammer source-code control systems. The overwrite problem exists even with unique access, since one open-write-close can be followed by another open-write-close containing edits based on reading the file before the intervening write, so that the update is to a now obsolete version. Various solutions include locks, checkouts, and conflict notifications. Terry J. Reedy From nm674674 at yahoo.com Wed Jun 15 13:05:20 2005 From: nm674674 at yahoo.com (nm674674 at yahoo.com) Date: 15 Jun 2005 10:05:20 -0700 Subject: Strange socket problem References: Message-ID: <1118855120.414719.247580@f14g2000cwb.googlegroups.com> Gurus, I am still doing my baby steps in the wonderful world of python (so far, so good). However, I am quite familiar with sockets. There is a socket option called SO_REUSEADDR that your server should call to fix this problem. From onurb at xiludom.gro Thu Jun 9 06:02:32 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 09 Jun 2005 12:02:32 +0200 Subject: Saving/retrieving user preferences In-Reply-To: <42a7e05c@dnews.tpgi.com.au> References: <42a78012@dnews.tpgi.com.au> <42a7e05c@dnews.tpgi.com.au> Message-ID: <42a813ba$0$5153$636a15ce@news.free.fr> Brian Wallis wrote: > This may be a FAQ,but I cannot find it. > > I want to save user preferences, window sizes, recently opened file names, > etc for a python application and I am looking for a package that does this > in a way that is portable across unix/linux and windows (and mac would be > nice as well). > > Is there a 'standard' package for doing this in python? http://docs.python.org/lib/module-ConfigParser.html HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aahz at pythoncraft.com Wed Jun 1 15:02:01 2005 From: aahz at pythoncraft.com (Aahz) Date: 1 Jun 2005 12:02:01 -0700 Subject: The need to put "self" in every method References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: [posted & e-mailed] In article , Piet van Oostrum wrote: > >There is. >Inside a method there are 3 kinds of identifiers: >- local ones e.g. parameters and local variables >- global ones (actually module-level) >- instance variables and methods > >Because Python has no declarations there must be a different way to >indicate in which category an identifier falls. For globals it is done with >the 'global' keyword (which actually is a declaration), for instance >variables the dot notation (object.name) is used and the rest is local. >Therefore every instance variable or instance method must be used with the >dot notation, including the ones that belong to the object `itself'. Python >has chosen that you can use any identifier to indicate the instance, and >then obviously you must name it somewhere. It could have chosen to use a >fixed name, like 'this' in Java or C++. It could even have chosen to use a >keyword 'local' to indicate local ones and let instance ones be the >default. But if instance variable would be implicit, local ones should have >been explicit. Any objection to swiping this for the FAQ? (Probably with some minor edits.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "The only problem with Microsoft is they just have no taste." --Steve Jobs From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 7 15:20:11 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 07 Jun 2005 21:20:11 +0200 Subject: split up a list by condition? In-Reply-To: References: <3gjpk0FcrnknU1@individual.net> Message-ID: <3gmabbFd6jmpU2@individual.net> Duncan Booth wrote: > Reinhold Birkenfeld wrote: > >> Hi, >> >> while writing my solution for "The python way?", I came across this >> fragment: >> >> vees = [c for c in wlist[::-1] if c in vocals] >> cons = [c for c in wlist[::-1] if c not in vocals] >> >> So I think: Have I overlooked a function which splits up a sequence >> into two, based on a condition? Such as >> >> vees, cons = split(wlist[::-1], lambda c: c in vocals) >> >> Reinhold > > If you really are being charged by the number of newline characters in your > code you could write: [...] > but every penny you save writing a one liner will be tuppence extra on > maintenance. This is clear. I actually wanted to know if there is a function which I overlooked which does that, which wouldn't be a maintenance nightmare at all. Reinhold From deets at web.de Mon Jun 20 15:55:25 2005 From: deets at web.de (Diez B. Roggisch) Date: Mon, 20 Jun 2005 21:55:25 +0200 Subject: Embedded Systems Python? In-Reply-To: <11bdnto1au02i63@corp.supernews.com> References: <11bdnto1au02i63@corp.supernews.com> Message-ID: <3hol9dFi5e6lU2@uni-berlin.de> Dennis Clark wrote: > I'm a bit of a newb when it comes to Python, is there anyone with experience > compiling it on Linux platforms that can offer me pointers to try this out > myself? Seatch for cross-compiling python patches. I'm working on an XScale255 platform with python2.2 and soon 2.3 - no trouble there. Diez From harold.fellermann at upf.edu Mon Jun 13 10:36:36 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 13 Jun 2005 16:36:36 +0200 Subject: Controlling assignation In-Reply-To: References: Message-ID: <73cd19a37027b3d16c44d04ea560ee32@upf.edu> On 13.06.2005, at 15:52, Xavier D?coret wrote: > I would like to know if there is for python's classes an equivalent of > the operator= that can be overidden. > > Let's say I have >>>> a=A() > and I want to write >>>> a=5 > and I want this to change some internal value of a instead of making a > point to a new object (an int 5) > > In other word, I would like to be able to use a=5 instead of a.set(5) > > Is that possible? the short answer is: no. the long answer: if you write >>> a=A() an instance of class A is created and bound to the local identifier 'a'. If you later write >>> a=5 the object 5 is reassigned to the same identifier, deleting whatever value was stored there before. The identifier itself does not impose any restrictions on the type of instances that can be bound to it. Binding an instance of class A in the first part, does not make the identifier of the kind 'can-only-bind-A-instances'. In other words: identifiers don't have types. Thus, there is no mechanism that allows to change the binding behavior of identifiers. As a general advise, don't try to write C++ in python. I think, for most cases, there are far better solutions than changing the assign operator anyway... explicit is better than implicit: If class A has only one dedicate value and no internal state, make it a construcotr call: >>> a=A(5) Otherwise, it is worth mentioning the name of the member to set. IMHO this increases the readability of your source code: >>> a.pressure=5 Cheers, - harold - -- "I was born not knowing and have had only a little time to change that here and there." -- Richard Feynman From has.temp2 at virgin.net Wed Jun 1 05:26:44 2005 From: has.temp2 at virgin.net (has) Date: 1 Jun 2005 02:26:44 -0700 Subject: scripting browsers from Python In-Reply-To: References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> Message-ID: <1117618004.058509.244530@o13g2000cwo.googlegroups.com> Simon Brunning wrote: > On 31 May 2005 00:52:33 -0700, Michele Simionato > wrote: > > I would like to know what is available for scripting browsers from > > Python. > > I don't know of anything cross platform, or even cross browser, but on > Windows, IE can be automated via COM On OS X you can use appscript , either directly via the application's scripting interface if it has one or indirectly by manipulating its GUI via GUI Scripting. HTH From gene.tani at gmail.com Mon Jun 6 22:54:47 2005 From: gene.tani at gmail.com (gene tani) Date: 6 Jun 2005 19:54:47 -0700 Subject: Question about Object Oriented + functions/global vars? In-Reply-To: <1118074376.475660.183950@g44g2000cwa.googlegroups.com> References: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> <1118074376.475660.183950@g44g2000cwa.googlegroups.com> Message-ID: <1118112887.825446.78870@g14g2000cwa.googlegroups.com> #include canonical design pattern advice longjmp(Borders or other_big_chain_bookstore) opt1=fopen("Oreilly's Head first design pattern","r") opt2=fopen("design patterns book by Shalloway and trott (i think that's their names)","r") another=poll("any other intro to DP books that people like?") From flupke at nonexistingdomain.com Tue Jun 7 04:24:35 2005 From: flupke at nonexistingdomain.com (flupke) Date: Tue, 07 Jun 2005 08:24:35 GMT Subject: poker card game revisited (code included) Message-ID: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> Hi, i've included the code so people can take a look. I've tried to expand on the thread of 26/05/2005 on "Checking for a full house". Code is suboptimal as I coded it rather quickly. I've added the "normal" classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere "straight" detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like "deuces wild", what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen ===================== CODE ===================== """ Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger """ import random class Card(object): """ Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace """ suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] rankList = [ "narf", "narf", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, suit=0, rank=0): """ Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) """ self.suit = suit self.rank = rank def __str__(self): """ Pretty print a card """ return self.rankList[self.rank] + " of " + self.suitList[self.suit] def __cmp__(self, other): """ Compare 2 cards @type other: card @param other: the card to compare with """ # check the suits if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 # suits are the same... check ranks if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): """ Represents a deck of cards. We can have different decks of cards """ DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): """ Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) """ self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): """ Pretty print the deck """ for card in self.cards: print card def __str__(self): """ Pretty print the deck """ s = "" for i in range(len(self.cards)): s = s + " "*i + str(self.cards[i]) + "\n" return s def sort(self,rank=True,suit=False): """ Sort the deck """ def sortonrank(x,y): if x.rank > y.rank: return 1 if x.rank < y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit > y.suit: return 1 if x.suit < y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): """ Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle """ import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print " shuffle %s " % shuffle for i in range(nCards): j = random.randrange(i, nCards) [self.cards[i], self.cards[j]] = [self.cards[j], self.cards[i]] def removecard(self, card): """ Removes a card from the deck. Do not use this function if you want to keep playing with the same deck afterwards! @type card: card @param card: card you want to remove """ if card in self.cards: self.cards.remove(card) return 1 else: return 0 def removecardindex(self,index): """ Remove a card at the given index. You get the card so you can return it to the deck later """ if ( index >= 0 and index <= len(self) ): return self.cards.pop(index) def addcard(self,card): """ Add the card back to the bottom of the deck @type card: card @param card: card you want to add to the deck """ self.cards.append(card) def popcard(self): """ Get the top card and deal it """ return self.cards.pop() def isempty(self): """ Is the deck empty? """ return (len(self.cards) == 0) def deal(self, hands, ncards=999): """ Deal a number of cards to the hands. ncards are dealt to each hand. @type hands: list @param hands: list of hands to deal to @type ncards: int @param ncards: number of cards to deal to each hand """ nhands = len(hands) for hand in hands: for i in range(ncards): if self.isempty(): break # break if out of cards card = self.popcard() # take the top card # hand = hands[i % nhands] # whose turn is next? hand.addcard(card) # add the card to the hand # print " deal card %s to %s " % (card,hand) def __len__(self): """ How many cards are there in the deck? """ return len(self.cards) class Hand(Deck): """ A hand is a kind of deck that contains cards """ def __init__(self, name=""): """ Make a hand of cards @type name: string @param name: hand belongs to person with this name """ self.cards = [] self.name = name """ def addcard(self,card) : self.cards.append(card) """ def __str__(self): """ Pretty print the hand """ s = "Hand " + self.name if self.isempty(): s = s + " is empty\n" else: s = s + " contains\n" return s + Deck.__str__(self) class CardGame(object): """ A card game """ def __init__(self): """ Start a card game by taking a deck of cards and shuffling it """ self.deck = Deck() self.deck.shuffle() class Rank(object): def __init__(self,rnk,name): self.rnk = rnk self.name = name def __str__(self): return self.name class HandComparator(object): pass class HandEvaluator(object): RANK_NOTHING = Rank(1,"High card") RANK_PAIR = Rank(2,"Pair") RANK_DOUBLEPAIR = Rank(3,"Double Pair") RANK_THREEOFAKIND = Rank(4,"Three of a Kind") RANK_STRAIGHT = Rank(5,"Straight") RANK_FLUSH = Rank(6,"Flush") RANK_FULLHOUSE = Rank(7,"Full House") RANK_FOUROFAKIND = Rank(8,"Four of a Kind") RANK_STRAIGHTFLUSH = Rank(9,"Straight Flush") RANK_FIVEOFAKIND = Rank(10,"Five of a Kind") def __init__(self): print "Ready to evaluate hands" def is_straight(self,hand,numwildcards=0): """Checks for a five card straight Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games). Outputs: highest card in a five card straight or 0 if not a straight. Original list is not mutated. Ace can also be a low card (i.e. A2345). >>> is_straight([14,2,3,4,5]) 5 >>> is_straight([14,2,3,4,6]) 0 >>> is_straight([10,11,12,13,14]) 14 >>> is_straight([2,3,5], 2) 6 >>> is_straight([], 5) 14 >>> is_straight([2,4,6,8,10], 3) 12 >>> is_straight([2,4,4,5,5], 2) 6 """ hand = set(hand) if 14 in hand: hand.add(1) for low in (10,9,8,7,6,5,4,3,2,1): needed = set(range(low, low+5)) if len(needed & hand) + numwildcards >= 5: lhand = [x for x in hand] ind = lhand.index(low+4) str = lhand[ind-4:ind+1] return low+4 return -1 def is_group(self,hand,numwildcards=0): """Checks for pairs, threes-of-kind, fours-of-a-kind, and fives-of-a-kind Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games) Output: tuple with counts for each value (high cards first) for example (3, 14), (2, 11) full-house Aces over Jacks for example (2, 9), (2, 7) two-pair Nines and Sevens Maximum count is limited to five (there is no seven of a kind). Original list is not mutated. >>> groups([11,14,11,14,14]) [(3, 14), (2, 11)] >>> groups([7, 9, 10, 9, 7]) [(2, 9), (2, 7)] >>> groups([11,14,11,14], 1) [(3, 14), (2, 11)] >>> groups([9,9,9,9,8], 2) [(5, 9), (2, 8)] >>> groups([], 7) [(5, 14), (2, 13)] """ result = [] counts = [(hand.count(v), v) for v in range(2,15)] for count, value in sorted(counts, reverse=True): newcount = min(5, count + numwildcards) # Add wildcards upto five numwildcards -= newcount - count # Wildcards remaining if newcount > 1: result.append((newcount, value)) return result def is_flush(self,hand,numwildcards=0): result = [] counts = [(hand.count(v), v) for v in range(0,4)] for count, suit in sorted(counts, reverse=True): newcount = min(5, count + numwildcards) # Add wildcards upto five numwildcards -= newcount - count # Wildcards remaining if newcount >= 5: # we have a flush, return the flush suit # result.append((newcount, value)) return suit return -1 def is_straightflush(self,hand,numwildcards=0): return -1 def getrank(self,hand,numwildcards=0): result_group = None result_straight = None result_flush = None result_sf = None nrofresult = 0 rank = None cardranks = [card.rank for card in hand.cards] cardsuits = [card.suit for card in hand.cards] # check for groups result_group = self.is_group(cardranks,numwildcards) rank = self.__rankgroup(result_group) # if rank is lower than a four of a kind, a straight flush is # still better """ if (rank[0] < HandEvaluator.RANK_FIVEOFAKIND): result_sf = is_straightflush(hand """ # if rank is lower than a fullhouse, a flush might be higher if (rank[0] < HandEvaluator.RANK_FULLHOUSE): result_flush = self.is_flush(cardsuits,numwildcards) if ( result_flush > -1 ): return self.__rankflush(result_flush) # if rank is lower than a straight, it's useful to check for a # straight if (rank[0] < HandEvaluator.RANK_STRAIGHT): result_straight = self.is_straight(cardranks,numwildcards) if ( result_straight > -1 ): return self.__rankstraight(result_straight) # return the rank return rank def __namerank(self,rank): return Card.rankList[rank] def __namesuit(self,suit): return Card.suitList[suit] def __rankgroup(self,group): pair = 0 trips = 0 ranks = [] if (len(group) == 0 ): return (HandEvaluator.RANK_NOTHING,ranks) for count,rank in group: ranks.append(self.__namerank(rank)) if ( count >= 5 ): return (HandEvaluator.RANK_FIVEOFAKIND,ranks) elif ( count == 4 ): return (HandEvaluator.RANK_FOUROFAKIND,ranks) elif ( count == 3 ): trips += 1 elif ( count == 2 ): # can lead to a double pair # check to see if we have a next pair pair += 1 # Full house? if ( trips >= 2 ): return (HandEvaluator.RANK_FULLHOUSE,ranks) if ( trips == 1 and pair >= 1 ): return (HandEvaluator.RANK_FULLHOUSE,ranks) # Trips if ( trips >= 1 ): return (HandEvaluator.RANK_THREEOFAKIND,ranks) # Check for a pair or a double pair if ( pair >= 2 ): return (HandEvaluator.RANK_DOUBLEPAIR,ranks) elif ( pair == 1 ): return (HandEvaluator.RANK_PAIR,ranks) def __rankflush(self,suit): ranks = [] ranks.append(self.__namesuit(suit)) return (HandEvaluator.RANK_FLUSH,ranks) def __rankstraight(self,highcard): ranks = [] ranks.append(self.__namerank(highcard)) return (HandEvaluator.RANK_STRAIGHT,ranks) def getprintablerank(self,handeval): rank = handeval[0] cards = handeval[1] what = "" if ( rank == HandEvaluator.RANK_PAIR or rank == HandEvaluator.RANK_THREEOFAKIND or rank == HandEvaluator.RANK_FOUROFAKIND or rank == HandEvaluator.RANK_FIVEOFAKIND ): what = "%s of %s's " % (rank, cards[0]) elif ( rank == HandEvaluator.RANK_FULLHOUSE ): what = "%s, %s's over %s's" % (rank, cards[0], cards[1]) elif ( rank == HandEvaluator.RANK_DOUBLEPAIR ): what = "%s, %s's and %s's" % (rank, cards[0], cards[1]) elif ( rank == HandEvaluator.RANK_NOTHING ): what = "%s" % rank elif ( rank == HandEvaluator.RANK_STRAIGHT ): what = "%s, %s high" % (rank,cards[0]) elif ( rank == HandEvaluator.RANK_FLUSH ): what = "%s of %s" % (rank,cards[0]) return what if __name__ == "__main__": # Deal to 5 players, first 3 cards, then 1 and another 3 todeal = [] for hnd in range(0,5): todeal.append(Hand("Player %s" % (hnd + 1) )) d = Deck() d.shuffle(3) print " Dealing 2 cards to all players " d.deal(todeal,3) print " Dealing 1 cards to all players " d.deal(todeal,1) print " Dealing 2 cards to all players " d.deal(todeal,3) print " What are the hands of the players " ev = HandEvaluator() for hand in todeal: print "%s" % hand rank = ev.getrank(hand) print "%s" % ev.getprintablerank(rank) print "*"*40 print " What's left in the deck?" print "%s" % d print " %s cards left in the deck " % len(d) From tim.golden at viacom-outdoor.co.uk Tue Jun 14 04:20:10 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Jun 2005 09:20:10 +0100 Subject: windows directory Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8CB@vogbs009.gb.vo.local> [Austin] | I would like to write a program which creates the folders in specific | directory. | For example, I want to create folder in Program Files. How do | I know which | is in C:\ or D:\ | Is there any function to get the active path? It's not quite clear what you mean. You seem to be asking three possibly distinct questions: 1) How do I create folders in a particular directory. A. Look at os.mkdir or os.makedirs 2) How do I know where the "Program Files" folder is? A. Look at the shell module of the pywin32 extensions. Specifically, you're looking for the shell.SHGetPathFromIDList and shell.SHGetSpecialFolderLocation functions. 3) How do I know what the active path is? A. Look at os.getcwd I know I haven't been too detailed in my answers, but I didn't want to spend lots of time explaining in case I'd actually missed the point of the question. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From lycka at carmen.se Wed Jun 8 04:43:29 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 08 Jun 2005 10:43:29 +0200 Subject: optparse.py: FutureWarning error In-Reply-To: References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > This should REALLY be on the doc page of the Python site. Agreed. > It is really time to stop pretending that the only Python users > that count have a *nix on their desk. I agree with this too, but if you're a programmer on the Windows platform with possibility to install software on the machine you work with, I strongly suggest that you install cygwin or something equivalent. Not just for "man python". Tools like grep and find are vastly superior to anything I've seen natively on windows if you want to process the data you find in some automated way. In my experience, Windows 2000 and later are fairly decent operating systems if you have Python and cygwin installed, but I'd feel awfully handicapped without those tools. From michele.simionato at gmail.com Thu Jun 16 01:01:48 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 Jun 2005 22:01:48 -0700 Subject: dynamic In-Reply-To: References: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> Message-ID: <1118898108.786914.164590@g44g2000cwa.googlegroups.com> Yes, factory methods, exactly. If I had a base class ImageReader with children JpegReader and TIFFReader, I will probably add two factory methods ImageReader.makeJpegReader and ImageReader.makeTIFFReader, I will not override ImageReader.__new__ to return sometimes JpegReader instances and sometimes TIFFReader instances. Explicit is better than implicit and all that. Michele Simionato From listserver at tdw.net Fri Jun 17 10:02:22 2005 From: listserver at tdw.net (Tim Williams) Date: Fri, 17 Jun 2005 15:02:22 +0100 Subject: Python & firewall control (Win32) References: <011101c57338$fcb5e8b0$ccbefea9@twilliams> Message-ID: <012401c57345$2f46e480$ccbefea9@twilliams> > ----- Original Message ----- > From: "Tom Anderson" > > > > > AIUI, you won't be stopping and restarting ipfw - the ipfw command just > > modifies the ruleset being used by a continuously-running instance of the > > ipfw kernel module or daemon or whatever. How long it takes from starting > > the os.system call to the changes taking effect in the firewall, though, i > > have no idea - it might not be fast enough for you. I'd be surprised if it > > was more than a few hundred milliseconds, though, and really ought to be > > much, much faster than that. > > Thanks Tom Again, I will give it a go and post back with my findings re: http://wipfw.sourceforge.net/?page=home Tom, this looks good. I had it downloaded, installed and running some custom rules in under 5 minutes. Very simple and straightforward. > AIUI, you won't be stopping and restarting ipfw This is correct, the service doesn't appear to restart, the rule updates are actioned very quickly (instantaneous) I haven't had chance to try it integrated into a Python app, but it looks very promising,. Thanks again From thomasbartkus at comcast.net Wed Jun 29 16:35:17 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 29 Jun 2005 15:35:17 -0500 Subject: Boss wants me to program References: Message-ID: "phil" wrote in message news:mailman.1070.1120060456.10512.python-list at python.org... > > > About teaching in the exact sciences: I think we need a more hands-on > > applied approach, to some extent this holds for the entire school > > system. > > YES! As a geometry(& trig) teacher, I am going to have them build a > shed, a kite, a sundial. I would love some doable ideas for hands > on which would teach more principles without being major > construction projects. > Wow! How about a sextant? Simple device really. And a great practical demonstration of trigonometry. It would be helpful of if your class was near the seashore. You would want a clear shot at the horizon. Thomas Bartkus From kent37 at tds.net Fri Jun 3 21:15:13 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Jun 2005 21:15:13 -0400 Subject: optparse.py: FutureWarning error In-Reply-To: References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> <42a02aba$1_3@newspeer2.tds.net> Message-ID: <42a10066$1_1@newspeer2.tds.net> Terry Reedy wrote: > "Kent Johnson" wrote in message > news:42a02aba$1_3 at newspeer2.tds.net... > >>Terry Reedy wrote: >> >>>"kosuke" wrote in message >>>news:1117765604.103092.154190 at g47g2000cwa.googlegroups.com... >>> >>> >>>>man python --- >>>> >>>>COMMAND LINE OPTIONS >>> >>> >>>This should REALLY be on the doc page of the Python site. >> >>Hear, hear! I never even knew this existed! >> >>Where should it go in the docs? In the Language Reference or the Tutorial >>or...? > > > Since the Tutorial already has section 2. Using the Python Interpreter that > discusses a few of the switches, I would add it as an appendix with a > reference to the appendix at the end of the appropriate subsection. > Perhaps I will submit a tracker item. Sounds good to me. Kent From max at alcyone.com Tue Jun 28 23:12:09 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 28 Jun 2005 20:12:09 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> Message-ID: Mike Holmans wrote: > My wife's an Okie, but she speaks the US equivalent of RP - the one > used by newsreaders on the main terrestrial TV networks and which is > commonly thought to be used mostly in Ohio and other places just south > of the Great Lakes. If there's such a thing as a standard "American > accent", that's it. It neither sounds dumb nor clever - just American. The linguistic term for that accent, by the way, is General American. > The problem which a lot of fairly-midstream American accent users face > is that it's the same sort of thing which Brits try and imitate when > they want to suggest a snake-oil salesman. And due to overcorrection, typically do a really bad job of it :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis If I had never met you / Surely I'd be someone else -- Anggun From steve at REMOVETHIScyber.com.au Wed Jun 22 21:25:59 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 23 Jun 2005 11:25:59 +1000 Subject: how to use more than 1 __init__ constructor in a class ? References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: On Wed, 22 Jun 2005 12:34:21 -0500, Rocco Moretti wrote: > scott wrote: >> hi people, >> >> can someone tell me, how to use a class like that* (or "simulate" more >> than 1 constructor) : >> #-- [snip] > You could also turn __init__ into a dispatch fuction: > > #-- > class myPointClass: > def __init__(self, *args): > if len(args) <= 2: > self.__init_two(*args) > if len(args) == 3: > self.__init_three(*args) Oh wow, so that's what I've been doing for years. Dispatching. And I thought I was just calling other functions :-) That's the joys of a mostly self-taught programming knowledge: you miss out on all the buzzwords. -- Steven. From rkern at ucsd.edu Wed Jun 1 23:32:28 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 01 Jun 2005 20:32:28 -0700 Subject: Beginner question: Logs? In-Reply-To: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> Message-ID: Svens wrote: > Hey everyone! I'm a math student working on a short script involving > logs. I have a function on my scientific calculator, and was wondering > if there was a similar funtion in python. > > For example: > > (log65536)/(log4)= 8 > > I've searched around a bit and haven't been able to find anything. import math -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kent37 at tds.net Thu Jun 9 14:19:45 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Jun 2005 14:19:45 -0400 Subject: Changing entities In-Reply-To: <1118340567.897351.259050@z14g2000cwz.googlegroups.com> References: <1118235783.224018.281490@g44g2000cwa.googlegroups.com> <42a6ed6e$1_1@newspeer2.tds.net> <1118340567.897351.259050@z14g2000cwz.googlegroups.com> Message-ID: <42a887e9$1_2@newspeer2.tds.net> Daniel wrote: > I need match a regular expression, change it erasing the other strings > after this. Just like: > > a = "I'm going send to out of space, find another race" > > And I want to match "space" instance, and erase the other. If you mean you want to get rid of everything after 'space', this will do it: >>> import re >>> a = "I'm going send to out of space, find another race" >>> re.sub('space.*', 'space', a) "I'm going send to out of space" You should read this and learn to make your own regexes: http://www.amk.ca/python/howto/regex/ Kent From gsakkis at rutgers.edu Thu Jun 9 01:59:29 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 8 Jun 2005 22:59:29 -0700 Subject: Abstract and concrete syntax References: <3gpv0uFdqbi5U1@individual.net> Message-ID: <1118296769.780810.163360@g14g2000cwa.googlegroups.com> "Greg Ewing" wrote: > > More generally, I think there is no abstract distinction between > > statements and expressions. Everything is an expression, can be evaluated > > to a value. > > That's true in a functional language, but Python is not a > functional language. In imperative programming, often you just > do something for its side effect, and there's no obvious value > to return. Forcing everything to return a value just for the > sake of conceptual purity is an artificiality, in my view. Well, I guess what makes an artificiality is subjective then, because IMO the distinction between expressions and statements is a bigger artificiality. Python already uses a default value (None) to return from a callable, so what makes statements special ? Certainly not the side effects, as the two equivalent ways to set an attribute show: a.x = val # statement setattr(a,'x',val) # expression George From deets at web.de Sun Jun 5 10:34:40 2005 From: deets at web.de (Diez B. Roggisch) Date: Sun, 05 Jun 2005 16:34:40 +0200 Subject: XML help In-Reply-To: References: Message-ID: > > I've managed to test for specific elements and extract values. I want to > place the reults in arrays with array index equal to element ID. So as I > walk the tree I temporarily store IDs and DeptValues in lists. I'm ok so > far. I then intend to create an array of size determined by the maximum > value of ID. So in the sample above the array size will be 8 even though > only three entries exist. That sounds wrong. If what you want is a mapping between keys (your IDs) and values, you need to use a dcitionary. Like this: mapping[myid] = value > > At this point I'm stuck because I want to do this latter array creation and > processing when I "see" the /Block end of block tag. However I can't figure > out how to do that. Obviously I'm not understanding something about XML DOM > trees and Elements because when I try to print all elements I never see an > end tag for any. I'm obviously approaching this from a readline and process > point of view which is probably half the problem. Your misunderstanding the nature of nodes in dom: a node in dom _is_ the start and end-tag. If you have a dom-tree that you serialize, a node in there will either be serialized as if it has no childs, or as ... if it has childs. So the other way round, for a well-formed xml document parsed to a dom, you end up with one node for all pairs of opening/closing tags. If a end-tag is what you're after, you migth want to look into the event-driven XML api, SAX. But then you'll have other tradeoffs compared to dom': all statekeeping has to be done by yourself. It's up to you to chose. Regards, Diez From future_retro at yahoo.co.uk Thu Jun 23 11:08:11 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 23 Jun 2005 08:08:11 -0700 Subject: python create WMI instances In-Reply-To: <1119536561.777787.59510@g47g2000cwa.googlegroups.com> References: <1119536561.777787.59510@g47g2000cwa.googlegroups.com> Message-ID: <1119539291.255326.312050@g44g2000cwa.googlegroups.com> Heres a script for creating printer ports import win32com.client WBEM = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" + "." + r"\root\cimv2") printer = WBEM.Get("Win32_Printer").SpawnInstance_() printer.Properties_('DeviceID').Value = 'myprinter' printer.Properties_('DriverName').Value = 'HP 2000C' printer.Properties_('Location').Value = 'myoffice' printer.Properties_('Network').Value = 'True' printer.Properties_('Shared').Value = 'True' printer.Properties_('ShareName').Value = 'myprintershare' printer.Properties_('PortName').Value = 'IP_169.254.110.14' printer.Put_() From Scott.Daniels at Acm.Org Tue Jun 14 10:09:39 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 14 Jun 2005 07:09:39 -0700 Subject: implicit variable declaration and access In-Reply-To: References: Message-ID: <42aeddf7$1@nntp0.pdx.net> Tom Anderson wrote: > ... If it's not, try: > x = "myVarName" > y = "myVarValue" > locals()[x] = y Sorry, this works with globals(), but not with locals(). There isn't a simple way to fiddle the locals (the number is determined when the function is built). I do, however, agree with you about what to use. I use: class Data(object): def __init__(self, **kwargs): for name, value in kwargs.iteritems(): setattr(self, name, value) def __repr__(self): return '%s(%s)' % (type(self).__name__, ', '.join( ['%s=%r' % (name, getattr(self, name)) for name in dir(self) if name[0] != '_'])) When I want to fiddle with named values. el = Data(a=5, b='3') el.c = el.a + float(el.b) setattr(el, 'other', getattr(el, 'a') + getattr(el, 'c')) el --Scott David Daniels Scott.Daniels at Acm.Org From tim.golden at viacom-outdoor.co.uk Wed Jun 1 09:48:28 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 1 Jun 2005 14:48:28 +0100 Subject: Monitoring a USB-drive / Card-reader using python? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB87D@vogbs009.gb.vo.local> [Thomas W] | I want to monitor a given USB-device, like a Memory Card-reader, and | when a memory card is inserted I want to move the data on the | card to a | different location on the filesystem ( or do something else with the | files). | | Does anybody know how to do this ( on Linux and/or windows ) | or if it's | even do-able ? It can be done on Windows using the WM_DEVICECHANGE I'll try to hunt out some code... OK, it's a bit long, but if you Google this group for "wm_devicechange" you'll find some code I posted which works for USB sticks and CD-ROMs. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From dstanek at dstanek.com Fri Jun 3 17:02:25 2005 From: dstanek at dstanek.com (dstanek at dstanek.com) Date: Fri, 3 Jun 2005 17:02:25 -0400 (EDT) Subject: Python interest group software In-Reply-To: <17056.50461.644952.876939@montanaro.dyndns.org> References: <20050603204724.GB8195@goliath.ag.com> <17056.50461.644952.876939@montanaro.dyndns.org> Message-ID: <33626.207.58.192.150.1117832545.squirrel@207.58.192.150> > > David> Is there already any software out there to manage a Python > David> Interest Group? Something that can register users, take RSVPs > for > David> meetings, etc. > > I suspect a fair number take advantage of meetup.com. > > Skip > > The original group did use meetup.com. I'm not too fond of them charging a monthly fee for their service. If something suitable does not exists I can always write it in Python! David From nephish at xit.net Thu Jun 30 03:00:42 2005 From: nephish at xit.net (nephish) Date: Thu, 30 Jun 2005 00:00:42 -0700 Subject: some trouble with MySQLdb Message-ID: <42C3989A.8010008@xit.net> Hey there all, i have a question about how to point my python install to my sql database. when i enter this: db = MySQLdb.connect(user="user", passwd="pass", db="myDB") i get this: Traceback (most recent call last): File "", line 1, in -toplevel- db = MySQLdb.connect(user="user", passwd="pass", db="MyDB") File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66, in Connect return Connection(*args, **kwargs) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 134, in __init__ super(Connection, self).__init__(*args, **kwargs2) OperationalError: (1049, "Unknown database 'MyDB'") i am using the all in one package from lampp (now xampp) and i have tested a couple of python scripts from the cgi, but.... nothing that connects to the database. any ideas? thanks From Scott.Daniels at Acm.Org Wed Jun 22 12:07:16 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Jun 2005 09:07:16 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <11bh7ffsps4ea3@corp.supernews.com> References: <11bh7ffsps4ea3@corp.supernews.com> Message-ID: <42b9854e$1@nntp0.pdx.net> Grant Edwards wrote: > I finally figured out why one of my apps sometimes fails under > Win32 when it always works fine under Linux: Under Win32, the > pickle module only works with a subset of floating point > values. In particular the if you try to dump/load an infinity > or nan value, the load operation chokes: There is no completely portable way to do this. Any single platform can have a solution, but (since the C standards don't address how NaNs and Infs are represented) there is not a good portable way to do the pickle / unpickle. It is nice the exception is raised, since at one point it was not (and a simple 1.0 was returned). See explanations in article 654866: http://sourceforge.net/tracker/index.php?func=detail&aid=714733&group_id=5470&atid=105470 > $ python pickletest.py > Traceback (most recent call last): ... > File "C:\PYTHON23\lib\pickle.py", line 968, in load_float > self.append(float(self.readline()[:-1])) > ValueError: invalid literal for float(): 1.#INF > I realize that this is probably due to underlying brokenness in > the Win32 libc implimentation, but should the pickle module > hide such platform-dependancies from the user? As mentioned above, there is no C standard-accessible way to predictably build or represent NaNs, negative zeroes, or Infinities. > [NaN and Infinity are prefectly valid (and extremely useful) > floating point values, and not using them would require huge > complexity increases in my apps (not using them would probably > at least triple the amount of code required in some cases).] You could check to see if the Python 2.5 pickling does a better job. Otherwise, you've got your work cut out for you. -Scott David Daniels Scott.Daniels at Acm.Org From roberson at ibd.nrc-cnrc.gc.ca Mon Jun 20 03:33:48 2005 From: roberson at ibd.nrc-cnrc.gc.ca (Walter Roberson) Date: 20 Jun 2005 07:33:48 GMT Subject: references/addrresses in imperative languages References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: In article <1119220461.626477.56110 at g49g2000cwa.googlegroups.com>, Xah Lee wrote: >In hindsight analysis, such language behavior forces the programer to >fuse mathematical or algorithmic ideas with implementation details. A >easy way to see this, is to ask yourself: how come in mathematics >there's no such thing as "addresses/pointers/references". There is. Each variable in predicate calculas is a reference. No matter how large the formulae, a change in a variable is, in mathematics, immediately propagated to all occurances of the variable (potentially changing the references of other variables). If the predicate calculas variables were not equivilent to references, then the use of the variable in a formula would have to be a non-propogating copy. and a change to the original value whence not be reflected in all parts of the formula and would not change what the other variables referenced. Consider for example the proof of Goedel's Incompleteness theorem, which involves constructing a formula with a free variable, and constructing the numeric encoding of that formula, and then substituting the numeric encoding in as the value of the free variable, thus ending up with a number that is "talking about" iteelf. The process of the proof is *definitely* one of "reference" to a value in the earlier stages, with the formula being "evaluated" at a later point -- very much like compiling a program and then feeding the compiled program as input to itelf. You cannot do it without a reference, because you need to have the entire number available as data at the time you start evaluating the mathematical formula. -- Ceci, ce n'est pas une id?e. From jeremy+complangpython at jeremysanders.net Thu Jun 23 13:17:01 2005 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Thu, 23 Jun 2005 18:17:01 +0100 Subject: User interfaces in console (dialog like) References: <2fdabf19.0506230445.249d063f@posting.google.com> Message-ID: Negroup wrote: > Do you guys know an alternative that fits my needings without moving > from Python? Turbo Vision in dos used to be really good. There's a python binding to the free version here: http://tvision.sourceforge.net/ (I haven't tried it) -- Jeremy Sanders http://www.jeremysanders.net/ From david.bear at asu.edu Mon Jun 27 17:24:26 2005 From: david.bear at asu.edu (David Bear) Date: Mon, 27 Jun 2005 14:24:26 -0700 Subject: rsync protocol in python Message-ID: <4046073.1XfbebpUv1@teancum> I was wondering if anyone has implemented the rsync protocol in python. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From renting at astron.nl Tue Jun 28 05:47:02 2005 From: renting at astron.nl (Adriaan Renting) Date: Tue, 28 Jun 2005 11:47:02 +0200 Subject: Boss wants me to program Message-ID: Visual Basic is a good option for small programs on Windows. It does cost a lot of money depending on your needs. It's not a good choice for large programs (or at least used to be). The older versions of VC++ are very hard and difficult, the newer versions seem to be o.k. I used to prefer Borland C++Builder for large Windows projects. Both Java and C++ are very complex languages, they wouldn't be my first choice to learn programming basics. Python is especially nice if you are using Some Unix environment. I like how it interoperates with Qt for designing user interfaces. It's free too, but for Windows you might need to wait for Qt version 4 to be able to create User Interfaces o Windows. I like the Eric3 program to develop my applications. As to the actual programming: Writing the documentation, helpfiles and maintaining the application is what will take most of the time, not the actual writing itself. Here are some sites that might have some useful hints for creating easy to use applications: "http://www.webpagesthatsuck.com/mysterymeatnavigation.html" "http://www.nngroup.com/" "http://www.rha.com/ui_hall_of_shame.htm" "http://digilander.libero.it/chiediloapippo/Engineering/iarchitect/shame.htm" "http://www.pixelcentric.net/x-shame/" "http://www.joelonsoftware.com/articles/Wrong.html" Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> Cyril BAZIN 06/28/05 11:25 AM >>> Hello, If you have enough money to buy a licence, Visual Basic seem a very good option. (But you should learn how to use design patterns.) Without knowing this language I was able to perform a graphical user interface to interact with an automat, a mySQL database and many analogical sensors in less than 1 month. Cyril On 27 Jun 2005 11:51:21 -0700, xeys_00 at yahoo.com wrote: > > I'm a manager where I work(one of the cogs in a food service company). > The boss needed one of us to become the "tech guy", and part of that is > writing small windows programs for the office. He wants the development > work done in house, and he knows I am in school for a CS minor. I know > basic C++(Part 2 of that is in the fall), and I will be taking Java 1 > in the fall also. What is the easiest way for me to make windows > programs that will do basic things like(Inventory, Menu Management, > etc...)? I have heard visual basic is where it's at. I want to keep an > open mind though, so I am wondering if python could be an option. The > programs have > no speed requirement. But they must be pretty, and not confuse my > boss. Plus he wants well documented help for each function. I asked the > windows programming group, but I thought I would ask here also. Thanks. > > Xeys > > -- > http://mail.python.org/mailman/listinfo/python-list > From tzot at sil-tec.gr Fri Jun 24 11:04:04 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 24 Jun 2005 18:04:04 +0300 Subject: Thanks for PIL (and other stuff) References: <1119579123.611615.197720@g14g2000cwa.googlegroups.com> Message-ID: <868ob1d9vmam81583h0466dfej5aso8vk2@4ax.com> On 23 Jun 2005 19:12:03 -0700, rumours say that "jean-marc" might have written: >So I wish it and its author(s) a good day, week, month, year and more! >Really! That is, "So long and thanks for all the PIL." -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From elmo13 at jippii.fi Tue Jun 28 20:07:14 2005 From: elmo13 at jippii.fi (=?UTF-8?B?RWxtbyBNw6RudHluZW4=?=) Date: Wed, 29 Jun 2005 03:07:14 +0300 Subject: Set/Get attribute syntatic sugar In-Reply-To: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Peter Hansen wrote: > ???? ???????? wrote: > >> There is a syntactic sugar for item access in >> dictionaries and sequences: >> >> o[e] = v <-> o.__setitem__(e, v) >> o[e] <-> o.__getitem__(e) >> >> where e is an expression. >> >> There is no similar way for set/get attribute for objects. >> If e is a given name, then o.e = v <-> o.__setattr__(e, v) >> o.e <-> o.__getattr__(e) >> >> Anybody thought about this issue? > > > Perhaps not, but now that you've pointed it out they've taken the time > machine back and fixed the problem before it arose: Maybe funny, but a bit too cocky for my taste. Robert kern is propably right about what he really meant so don't be too hasty in the future, right?). Looking at his code example I got the picture that he's of the kind that could come up with something useful. So either he's right(which I think is the case), or it's just the kind of silly mistake all of us sometimes make. I sure think some one should look in to this suggestion. >>>> class C: > ... def __setattr__(self, e, v): > ... print 'setting %s to %s' % (e, v) > ... self.__dict__[e] = v > ... >>>> o = C() >>>> v = 'mystring' >>>> o.e = v > setting e to mystring >>>> o.e > 'mystring' >>>> > > -Peter -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFCweYyctNFyQJObrsRAhGtAJwJXlhQ9i1PIQKj1fus6GIq7mfDVgCeJBRw vq6yJrozRTUSTu+p8akVbVw= =k4EW -----END PGP SIGNATURE----- From martin.witte at gmail.com Wed Jun 1 14:55:42 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 1 Jun 2005 11:55:42 -0700 Subject: creating a hex value In-Reply-To: <1285743.rKB6TKaXDy@teancum> References: <1285743.rKB6TKaXDy@teancum> Message-ID: <1117652142.697576.85300@o13g2000cwo.googlegroups.com> What about martin at lijnbaansgracht:~$ python Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> hex(21) '0x15' >>> From lycka at carmen.se Tue Jun 21 07:41:45 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 21 Jun 2005 13:41:45 +0200 Subject: OO approach to decision sequence? In-Reply-To: References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> <42B3D2BC.3050406@po-box.mcgill.ca> Message-ID: Chinook wrote: > I understand what you are saying. The point I'm messing up my head with > though, is when the entity (tree node in my case or variable record content > deconstructing in the aspect example I noted) is not an instance of a class > already - it is obtained from an external source and only decipherable by its > content. There are several aspects and approaches here, depending on the data. If you receive a stream of text, you might want to build a parser to handle that. For instance you might want to use something like PyParsing. That's not really an OO approach, but once you have your objects, it's time for OO! :) Note, that while the basic approach of the factory patterns is applicable to Python, most texts describe how to use it with C++ or Java, and do a large degree, they are complicated by shortcomings in those languages (such as static typing and reliance on inheritence for polymorphism) that are non-issues in Python. IOW, keep it simple. From leftwing17 at gmail.com Mon Jun 6 17:25:39 2005 From: leftwing17 at gmail.com (Adam Endicott) Date: 6 Jun 2005 14:25:39 -0700 Subject: wxPython: GridBagSizer, EXPAND, and HtmlListBox Message-ID: <1118093139.869663.310520@g44g2000cwa.googlegroups.com> I'm having some trouble using an HtmlListBox with a GridBagSizer. I'm not sure how best to explain what's happening, but it seems that every time my frame gets resized, the HtmlListBox grows taller, even when the resize is only horizontal, or makes the frame smaller. I'm pretty new to GUI layout and wxPython, so hopefully I'm doing something obviously wrong. Here's a short runnable code sample showing my basic layout (I'm using python 2.3.3 and wxPython 2.6 running on windows XP pro): -----Start Code----- import wx class TestFrame(wx.Frame): def __init__(self): app = wx.PySimpleApp() wx.Frame.__init__(self, None, -1) p = wx.Panel(self, -1) gbs = wx.GridBagSizer(5, 5) gbs.Add(wx.Button(p, -1), (0, 0), span=(1, 2), flag=wx.EXPAND) hlb = wx.HtmlListBox(p, -1) gbs.Add(hlb, (1, 0), span=(4, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (1, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (2, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (3, 1), flag=wx.EXPAND) gbs.Add(wx.Button(p, -1), (4, 1), flag=wx.EXPAND) gbs.AddGrowableRow(2) gbs.AddGrowableCol(1) p.SetSizerAndFit(gbs) self.SetClientSize(p.GetSize()) self.Show(True) wx.EVT_SIZE(hlb, self.onSize) app.MainLoop() def onSize(self, event): print event.GetSize() if __name__ == '__main__': TestFrame() -----End Code----- If you run that and try to resize the window by dragging an edge, the HtmlListBox just goes crazy and keeps getting bigger (try dragging the right edge back and forth). It does the same thing if I replace the HtmlListBox with a wx.Panel or even a wx.Window, but not with a wx.ListBox, or wx.Button. The effect I'm trying to accomplish is basically what you get if you sub in a wx.ListBox, (but I need the HtmlListBox because I want to put a small image next to the strings in the list). Removing the wx.EXPAND flag on the HtmlListBox (at line 11) solves the weird resizing, except that now the HtmlListBox doesn't fill the space it needs to. Does anyone know what's going on here, or how I can get this to work? From desertgarden at netscape.com Thu Jun 16 12:45:47 2005 From: desertgarden at netscape.com (Brian) Date: Thu, 16 Jun 2005 16:45:47 GMT Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') In-Reply-To: References: Message-ID: <%0ise.4937$hK3.169@newsread3.news.pas.earthlink.net> Hi Maxwell, Yes, to terminate a thread in Python early, use the following: import sys; sys.exit(0) This kills the particular thread without wiping out the entire Python application. Hope this helps, Brian :-) --- Maxwell Hammer wrote: > Hi all, > > This is related to an earlier post 'Help with thread related > tracebacks'...for which I have had no feedback yet :-( > > How should a thread complete i.e. how should it exit? > Reading the python online docs one gets the idea that simply returning is > OK - but I'm not sure. > Is it ok to do a sys.ext()? Use 'return' or just let them run out with no > 'return' ??? > > thanks. From deets at web.de Thu Jun 23 09:29:33 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 23 Jun 2005 15:29:33 +0200 Subject: Looking For Geodetic Python Software In-Reply-To: <7xmzph3mpg.fsf@ruckus.brouhaha.com> References: <447po2-iqt.ln1@eskimo.tundraware.com> <7xmzph3mpg.fsf@ruckus.brouhaha.com> Message-ID: <3hvrptFj700gU1@uni-berlin.de> > For spherical earth, this is easy, just treat the 2 locations as > vectors whose origin is at the center of the earth and whose length is > the radius of the earth. Convert the lat-long to 3-D rectangular > coordinates and now the angle between the vectors is > arccos(x dotproduct y). The over-ground distance is then just R*theta > where theta is the angle. It's a bit more complicated in the real world - usually one takes a spheroid as defined by the wgs84 standard: http://www.codeguru.com/Cpp/Cpp/algorithms/article.php/c5115/ Maybe for python, this is enteresting (haven't used it myself though): http://pyogclib.sourceforge.net/ Diez From catalin at bounce-software.com Tue Jun 21 12:16:07 2005 From: catalin at bounce-software.com (Catalin Constantin) Date: Tue, 21 Jun 2005 19:16:07 +0300 Subject: utf8 silly question Message-ID: <1374382022.20050621191607@bounce-software.com> i have the following code: c=chr(169)+" some text" how can i utf8 encode the variable above ? something like in php utf8_encode($var);?! chr(169) is the © (c) sign ! 10x for your help ! p.s.: i tryed using codecs, etc but always get an error message like: 'ascii' codec can't decode byte 0xa9 in position 0... -- Catalin Constantin Bounce Software http://www.bounce-software.com http://www.cabanova.ro From jarrod.roberson at gmail.com Mon Jun 13 14:17:50 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 13 Jun 2005 11:17:50 -0700 Subject: Dealing with marketing types... In-Reply-To: References: Message-ID: <1118686670.891440.88180@g14g2000cwa.googlegroups.com> man this is the worst advice I have ever heard, you can't "walk away with code" someone else paid you to write. Regardless of what your perceived slight is. NEVER take code you were paid to write unless you have it in writing that you can, you will lose that one everytime. From greg_miller at nexpress.com Thu Jun 30 07:08:23 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 30 Jun 2005 04:08:23 -0700 Subject: COM problem .py versus .exe In-Reply-To: <1120072089.931846.17010@o13g2000cwo.googlegroups.com> References: <1120053841.209150.69670@g43g2000cwa.googlegroups.com> <1120063626.040217.69630@z14g2000cwz.googlegroups.com> <1120072089.931846.17010@o13g2000cwo.googlegroups.com> Message-ID: <1120129703.918400.170720@g49g2000cwa.googlegroups.com> Thanks for the information, I stumbled across that page yesterday. It seems all the problems with this are solved. The executable works just like the Python version. Now I have to come up with an algorithm to parse through the output data to come up with the version numbers. Thanks for all your time. It's been a good learning experience for me. Now on with the project............................Greg From tassilo.von.parseval at rwth-aachen.de Wed Jun 1 00:09:43 2005 From: tassilo.von.parseval at rwth-aachen.de (Tassilo v. Parseval) Date: Wed, 1 Jun 2005 06:09:43 +0200 Subject: What are OOP's Jargons and Complexities? References: <1116843761.619249.144790@g47g2000cwa.googlegroups.com> <3584469.Aerji1NdQr@yahoo.com> <9SXme.22456$Is4.3402@attbi_s21> Message-ID: Also sprach Dale King: > David Formosa (aka ? the Platypus) wrote: >> On Tue, 24 May 2005 09:16:02 +0200, Tassilo v. Parseval >> wrote: >> >>> [...] I haven't yet come across a language that is both statically and >>>strongly typed, in the strictest sense of the words. I wonder whether >>>such a language would be usable at all. >> >> >> Modula2 claims to be both statically typed and strongly typed. And >> your wonder at its usablity is justified. > > I used a variant of Modula-2 and it was one of the best languages I have > ever used. That strong, static type checking was a very good thing. It > often took a lot of work to get the code to compile without error. > Usually those errors were the programmers fault for trying to play fast > and loose with data. But once you got it to compile it nearly always worked. I am only familiar with its successor Modula-3 which, as far as I understand, is Modula-2 with uppercased keywords and some OO-notion bolted onto it (I still recall 'BRANDED' references). I have to say that doing anything with this language was not exactly a delight. Tassilo -- use bigint; $n=71423350343770280161397026330337371139054411854220053437565440; $m=-8,;;$_=$n&(0xff)<<$m,,$_>>=$m,,print+chr,,while(($m+=8)<=200); From JOHNWUN at aol.com Mon Jun 6 19:03:22 2005 From: JOHNWUN at aol.com (Grooooops) Date: 6 Jun 2005 16:03:22 -0700 Subject: split up a list by condition? In-Reply-To: <3gjpk0FcrnknU1@individual.net> References: <3gjpk0FcrnknU1@individual.net> Message-ID: <1118099002.528915.289830@g47g2000cwa.googlegroups.com> Reinhold, Thanks for your response in the previous thread. Yours is an interesting question. I haven't come up with a solution, but I did realize that in the previous problem, the source 'word' doesn't really need to stay intact... So perhaps a solution along these lines? >>> for a in enumerate(wlist): ... if a[1] in vowels: ... vees.append(wlist.pop(a[0])) I don't know if it's possible to cram a 'pop' command into the single line solution though. I look forward to seeing other tricks to this end... :) From snail at objmedia.demon.co.uk Wed Jun 29 06:03:33 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 29 Jun 2005 11:03:33 +0100 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> <42BF6995.1050606@boonthavorn.com> <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> Message-ID: <0CuRDhE1HnwCFwl9@objmedia.demon.co.uk> In message , Markus Wankus writes >Have you ever tried anything that provides real, usable refactoring >like Eclipse does with Java? I guarantee if you used it more than a >few times your view would most likely change. I was forced to use Eclipse recently. Dreadful. I really disliked it. I never got as far as wanting to refactor things. I couldn't wait to stop using it. >The fact is, code evolves. You simply cannot write high-quality >software in one pass. Total agreement. My point is that productivity gains from refactoring tools are the least of your worries. Hiring good staff that know how to write, test and debug software is very much more important than the amount of time a refactoring tool will save. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From mfranklin1 at gatwick.westerngeco.slb.com Thu Jun 16 04:07:07 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Thu, 16 Jun 2005 09:07:07 +0100 Subject: Tkinter Question In-Reply-To: References: <23B7F3E89F1D424C96B13402B5F514D3048A55F9@ntm007.apsc.com> Message-ID: Fredrik Lundh wrote: > Nicholas.Vaidyanathan at aps.com wrote: > > >>Thanks for all the help guys... I'm a bit confused as to the inner >>workings of the Tkinter system (I'm both a Python and a GUI n00b). I was >>hoping that by slapping the x on button python was doing some cool >>dynamic variable creation (i.e. creating 9 variables with 1 loop using >>the x as a variable to modify the identifier), but I suppose you can't >>do that in Python (or can you?) > > > that's what lists are for (see the python tutorial for details). > A short explanation using a standard python list to hold the instances of Tkinter Buttons: buttonlist = [] for a in range(10): b = Tkinter.Button(root, text=a) b.pack() buttonlist.append(b) .... later .... print buttonlist[2]["text"] > >>I'm a little confused as to why self.button.text doesn't work but >>self.button["text"] does, can someone explain this? > > > x.text and x["text"] are two different operations in Python, and > Tkinter uses the former for widget methods, and latter for widget > options. > > (w[x] is a shortcut for x.cget(x), btw) > > > > > From steve at REMOVETHIScyber.com.au Sun Jun 12 11:33:12 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 13 Jun 2005 01:33:12 +1000 Subject: How to get/set class attributes in Python References: Message-ID: On Sun, 12 Jun 2005 14:40:26 +0000, Chris Spencer wrote: > Being an untyped language, Python does not require you to enforce types. > However, for those that require such functionality, you can get away > with using the "assert" statement. Assuming that Python isn't executed with the optimize switch, which disables assert. $ python -O Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> py> py> def tester(x): ... assert type(x) == type(0) ... print "%s is an integer." % x ... py> tester(3) '3 is an integer' py> tester("hello") 'hello is an integer' From ironfroggy at gmail.com Wed Jun 1 12:50:36 2005 From: ironfroggy at gmail.com (ironfroggy) Date: 1 Jun 2005 09:50:36 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117644113.523658.173830@g43g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> Message-ID: <1117644636.721724.41050@g14g2000cwa.googlegroups.com> because they are representing a seperate typing system outside of python, to which I am creating a bridge. The metaclass represents the types of this other system and the class represents the most basic object type, but since the types the metaclass represent are also objects, this is the only way i see to represent the relationship properly. From dlc at io.frii.com Mon Jun 20 11:24:40 2005 From: dlc at io.frii.com (Dennis Clark) Date: Mon, 20 Jun 2005 15:24:40 -0000 Subject: Embedded Systems Python? Message-ID: <11bdnto1au02i63@corp.supernews.com> Hi all, I've looked through the threads about embedded Python that are a year and a half old, and I thought that I'd ask this question now to see if anything has changed. Has anyone, or is anyone working with Python in an embedded Linux environment? Mine is NO where near as constrained as a cell phone since I've got plenty of memory to work with, I'm just running a Linux 2.4 kernel on an ARM9 platform. Are there success stories for Python on embedded Linux systems today? The embedded Java JVM's seem to all be propriatary and have quite high license fees (don't mention Kaffe, it seems pretty fragile to me.) I'm a bit of a newb when it comes to Python, is there anyone with experience compiling it on Linux platforms that can offer me pointers to try this out myself? thanks, DLC -- ============================================================================ * Dennis Clark dlc at frii.com www.techtoystoday.com * * "Programming and Customizing the OOPic Microcontroller" Mcgraw-Hill 2003 * ============================================================================ From codedivine at gmail.com Wed Jun 29 17:38:20 2005 From: codedivine at gmail.com (Rahul) Date: 29 Jun 2005 14:38:20 -0700 Subject: strange __call__ References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> <1120062469.370984.130670@f14g2000cwb.googlegroups.com> <1120076592.828106.301340@z14g2000cwz.googlegroups.com> Message-ID: <1120081100.410853.49590@g49g2000cwa.googlegroups.com> Hi. I understood your point. thanks... rahul Steven Bethard wrote: > Steven Bethard wrote: > > > > def wrap(obj): > > def f(*args, **kwargs): > > for arg in args: > > print arg > > return obj(*args, **kwargs) > > return f > > > > @wrap > > def func(a, b, c): > > ... > > > > class C(object): > > ... > > C = wrap(C) > > Rahul top-posted: > > If you do C = wrap(C) C no longer remains a class..it becomes a > > function. > > And if you do > func = wrap(func) > which is the equivalent of > @wrap > def func(...): > ... > then func no longer has the same signature. But as Reinhold suggests, > does that really matter? In the case of the class, you can still call > it to create class instances. In the case of the function, you can > still call it to retrieve return values. Why do you care about the type > of the object? > > In the case that it does matter, e.g. you want to be able to invoke your > methods from the class instead of the instance, you can wrap the > specific function that you need wrapped, e.g. > > class C(object): > @wrap > def __new__(cls, *args): > super(C, cls).__new__(cls, *args) > ... > > STeVe From guettli at thomas-guettler.de Wed Jun 29 09:45:20 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 29 Jun 2005 15:45:20 +0200 Subject: Reading output from a child process non-blockingly References: Message-ID: Am Wed, 29 Jun 2005 16:08:54 +0800 schrieb Yuan HOng: > In my program I have to call an external program and parse its output. > For that I use the os.popen2 function, and then read the output > stream. [cut] > I tried use select.select on the output stream returned by os.popen2, > but it returns a readable file descriptor only after the whole child > process ends. Select is the right module for this. But it only works on file descriptors on unix. What happens, if you run the external command on the shell like this: ext_prog > out.log & Check out.log with "tail" or "less +F". Do you see the data appear in small chunks? If not, the application detects that stdout is not a tty and you only get data if the buffer is full or if the application ends. If out.log gets filled in chunks you want to read, you can read this file as long as the application is running. Remember the size of the file after each read and use fd.seek() to read only the new data after opening it again. This should work on windows, too. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From daniel.dittmar at sap.corp Thu Jun 23 07:19:45 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 23 Jun 2005 13:19:45 +0200 Subject: PEP ? os.listdir enhancement In-Reply-To: References: Message-ID: Riccardo Galli wrote: > On Thu, 23 Jun 2005 11:34:02 +0200, Andreas Kostyrka wrote: > > >>What's wrong with >> >>(os.path.join(d, x) for x in os.listdir(d)) >> >>It's short, and easier to understand then some obscure option ;) >> >>Andreas > > > how does it help in using list comprehension, as the ones in the first > post? You can nest list comprehension [ e for e in (os.path.join(d, x) for x in os.listdir(d)) if os.path.isdir (e)] You might also want to look at module itertools, which has better support for transforming and filtering in multiple steps. Daniel From hammer at maxwell.com Thu Jun 16 01:50:39 2005 From: hammer at maxwell.com (Maxwell Hammer) Date: Thu, 16 Jun 2005 01:50:39 -0400 Subject: Help with thread related tracebacks Message-ID: <8o2dnXTQmO42jizfRVn-uA@look.ca> Hope someone can help with a problem I'm having. A python program I wrote terminates with the following traceback. *** start traceback *** Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/lib/python2.4/atexit.py", line 22, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib/python2.4/threading.py", line 636, in __exitfunc self._Thread__delete() File "/usr/lib/python2.4/threading.py", line 522, in __delete del _active[_get_ident()] KeyError: 16384 Error in sys.exitfunc: Traceback (most recent call last): File "/usr/lib/python2.4/atexit.py", line 22, in _run_exitfuncs func(*targs, **kargs) File "/usr/lib/python2.4/threading.py", line 636, in __exitfunc self._Thread__delete() File "/usr/lib/python2.4/threading.py", line 522, in __delete del _active[_get_ident()] KeyError: 16384 *** end traceback *** The program works correctly, and the traceback occurs ONLY after my program has exited normally. I really don't know what causes this, and since the program is quite large I wouldn't know what code snippet to post (if any). The following pseudocode describes what my program does: Main thread starts does some processing... while... does some processing... loads a function from a module known only at runtime by doing: exec 'import %s as Plugin' % PluginImportPath exec 'PluginStartFunction=getattr(Plugin, \'%s\')' % FunctionName PluginStartFunction(job commands...) monitor_events() if we have to quit: signal threads to complete and exit. wait for threads to indicate complete exit # end while Plugin Module: PluginStartFunction(job commands...): does some processing... run the module's "run" function by doing: thread.start_new_thread(PluginRunFunction, (job commands...)) return PluginRunFunction(job commands...): does some processing... spawns an external unix (console) program by doing: RETURN=os.system(program string...) does some processing... return ##end Plugin Module I have to load the plugin functions using "exec" because the plugin modules are only known at runtime, so cannot be hard-coded. In any case, I have made sure that the main thread does wait for all other threads to have terminated before it calls sys.exit and exits. It is only after main thread has exited that the above traceback occurs. Any gurus out there that can aid with this? Any and all help would be appreciated, even guidance as to what to investigate or to try. By the way what graphical debuggers do people use for debugging python apps.? Thanks very much From thomasbartkus at comcast.net Thu Jun 23 09:59:33 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 23 Jun 2005 08:59:33 -0500 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> <3tiue.27$jv6.1568@news.uswest.net> Message-ID: <4aGdnfbfEs1YIiffRVn-3Q@telcove.net> "Magnus Lycka" wrote in message news:d9dopt$8ih$1 at wake.carmen.se... > Cameron Laird wrote: > > OK, I'm with you part of the way. Typical "Access" developers > > are *always* involved with DLL hell, right? You're surely not > > saying that Python worsens that frustration, are you? > > I think Dan was commenting on flaws in Microsoft's products, > not in Python. As I understand it, he was suggesting to use > something else than Access with Python, not something else > than Python with Access. > The O.P. wanted a database for his > Python app, and Thomas Bartkus suggested Access. Not exactly! I suggested the built in Microsoft DAO or ADO database libraries which he could use without need to distribute with his app. The Access application is simply another client app that sits on top of DAO/ADO and would be quite unnecessary here. Any Python/DB application you wished to distribute for MS Windows would do best talk to the ADO library directly - end of distribution problems. * Everyone with WindowsXP already has the DAO and ADO libraries. * Not everyone has (or needs) MS Access which one would have to pay for and could not distribute freely with ones Python app. * Python has no need of MS Access in order to create, maintain, and manipulate databases using Microsofts built in ADO database facilities - although a developer *might* find Access useful as an inspection/debugging tool on his own workstation. All of which used to confuse the hell out of me :-) Thomas Bartkus From nid_oizo at yahoo.com_removethe_ Sat Jun 4 11:58:24 2005 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Sat, 04 Jun 2005 11:58:24 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Andrew Dalke wrote: > The implementation would need to track all the with/as forms > in a block so they can be __exit__()ed as appropriate. In this > case ghi.__exit() is called after jkl.__exit__() and > before defg.__exit__ > > The PEP gives an easy-to-understand mapping from the proposed > change to how it could be implemented by hand in the existing > Python. Can you do the same? I think it is simple and that the implementation is as much straight-forward. Think about it, it just means that: > with abc > > with defg: > with ghi > with jkl: > 1/0 is equivalent to: > with abc: > > with defg: > with ghi: > with jkl: > 1/0 That's it. Nothing more complex. It's only about syntax. > I have not idea if the problem you propose (multiple with/as > blocks) will even exist so I can't comment on which solution > looks good. It may not be a problem in real code, so not needing > any solution. Good point. As a C++ programmer, I use RAII a lot. However, there's situations in C++ that don't apply, like allocating dynamic memory in a scope. However, I still expect some Python programmers to use it enough to ask for that syntax to be added, in the same way operators like += have been added. But there's another point that has nothing to do with how many "with" statements you have in a function. In C++, very very rarely I've seen something like: void foo() { { // (define a scope for the Lock object) Lock locking(myMutex); ... } ... { Lock locking(myMutex); ... } } So I come to another conclusion: the indentation syntax will most of the time result in a waste of space. Typically a programmer would want its with-block to end at the end of the current block. So basically, there's two 10-90% points, one in favor of my proposal, one against: - Most of the time, you don't have a lot of with-statements in a single function, so not so much indentation. - Most of the time, a with-statement ends at the end of current block, so indentation-syntax most of the time result in a waste of space. The way to see my proposal is not "to be used when you have multiple with-blocks" but instead "never use the ':' syntax, unless necessary". The day some code need it, it's very easy to add a ':' and indent some code with our favorite editor. Regards, Nicolas From bwr607 at hotmail.com Mon Jun 6 23:07:26 2005 From: bwr607 at hotmail.com (William Drew) Date: 07 Jun 2005 03:07:26 GMT Subject: MySQL newsgroup proposal. Message-ID: ANNOUNCEMENT: A RFD (REQUEST FOR DISCUSSION) has been posted for the creation of a new Usenet newsgroup: comp.databases.mysql The proposal and related discussion can be read in the Usenet group news.groups ... feel free to weigh in and make any suggestions you may have. Message-ID: <1118086694.23087 at isc.org> Link: http://makeashorterlink.com/?Z1061363B -- Bill From riccardo_cut1 at cut2_sideralis.net Thu Jun 23 12:31:54 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Thu, 23 Jun 2005 18:31:54 +0200 Subject: User interfaces in console (dialog like) References: <2fdabf19.0506230445.249d063f@posting.google.com> Message-ID: On Thu, 23 Jun 2005 05:45:07 -0700, Negroup wrote: > Hi all. > > I need to provide to my users a graphical interface to be used from os' > command line. > Initially I thought something equivalent to Unix dialog, and googling > around I have found Python Dialog > (http://pythondialog.sourceforge.net/). This would be the perfect solution > for me if it could be cross platform. However, it doesn't work on Windows, > just on Linux/Unix. > > Do you guys know an alternative that fits my needings without moving from > Python? > > Thanks, > -ng It doesn't depend on the language. There aren't truely portable graphic interface libraries, which show more than a coloured rectangle. For *nix, there is also curses-extra, which offers various widgets (textview,combobox,radio and checkbuttons and so on). http://www.sideralis.net/index.php?action=4&pjid=20 Bye, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From devlai at gmail.com Sun Jun 26 14:38:17 2005 From: devlai at gmail.com (Devan L) Date: 26 Jun 2005 11:38:17 -0700 Subject: Favorite non-python language trick? References: <1119810243.032890.95410@g43g2000cwa.googlegroups.com> Message-ID: <1119811097.681889.198790@f14g2000cwb.googlegroups.com> < "return a if a.value == true" < "database.query(q) unless database.connect == error (etc) if a.value == True: return a if not database.connect == error: database.query(q) Trading two words for one word doesn't necessarily make the code better. < unless false then print 1 # this prints 1 forever while not False: print 1 "unless" seems to become "while not", as opposed to "if not". Should be more consistent. From rkern at ucsd.edu Wed Jun 22 02:37:50 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 21 Jun 2005 23:37:50 -0700 Subject: getting an object name In-Reply-To: References: Message-ID: David Bear wrote: > Let's say I have a list called, alist. If I pass alist to a function, > how can I get the name of it? > > alist = range(10) > > def afunction(list): > listName = list.__name__ (fails for a list object) In general, you don't. A particular object can have any number of names in various scopes or have no name at all. In particular, in your code, the same list object has 2 names in 2 scopes, "alist" in the global scope and "list" in afunction's local scope. alist = range(10) blist = alist clist = [alist] alist is blist alist is clist[0] -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From lqf at jdlssoft.com.cn Sun Jun 12 23:56:28 2005 From: lqf at jdlssoft.com.cn (lqf) Date: 12 Jun 2005 20:56:28 -0700 Subject: tree functions daily exercise: Range References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> Message-ID: thank From kent37 at tds.net Mon Jun 6 14:52:04 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Jun 2005 14:52:04 -0400 Subject: the python way? In-Reply-To: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> Message-ID: <42a49b05$1_2@newspeer2.tds.net> Grooooops wrote: > The code just seems kind of bulky to me. I am wondering, is this an > efficient way to do things, or am I making things harder than > necessary? Harder than necessary. contains() is not needed at all, you can test for 'b in alist' directly. List comprehensions simplify reinterpolate(), and you have a lot of redundant calls to list(). Here is a shorter version: """scrambles a word, but creates plausable gibberish""" import random def shuffled(s): """ scrambles word""" l = list(s) random.shuffle(l) return ''.join(l) def newZip(a1,a2): """ reassemble """ l1=len(a1) l2=len(a2) longest, shortest = [[a1,a2], [a2,a1]][l10: ret += longest.pop() if len(shortest)>0: ret += shortest.pop() return ret def reinterpolate(word): """ main function """ wlist = shuffled(word) vlist = 'aeiouy' # ok, y isn't really a vowel, but... vees = [ x for x in wlist if x in vlist ] cons = [ x for x in wlist if x not in vlist ] return newZip(vees,cons) word = "encyclopedia" print reinterpolate(word) Kent > > #--------------------------begin code------------------ > """scrambles a word, but creates plausable gibberish""" > import random > def shuffled(s): > """ scrambles word""" > l = list(s) > random.shuffle(l) > return ''.join(l) > > def contains(alist,b): > """...is letter b in list a...""" > ret = [] > for all in alist: > #print all > if all==b: > return 1 > return 0 > > def newZip(a1,a2): > """ reassemble """ > l1=len(a1) > l2=len(a2) > > longest = [a1,a2][l1 shortest = [a1,a2][longest == a1] > diff = max(l1,l2)-min(l1,l2) > #print longest > seq = len(longest) > ret = "" > for j in range(seq): > if len(longest)>0: > ret = ret + longest.pop() > if len(shortest)>0: > ret = ret + shortest.pop() > return ret > > def reinterpolate(word): > """ main function """ > wlist = shuffled(list(word)) > vlist = list('aeiouy') # ok, y isn't really a vowel, but... > vees = filter(lambda x: contains(vlist,x),wlist) > cons = filter(lambda x: not(contains(vlist,x)),wlist) > a=list(vees) > b=list(cons) > return newZip(a,b) > > word = "encyclopedia" > print reinterpolate(word) > > #-------------------------------end code--------------------------- From grante at visi.com Sat Jun 18 10:10:18 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 14:10:18 -0000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <11b88ier7jled7@corp.supernews.com> <1119102644.048879.258100@g47g2000cwa.googlegroups.com> Message-ID: <11b8aqap8gqom16@corp.supernews.com> On 2005-06-18, cpunerd4 wrote: > what is this py2exe thing? > Is py2exe included? > Where can I find it? http://www.google.com/search?q=py2exe -- Grant Edwards grante Yow! I just bought at FLATBUSH from MICKEY visi.com MANTLE! From ptmcg at austin.rr.com Fri Jun 24 15:09:41 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jun 2005 12:09:41 -0700 Subject: key - key pairs References: <200506231612.42324.hancock@anansispaceworks.com> <1119590073.725041.138270@g44g2000cwa.googlegroups.com> Message-ID: <1119640181.498665.15910@g43g2000cwa.googlegroups.com> Man, this is not my week! Another bug in my posted code! The posted version of SymmetricDict fails when adding an entry in which the key equals the value. First bug is in __setitem__ in which the insertion is done twice, which is wasteful but benign. The second bug is in __delitem__, which throws an exception when we try to delete the back-pointing entry - which was already deleted since there is only one entry. Another cautionary tale on the value of testing... Here it the improved SymmetricDict code. -- Paul class SymmetricDict(dict): def __delitem__(self,k): v = self[k] super(SymmetricDict,self).__delitem__(k) if not v==k: super(SymmetricDict,self).__delitem__(v) def __setitem__(self,k,v): if k in self: del self[k] if v in self: del self[v] super(SymmetricDict,self).__setitem__(k,v) if not v==k: super(SymmetricDict,self).__setitem__(v,k) From cam.ac.uk at mh391.invalid Tue Jun 28 17:38:30 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 28 Jun 2005 22:38:30 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119990282.791576.196130@g43g2000cwa.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1119990282.791576.196130@g43g2000cwa.googlegroups.com> Message-ID: muldoon wrote: > Michael Hoffman wrote: >>muldoon wrote: >> >>>Americans consider having a "British accent" a sign of sophistication >>>and high intelligence. Many companies hire salespersons from Britain to >>>represent their products,etc. Question: When the British hear an >>>"American accent," does it sound unsophisticated and dumb? >>> >>>Be blunt. We Americans need to know. >> >>To be blunt, I have no idea what this has to do with Python. Surely >>selecting the right forum to use indicates more sophistication and high >>intelligence than the way one speaks. ;-) > This is from California, not far from where they did the old atomic > bomb tests. Be tolerant. Mutation you know. First you say "be blunt," now you say "be tolerant?" Make up your mind! ;-) -- Michael Hoffman From newsgroups at jhrothjr.com Mon Jun 20 00:09:33 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 19 Jun 2005 22:09:33 -0600 Subject: Using print with format to stdout generates unwanted space References: <3hmt4rFhnn89U1@individual.net> Message-ID: <11bcgc0ctni8d19@news.supernews.com> Don't use print, write directly to sys.stdout. Print is not intended for precise output formatting; it's intended for quick outputs that are useable most of the time. John Roth "Paul Watson" wrote in message news:3hmt4rFhnn89U1 at individual.net... > #!/usr/bin/env python > > # Using a print statement to stdout results in an > # unwanted space character being generated at the > # end of each print output. Same results on > # DOS/Windows and AIX. > # > # I need precise control over the bytes that are > # produced. Why is print doing this? > # > import sys > > # If this is a DOS/Windows platform, then put stdout > # into binary mode so that only the UNIX compatible newline > # will be generated. > # > try: > import msvcrt, os > msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) > except: > print 'This is not an msvcrt platform.' > pass > > # Using print with newline suppressed generates a space at the > # end of each print statement. > # > for i in range(3): > print '%d,60,' % (i), > for j in range(10): > print '%d,' % (j), > print '' > > # Using a list and doing a join does not result in the space > # character being generated. > # > for i in range(3): > alist = [] > alist.append('%d,60,' % (i)) > for j in range(10): > alist.append('%d,' % (j)) > print ''.join(alist) > > sys.exit(0) > From peter at engcorp.com Thu Jun 23 13:21:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 23 Jun 2005 13:21:07 -0400 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <42b9d01e$0$2588$da0feed9@news.zen.co.uk> Message-ID: Dan wrote: > So in SQLLite, what happens of you try to store XYZ in an integer field? Without your having enabled any of the "affinity" options mentioned by Dave Cook, SQLite will happily store 'XYZ' in that column, and return it to you when you query that row. The types are either ignored, or advisory, or meaningful in various ways, depending on the settings you pick. Note that this is considered something as a desirable feature in the SQLite community, in a similar fashion (it appears to me) to how dynamic typing is considered in the Python community, so don't consider it outright to be a Bad Thing. I'd say more on the issue, if I knew anything that I hadn't just read in the documentation. ;-) -Peter From rune.strand at gmail.com Thu Jun 9 23:55:29 2005 From: rune.strand at gmail.com (Rune Strand) Date: 9 Jun 2005 20:55:29 -0700 Subject: how to operate the excel by python? In-Reply-To: References: Message-ID: <1118375729.127295.90870@g43g2000cwa.googlegroups.com> The key is Python for Windows : http://starship.python.net/crew/mhammond/win32/ See here for an Excel dispatch example: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325735 When doing such operations, I generally save all the Excel files to CSV files and do the operations on them using the csv module. From dimitri.pater at gmail.com Thu Jun 23 18:54:21 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Fri, 24 Jun 2005 00:54:21 +0200 Subject: string capitalize sentence Message-ID: Hello! I want to capitalize every sentence in a string: harry is a strange guy. so is his sister, but at least she is not a guy. i am. to: Harry is a strange guy. So is his sister, but at least she is not a guy. I am. I came up with the following solution: a = 'harry is a strange guy. so is his sister, but at least she is not a guy. i am.' b = a.replace('. ', '.') splitlist = b.split('.') newlist = [] for i in range(len(splitlist)): i = ''.join(splitlist[i].capitalize() + '.' newlist.append(i) cap = ' '.join(newlist).replace(' .', '') print cap and it prints : Harry is a strange guy. So is his sister, but at least she is not a guy. I am. But I wonder if there is a easier way to accomplish this. For instance it doesn't work with: is harry a strange guy? so is his sister, but at least she is not a guy. i am. any suggestions? Thanks, Dimitri -- Please visit dimitri's website: www.serpia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cam.ac.uk at mh391.invalid Tue Jun 28 16:01:20 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 28 Jun 2005 21:01:20 +0100 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: Robert Kern wrote: >> ???? ???????? wrote: >> >>> There is a syntactic sugar for item access in >>> dictionaries and sequences: >>> >>> o[e] = v <-> o.__setitem__(e, v) >>> o[e] <-> o.__getitem__(e) >>> >>> where e is an expression. >>> >>> There is no similar way for set/get attribute for objects. >>> If e is a given name, then o.e = v <-> o.__setattr__(e, v) >>> o.e <-> o.__getattr__(e) >>> >>> Anybody thought about this issue? > > I think he means something like this: > e = 'i_am_an_attribute' > o.(e) = 10 > o.i_am_an_attribute == 10 I always use the getattr() and setattr() built-ins which could be considered syntactic sugar when compared to the alternatives above. But that's all the syntactic sugar you need--any more will give you cancer of the semicolon. -- Michael Hoffman From mensanator at aol.com Tue Jun 7 20:58:43 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 7 Jun 2005 17:58:43 -0700 Subject: Binary numbers In-Reply-To: References: Message-ID: <1118192323.036948.304420@g49g2000cwa.googlegroups.com> Douglas Soares de Andrade wrote: > Hi ! > > How to work with binary numbers in python ? Is there a way to print a number > in its binary form like we do with oct() or hex() ? > > Im doing a project that i have to work with binaries and i tired of convert > numbers to string all the time to perform some operations. > > I searched about it in many places like python.org and google, but not found > anything useful. > > Thats why im asking this. > > And another question... if python has not a way to do this, why i let me use > oct(), hex() and not bin() ? > > Thanks for the help ! > > -- > Douglas Soares de Andrade > http://douglasandrade.cjb.net - dsa at unilestemg.br > UnilesteMG - www.unilestemg.br > ICQ, MSN = 76277921, douglas at tuxfamily.org You might want to try the GMPY module: >>> from gmpy import * >>> help(digits) Help on built-in function digits: digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. >>> x = 2**32 - 1 >>> print x 4294967295 >>> print digits(x,2) 11111111111111111111111111111111 From mahs at telcopartners.com Thu Jun 2 12:50:55 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 02 Jun 2005 09:50:55 -0700 Subject: Performance Issues please help In-Reply-To: <1117723908.636248.302410@g14g2000cwa.googlegroups.com> References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> <1117723908.636248.302410@g14g2000cwa.googlegroups.com> Message-ID: PyPK wrote: > Yep that improved the speed by about 50% now it takes about 10 secs > instead of 24 seconds..Thanks much. I guess that is the best we could > do right.It would be really helpful if I could get it less than 5 > seconds. Any suggestions on that?? > Things to try: * in-lining the min and max expressions * depending on the distribution of e, it may be faster to catch KeyErrors def search1(m): box = {} for r,row in enumerate(m): for c,e in enumerate(row): try: minc, minr, maxc, maxr = box[e] box[e] = ( c < minc and c or minc, r < minr and r or minr, c > maxc and c or maxc, r > maxr and r or maxr) except KeyError: box[e] = (c, r, c, r) return box Michael From enas_khalil at yahoo.com Thu Jun 30 09:07:37 2005 From: enas_khalil at yahoo.com (enas khalil) Date: Thu, 30 Jun 2005 06:07:37 -0700 (PDT) Subject: if you please i want a help in running a nltk modules In-Reply-To: Message-ID: <20050630130738.50576.qmail@web50302.mail.yahoo.com> if you please i want a help im a beginner in using python i want to know how can i run a GUI module i installed python on windows platform thanks python-list-request at python.org wrote: Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." Today's Topics: 1. ANN: PyGaim released - Gaim Python plugin (Gerrit van Dyk) 2. multi regexp analyzer ? or how to do... (joh12005 at yahoo.fr) 3. Re: need help with MySQLdb (Wolfram Kraus) 4. Re: Favorite non-python language trick? (Paddy) 5. Re: need help with MySQLdb (Dennis Lee Bieber) 6. Re: some trouble with MySQLdb (dimitri pater) 7. Re: need help with MySQLdb (Dennis Lee Bieber) 8. python install settings... (jtan325) 9. Re: aligning text with space-normalized text (Peter Otten) 10. Re: Inheriting from object (Fuzzyman) From: Gerrit van Dyk To: python-list at python.org Date: Thu, 30 Jun 2005 07:36:22 +0200 Subject: ANN: PyGaim released - Gaim Python plugin PyGaim has been released. Summary: Gaim Python plug-in. The product provides developers with the capability to develop python plugins for Gaim This release is just a get it out there release and a lot of polishing still needs to be done. However, it does enable a python developer to develop gaim plugins using python as the programming language. The current packages is available from http://sourceforge.net/projects/pygaim ToDo: Web page CVS Instructions on installing and using More examples A interface to the gaim gui using pygtk Lots of other stuff. The mailing list should be up in the next 24 hours From: joh12005 at yahoo.fr To: python-list at python.org Date: 29 Jun 2005 23:19:50 -0700 Subject: multi regexp analyzer ? or how to do... Hello, here is a trouble that i had, i would like to resolve it with python, even if i still have no clue on how to do it. i had many small "text" files, so to speed up processes on them, i used to copy them inside a huge one adding some king of xml separator : [content] content is tab separated data (columns) ; data are strings now here come the tricky part for me : i would like to be able to create some kind of matching rules, using regular expressions, rules should match data on one line (the smallest data unit for me) or a set of lines, say for example : if on this line , match first column against this regexp and match second column and on following line match third column -> trigger something so, here is how i had tried : - having all the rules, - build some kind of analyzer for each rule, - keep size of longest one L, - then read each line of the huge file one by one, - inside a "file", create all the subsets of length <= L - for each analyzer see if it matches any of the subsets - if it occurs... my trouble is here : "for each analyzer see if it matches any of the subset" it is really to slow, i had many many rules, and as it is "for loop inside for loop", and inside each rule also "for loop on subsets lines" i need to speed up that, have you any idea ? i am thinking of having "only rules for one line" and to keep traces of if a rule is a "ending one" (to trigger something) , or a "must continue" , but is still unclear to me for now... a great thing could also have been some sort of dict with regexp keys... (and actually it would be great if i could also use some kind of regexp operator to tell one can skip the content of 0 to n lines before matching, just as if in the example i had changed "following..." by "skip at least 2 lines and match third column on next line - it would be great, but i still have really no idea on how to even think about that) great thx to anybody who could help, best From: Wolfram Kraus To: python-list at python.org Date: Thu, 30 Jun 2005 08:41:37 +0200 Subject: Re: need help with MySQLdb nephish at xit.net wrote: > Hey there all, > i have a question about how to point my python install to my sql > database. > > when i enter this: db = MySQLdb.connect(user="user", passwd="pass", > db="myDB") > > i get this: > Traceback (most recent call last): > File " ", line 1, in -toplevel- > db = MySQLdb.connect(user="user", passwd="pass", db="MyDB") > File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66, > in Connect > return Connection(*args, **kwargs) > File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line > 134, in __init__ > super(Connection, self).__init__(*args, **kwargs2) > OperationalError: (1049, "Unknown database 'MyDB'") > > i am using the all in one package from lampp (now xampp) and i have > tested a couple of python scripts from the cgi, but.... nothing that > connects to the database. > > any ideas? > > thanks > Try the following from the shell (NOT the python shell): mysql -u user -p [Enter passwd] mysql> show databases; If MyDB isn't in the list either something went wrong with the xampp installation or the database for xampp got a different name. (I am no xampp expert, so I can't help you any further) HTH, Wolfram From: "Paddy" To: python-list at python.org Date: 29 Jun 2005 23:44:24 -0700 Subject: Re: Favorite non-python language trick? Sadly, its not a solution that I'm after, but a particular toolkit that can be used for solving that type of problem. - Pad. From: Dennis Lee Bieber To: python-list at python.org Date: Thu, 30 Jun 2005 06:47:18 GMT Subject: Re: need help with MySQLdb On 29 Jun 2005 21:56:49 -0700, nephish at xit.net declaimed the following in comp.lang.python: > any ideas? > Step 1: show us what the interactive command line tool "mysql" does with... mysql user -p pass use MyDB; IOW, verify you can connect to the database using the MySQL tools first, then figure out what is different with the MySQLdb call. -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Home Page: < > Overflow Page: < From: dimitri pater CC: python-list at python.org To: nephish Date: Thu, 30 Jun 2005 08:58:41 +0200 Subject: Re: some trouble with MySQLdb try: db = MySQLdb.connect(host="localhost", user="user", passwd="pass", db="myDB") localhost can be a URL also (if MySQL is set up properly in the first place) regards, Dimtiri On 6/30/05, nephish wrote:Hey there all, i have a question about how to point my python install to my sql database. when i enter this: db = MySQLdb.connect(user="user", passwd="pass", db="myDB") i get this: Traceback (most recent call last): File "", line 1, in -toplevel- db = MySQLdb.connect(user="user", passwd="pass", db="MyDB") File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66, in Connect return Connection(*args, **kwargs) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 134, in __init__ super(Connection, self).__init__(*args, **kwargs2) OperationalError: (1049, "Unknown database 'MyDB'") i am using the all in one package from lampp (now xampp) and i have tested a couple of python scripts from the cgi, but.... nothing that connects to the database. any ideas? thanks -- http://mail.python.org/mailman/listinfo/python-list -- Please visit dimitri's website: www.serpia.com From: Dennis Lee Bieber To: python-list at python.org Date: Thu, 30 Jun 2005 06:57:54 GMT Subject: Re: need help with MySQLdb On Thu, 30 Jun 2005 06:47:18 GMT, Dennis Lee Bieber declaimed the following in comp.lang.python: > On 29 Jun 2005 21:56:49 -0700, nephish at xit.net declaimed the following > in comp.lang.python: > > > > any ideas? > > > Step 1: show us what the interactive command line tool "mysql" > does with... > > > mysql user -p > pass > use MyDB; > > IOW, verify you can connect to the database using the MySQL > tools first, then figure out what is different with the MySQLdb call. {okay, slight error in the command line string -- I haven't ported MySQL from the old W98 machine to the WinXP machine yet} -- > ============================================================== < > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > wulfraed at dm.net | Bestiaria Support Staff < > ============================================================== < > Home Page: < > Overflow Page: < From: "jtan325" To: python-list at python.org Date: 30 Jun 2005 00:01:43 -0700 Subject: python install settings... hi, i am running Linux Ubuntu Hoary and am trying to build the Python numarray package, v. 1.3.2 by hand since ubuntu's repos won't be updated until breezy. i have python 2.4, and gcc 3.3.5 after unpacking the tar, i run "python setup.py install", as it says in the installation instructions. i get the following: [colfax 53] numarray-1.3.2 > python setup.py install Using EXTRA_COMPILE_ARGS = [] running install running build running build_py copying Lib/numinclude.py -> build/lib.linux-i686-2.4/numarray running build_ext Traceback (most recent call last): File "setup.py", line 222, in ? main() File "setup.py", line 213, in main setup(**p) File "/usr/lib/python2.4/distutils/core.py", line 149, in setup dist.run_commands() File "/usr/lib/python2.4/distutils/dist.py", line 946, in run_commands self.run_command(cmd) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/install.py", line 506, in run self.run_command('build') File "/usr/lib/python2.4/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/build.py", line 112, in run self.run_command(cmd_name) File "/usr/lib/python2.4/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/build_ext.py", line 254, in run customize_compiler(self.compiler) File "/usr/lib/python2.4/distutils/sysconfig.py", line 174, in customize_compiler cc_cmd = cc + ' ' + opt TypeError: cannot concatenate 'str' and 'NoneType' objects I had a similiar (but different) error earlier, but then I learned I had to set my "CC" environment variable. So I set that to "gcc". i have tried setting my "OPT" setting to something like "-g 02" (no idea what it means just found it somewhere, but it still didn't work. upon closer inspection of Python's distutils sysconfig.py, is the error being caused by the ' ' in "cc_cmd = cc + ' ' + opt"? Any ideas on this new error? Are there packages/settings I need to take care of before i can use Python's distutils to install stuff? Thanks, Jason From: Peter Otten <__peter__ at web.de> To: python-list at python.org Date: Thu, 30 Jun 2005 09:07:04 +0200 Subject: Re: aligning text with space-normalized text Steven Bethard wrote: > I have a string with a bunch of whitespace in it, and a series of chunks > of that string whose indices I need to find. However, the chunks have > been whitespace-normalized, so that multiple spaces and newlines have > been converted to single spaces as if by ' '.join(chunk.split()). Some If you are willing to get your hands dirty with regexps: import re _reLump = re.compile(r"\S+") def indices(text, chunks): lumps = _reLump.finditer(text) for chunk in chunks: lump = [lumps.next() for _ in chunk.split()] yield lump[0].start(), lump[-1].end() def main(): text = """\ aaa bb ccc dd eee. fff gggg hh i. jjj kk. """ chunks = ['aaa bb', 'ccc dd eee.', 'fff gggg hh i.', 'jjj', 'kk.'] assert list(indices(text, chunks)) == [(3, 10), (11, 22), (24, 40), (44, 47), (48, 51)] if __name__ == "__main__": main() Not tested beyond what you see. Peter From: "Fuzzyman" To: python-list at python.org Date: 30 Jun 2005 00:36:34 -0700 Subject: Re: Inheriting from object The reason I ask is that I often (well... a couple of times anyway) see cryptic omments like : and if you inherit from object you get all the benefits of new style classes Now I know about the advantages of inheriting from the built in types (if that's what you want to do) -but am a bit fuzzier on the 'general benefits'. I'm vaguely aware of properties.... I'll have to explore them at some point. Best Regards, Fuzzy http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list --------------------------------- Yahoo! Mail Mobile Take Yahoo! Mail with you! Check email on your mobile phone. -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Mon Jun 6 03:11:17 2005 From: http (Paul Rubin) Date: 06 Jun 2005 00:11:17 -0700 Subject: easiest way to split a list into evenly divisble smaller lists, and assign them to variables? References: <1118040724.644534.259460@g44g2000cwa.googlegroups.com> Message-ID: <7xekbgj6y2.fsf@ruckus.brouhaha.com> "flamesrock" writes: > Lets say I have a list containing 12, 13, 23 or however many entries. > What I want is the greatest number of lists evenly divisible by a > certain number, and for those lists to be assigned to variables. You almost certainly don't want to do that. That's something beginning programmers often think of doing, but it's almost always better to use something more general, like an array. > consider this code: > # my_list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14, > # 15,16,17,18,19,20,21,22,23,24,25] > # entry=0 > # dictionary_of_lists = {} > # while len(original_list) != 0: Umm, what's "original_list"? Do you mean "my_list"? The rest of your code has similar errors. > would give us > {1:[1,2,3,4],2:[5,6,7,8], > 3:[9,10,11,12],4:[13,14,15,16], > 5:[17,18,19,20],6:[21,22,23,24],7:[25]} > > Is there a better way? What I'd like to do is create free variables > without needing to put them in a dictionary. Your best bet is probably to create a list of lists: sublist_length = 4 # desired length of the "inner" lists list_of_lists = [] for i in xrange(0, len(my_list), sublist_length): list_of_lists.append(my_list[i: i+sublist_length]) That gives list_of_lists = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24], [25]] So you'd just use list_of_lists[0] to refer to the 1st sublist, etc. From jepler at unpythonic.net Sun Jun 12 21:52:22 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 12 Jun 2005 20:52:22 -0500 Subject: Get drives and partitions list (Linux) In-Reply-To: <42accf62$0$11720$8fcfb975@news.wanadoo.fr> References: <42accf62$0$11720$8fcfb975@news.wanadoo.fr> Message-ID: <20050613015221.GB2945@unpythonic.net> Using /proc/partitions is probably preferable because any user can read it, not just people who can be trusted with read access to drives, and because the format of /proc/partitions is probably simpler and more stable over time. That said, what you do is import commands fdisk_output = commands.getoutput("fdisk -l %s" % partition) followed by some specialized code to parse the output of 'fdisk -l' The following code is not at all tested, but might do the trick. # python parse_fdisk.py /dev/hda4 blocks=1060290 bootable=False partition_id_string='Linux swap' partition_id=130 start=8451 end=8582 /dev/hda1 blocks=15634048 bootable=True partition_id_string='HPFS/NTFS' partition_id=7 start=1 end=1947 /dev/hda3 blocks=9213277 bootable=False partition_id_string='W95 FAT32 (LBA)' partition_id=12 start=8583 end=9729 /dev/hda2 blocks=52235347 bootable=False partition_id_string='Linux' partition_id=131 start=1948 end=8450 # This source code is placed in the public domain def parse_fdisk(fdisk_output): result = {} for line in fdisk_output.split("\n"): if not line.startswith("/"): continue parts = line.split() inf = {} if parts[1] == "*": inf['bootable'] = True del parts[1] else: inf['bootable'] = False inf['start'] = int(parts[1]) inf['end'] = int(parts[2]) inf['blocks'] = int(parts[3].rstrip("+")) inf['partition_id'] = int(parts[4], 16) inf['partition_id_string'] = " ".join(parts[5:]) result[parts[0]] = inf return result def main(): import commands fdisk_output = commands.getoutput("fdisk -l /dev/hda") for disk, info in parse_fdisk(fdisk_output).items(): print disk, " ".join(["%s=%r" % i for i in info.items()]) if __name__ == '__main__': main() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dalke at dalkescientific.com Mon Jun 13 19:38:05 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 13 Jun 2005 23:38:05 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Peter Maas wrote: > I think Peter is right. Proceeding top-down is the natural way of > learning (first learn about plants, then proceed to cells, molecules, > atoms and elementary particles). Why in the world is that way "natural"? I could see how biology could start from molecular biology - how hereditary and self-regulating systems work at the simplest level - and using that as the scaffolding to describe how cells and multi-cellular systems work. Plant biology was my least favorite part of my biology classes. In general I didn't like the "learn the names of all these parts" approach of biology. Physics, with its more directly predictive view of the world, was much more interesting. It wasn't until college when I read some Stephen J. Gould books that I began to understand that biology was different than "'the mitochondria is the powerhouse of the cell', here's the gall bladder, that plant's a dicot, this is a fossilized trilobite." Similarly, programming is about developing algorithmic thought. A beginner oriented programming language should focus on that, and minimize the other details. Restating my belief in a homologous line: proceeding from simple to detailed is the most appropriate way of learning. Of course in some fields even the simplest form takes a long time to understand, but programming isn't string theory. Andrew dalke at dalkescientific.com From grante at visi.com Sat Jun 18 09:35:16 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 13:35:16 -0000 Subject: Loop until condition is true References: <1119074614.700809@yasure> Message-ID: <11b88ok1tr67475@corp.supernews.com> On 2005-06-18, Peter Otten <__peter__ at web.de> wrote: >> If?you?look?at?C?code,?at?least?in?my?experience?the >> "until" loop is quite rarely used.??(I?don't?see?it?once?in?the?source >> to Python 2.4, for example.) > > Long time no C? > > 'until' in C is actually > > do > statement > while (expression); > > I found 136 occurrences of "do {" versus 754 of "while (" and 1224 of "for > (" in the Python 2.4 source, so using these rough estimates do-while still > qualifies as "rarely used". AFAICT, the main use for do/while in C is when you want to define a block of code with local variables as a macro: #define DoSomething(foo) \ do \ { \ int i; \ /* do something with foo and i */ \ } while (0) -- Grant Edwards grante Yow! I HIJACKED a 747 to at get here!! I hope those visi.com fabulous CONEHEADS are at HOME!! From roy at panix.com Thu Jun 30 17:14:32 2005 From: roy at panix.com (Roy Smith) Date: 30 Jun 2005 17:14:32 -0400 Subject: Python for everything? References: <1120164834.057669.297840@f14g2000cwb.googlegroups.com> Message-ID: wrote: > I have read in the old days that C was used for everything. It was a > systems programming language, and also did a lot of the same stuff > Bash scripts and perl do now. I learned C in "the old days" (1977 or maybe 78). We had plenty of other tools for scripting. Before perl, we certainly had shell scripts (although the early shells were not as powerful as bash/ksh/etc), along with a healthy dose of utilities like grep/sed/sort and awk. I don't know anybody who tried to do everything in C. > My question is, can Python "do it all"? Probably not. I couldn't imagine writing an operating system in Python; you'd never get the performance you need. For very low-level stuff that interfaces with hardware and twiddles with bits, it's probably the wrong tool as well. > I am wondering what to learn as my scripting language. Python is an excellent scripting language, and I strongly urge you to learn it. But, for certain niches, there are better tools. If you main goal is to execute other processes and manipulate files, for example, bash is probably a better tool. Often, your choice of tool will be dictated by external constraints. If you're trying to interface to some third-party system which only has a perl or java API (not an uncommon situation), you're going to be doing it in perl or java. From nospam at nospam.com Thu Jun 9 16:57:07 2005 From: nospam at nospam.com (Mark Tolonen) Date: Thu, 9 Jun 2005 13:57:07 -0700 Subject: Any way to not create .pyc files? References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> Message-ID: "Lonnie Princehouse" wrote in message news:1118337243.321804.284910 at g14g2000cwa.googlegroups.com... > In short: > > Is there any way to run Python WITHOUT trying to create .pyc files (or > .pyo) or to have Python not attempt to import the .pyc files it finds? > > Reason: > > We have a site-specific package installed on a network drive[1]. When > anyone with write access imports this package, the network drive gets > spammed with .pyc files. > > If these .pyc files exist, they appear to cause problems when other > users' Python interpreters use them instead of the .py files. (I know, > they *should* work, but they don't). This may have something to do > with the fact that all of these users (on Windows) have the network > drive mapped to arbitrary drive letters. I don't know. > > PEP 304 would have helped, but it appears to be deceased. What I > really want is a command line option > > I'm going to have to cobble together a work-around, like having > imported modules delete their own .pyc files immediately after import, > but it would be really nice to have a /good/ way of not using .pyc... > > (footnotes) > > [1] Because it's an administrative nightmare to distribute code updates > to dozens of non-technical users > Are you using ActivePython? ActivePython's installation updates the PATHEXT environment variable on Windows with the .pyc and .py extensions (.pyc first). This environment variable is used to try extensions when you run a program from the command line without an extension. Example: [1] C:\ex>set pathext PATHEXT=.com;.exe;.bat;.cmd;.pyc;.py [2] C:\ex>echo print "old" > script.py [3] C:\ex>python -c "import script" old [4] C:\ex>script old [5] C:\ex>echo print "new" > script.py [6] C:\ex>script old [7] C:\ex>python -c "import script" new [8] C:\ex>script new Even though script.py contains new (line 5), script in line 6 runs the .pyc generated by line 3. To fix this problem, put .py and .pyw extenstions ahead of .pyc and .pyo in PATHEXT. Hope this helps, Mark From __peter__ at web.de Tue Jun 21 07:51:50 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 21 Jun 2005 13:51:50 +0200 Subject: getting list of all available modules References: <87d5qgsddt.fsf@penguin.brutt.org> Message-ID: Benjamin Rutt wrote: > I want to do the same (get all such modules in a python list); how can > I do so???Or?where?is?the?code?for?the?REPL?for?help()?itself?so?I?can > find out myself? Get hold of the Python source code and grep for some (hopefully) selective piece of text. In the case of help() you are lucky as it is implemented in Python, and therefore searching the stdlib will do: $ find /usr/local/lib/python2.4 -name \*.py |xargs grep "Please wait" /usr/local/lib/python2.4/pydoc.py:Please wait a moment while I gather a list of all available modules... Looking into that file, a suspiciously named ModuleScanner class is right over there. Now what is your excuse for not finding it yourself in the first place? You seem to be on Linux, so "That's not how I do it with Visual Basic" can't be it :-) Peter From ptaku2_wywal_to_ at tlen.pl Mon Jun 6 18:22:14 2005 From: ptaku2_wywal_to_ at tlen.pl (w.p.) Date: Tue, 07 Jun 2005 00:22:14 +0200 Subject: [wxPython] How to change deafult tab traversing (radiobuttons & panel) Message-ID: Hello! I want change default tab traversing in my app. But i don't know how to do it :( Belowe i include simple example - i want change default tab order: radiobutton "mode11" -> radiobutton "mode31" -> button OK I can't find any option, flag, or another way. I try use wx.EVT_KEY_DOWN macro, or Bind - but without success. When i use Borland Builder C++ i must only set tabStop=False .... sorry for my english ! w.p. ####################################################################################### import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title) mainPanel = wx.Panel(self) mainSizer = wx.BoxSizer(wx.VERTICAL) panel1=wx.Panel(mainPanel,style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER,size=(200,100)) mainSizer.Add(panel1,flag=wx.ALL,border=5) panel2=wx.Panel(mainPanel,style=wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER,size=(200,100)) mainSizer.Add(panel2,flag=wx.ALL,border=5) # group 1 gridSiz1 = wx.FlexGridSizer(2,2) panel1.SetSizer(gridSiz1) self.rb11 = wx.RadioButton(panel1, -1, style=wx.RB_GROUP, label="mode 11") self.rb12 = wx.RadioButton(panel1, -1, label="mode 12") self.rb21 = wx.RadioButton(panel1, -1, style=wx.RB_GROUP, label="mode 21") self.rb22 = wx.RadioButton(panel1, -1, label="mode 22") gridSiz1.Add(self.rb11,flag=wx.ALL,border=3) gridSiz1.Add(self.rb12,flag=wx.ALL,border=3) gridSiz1.Add(self.rb21,flag=wx.ALL,border=3) gridSiz1.Add(self.rb22,flag=wx.ALL,border=3) # group 2 gridSiz2 = wx.FlexGridSizer(2,2) panel2.SetSizer(gridSiz2) self.rb31 = wx.RadioButton(panel2, -1, style=wx.RB_GROUP, label="mode 31") self.rb32 = wx.RadioButton(panel2, -1, label="mode 32") self.rb41 = wx.RadioButton(panel2, -1, style=wx.RB_GROUP, label="mode 41") self.rb42 = wx.RadioButton(panel2, -1, label="mode 42") gridSiz2.Add(self.rb31,flag=wx.ALL,border=3) gridSiz2.Add(self.rb32,flag=wx.ALL,border=3) gridSiz2.Add(self.rb41,flag=wx.ALL,border=3) gridSiz2.Add(self.rb42,flag=wx.ALL,border=3) okBut = wx.Button(mainPanel,label="-- OK --") mainSizer.Add(okBut,flag=wx.ALL|wx.ALIGN_CENTER,border=10) mainPanel.SetSizer(mainSizer) self.Layout() # wx.EVT_KEY_DOWN(self.rb11,self.OnRBKD) self.rb11.Bind(wx.EVT_KEY_DOWN, self.OnRBKD) def OnRBKD(self,event): print "OnKey!" event.Skip() class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, "Simple wxPython App") self.SetTopWindow(frame) frame.Show(True) return True app = MyApp(0) app.MainLoop() From davecook at nowhere.net Thu Jun 23 02:12:11 2005 From: davecook at nowhere.net (Dave Cook) Date: Thu, 23 Jun 2005 06:12:11 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <42b9d01e$0$2588$da0feed9@news.zen.co.uk> Message-ID: On 2005-06-23, Peter Hansen wrote: > Your list didn't mention a few things that might be critical. > Referential integrity? You can implement it in sqlite with triggers. I only bother with cascading delete triggers, myself. >Type checking? SQLite currently supports > neither. sqlite3 has a "strict affinity" mode, but I'm not exactly sure how one sets it. http://www.sqlite.org/datatype3.html Dave Cook From martin at v.loewis.de Fri Jun 3 15:08:34 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 03 Jun 2005 21:08:34 +0200 Subject: thread vs GC In-Reply-To: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> References: <7xoeaofem9.fsf_-_@ruckus.brouhaha.com> Message-ID: <42a0aab3$0$31348$9b622d9e@news.freenet.de> Paul Rubin wrote: > Any suggestions for the cleanest way to get rid of the thread? As Jeff explains, it is rather unlikely that GC will collect primegen objects, since the generating thread holds self as a local variable. You should make background_generator have explicit q and event arguments, and you should signal the event in __del__. However, this won't terminate the thread, since it still hangs in .put. So it might be easiest to .read() in __del__ first. Regards, Martin From lycka at carmen.se Mon Jun 13 06:23:48 2005 From: lycka at carmen.se (Magnus Lycka) Date: Mon, 13 Jun 2005 12:23:48 +0200 Subject: DB API 2.0 and transactions In-Reply-To: References: Message-ID: <42AD5EB4.4060807@carmen.se> I'm CC:ing this to D'Arcy J.M. Cain. (See comp.lang.python for prequel D'Arcy.) Christopher J. Bottaro wrote: > Check this out... > > > import pgdb > import time > > print time.ctime() > db = pgdb.connect(user='test', host='localhost', database='test') > time.sleep(5) > db.cursor().execute('insert into time_test > (datetime) > values > (CURRENT_TIMESTAMP)') > db.commit() > curs = db.cursor() > curs.execute('select datetime from time_test order by datetime desc limit > 1') > row = curs.fetchone() > print row[0] > > > > Fri Jun 10 17:27:21 2005 > '2005-06-10 17:27:21.654897-05' > > > Notice the times are exactly the same instead of 5 sec difference. > > What do you make of that? Some other replies to this thread seemed to > indicate that this is expected and proper behavior. This is wrong. It should not behave like that if it is to follow the SQL standard which *I* would expect and consider proper. I don't think the SQL standard mandates that all evaluations of CURRENT_TIMESTAMP within a transaction should be the same. It does manadate that CURRENT_TIMESTAMP in only evaluated once in each SQL statement, so "CURRENT_TIMESTAMP=CURRENT_TIMESTAMP" should always be true in a WHERE statement. I don't think it's a bug if all timestamps in a transaction are the same though. It's really a bonus if we can view all of a transaction as taking place at the same time. (A bit like Piper Halliwell's time-freezing spell in "Charmed".) The problem is that transactions should never start until the first transaction-initiating SQL statement takes place. (In SQL-92, all standard SQL statements are transaction initiating except CONNECT, DISCONNECT, COMMIT, ROLLBACK, GET DAIGNOSTICS and most SET commands (SET DESCRIPTOR is the exception here).) Issuing BEGIN directly after CONNECT, ROLLBACK and COMMIT is in violation with the SQL standards. A workaround for you could be to explicitly start a new transaction before the insert as PostgreSQL (but not the SQL standard) wants you to do. I suppose you can easily do that using e.g. db.rollback(). If you like, I guess you could do db.begin=db.rollback in the beginning of your code and then use db.begin(). Another option would be to investigate if any of the other postgreSQL drivers have a more correct behaviour. The non-standard behaviour that you describe it obvious from the pgdb source. See: http://www.pygresql.org/cvsweb.cgi/pygresql/module/pgdb.py?rev=1.27 (Comments added by me.) > class pgdbCnx: > > def __init__(self, cnx): > self.__cnx = cnx > self.__cache = pgdbTypeCache(cnx) > try: > src = self.__cnx.source() > src.execute("BEGIN") # Ouch! > except: > raise OperationalError, "invalid connection." > > ... > def commit(self): > try: > src = self.__cnx.source() > src.execute("COMMIT") > src.execute("BEGIN") # Ouch! > except: > raise OperationalError, "can't commit." > > def rollback(self): > try: > src = self.__cnx.source() > src.execute("ROLLBACK") > src.execute("BEGIN") # Ouch! > except: > raise OperationalError, "can't rollback." ... This should be changed to something like this (untested): > class pgdbCnx: > > def __init__(self, cnx): > self.__cnx = cnx > self.__cache = pgdbTypeCache(cnx) > self.inTxn = False #NEW > try: > src = self.__cnx.source() # No BEGIN here > except: > raise OperationalError, "invalid connection." > ... > def commit(self): > try: > src = self.__cnx.source() > src.execute("COMMIT") > self.inTxn = False # Changed > except: > raise OperationalError, "can't commit." > > def rollback(self): > try: > src = self.__cnx.source() > src.execute("ROLLBACK") > self.inTxn = False # Changed > except: > raise OperationalError, "can't rollback." ... > def cursor(self): > try: > src = self.__cnx.source() > return pgdbCursor(src, self.__cache, self) # Added self > except: > raise pgOperationalError, "invalid connection." > ... > class pgdbCursor: > > def __init__(self, src, cache, conn): # Added conn > self.__cache = cache > self.__source = src > self.__conn = conn # New > self.description = None > self.rowcount = -1 > self.arraysize = 1 > self.lastrowid = None ... (execute calls executemany) ... > def executemany(self, operation, param_seq): > self.description = None > self.rowcount = -1 > > # first try to execute all queries > totrows = 0 > sql = "INIT" > try: > for params in param_seq: > if params != None: > sql = _quoteparams(operation, params) > else: > sql = operation > if not self.__conn.inTxn: # Added test > self.__source.execute('BEGIN') > self.__conn.inTxn = True > rows = self.__source.execute(sql) > if rows != None: # true is __source is NOT a DQL > totrows = totrows + rows > else: > self.rowcount = -1 I guess it would be even better if the executemany method checked that it was really a tranasction-initiating SQL statement, but that makes things a bit slower and more complicated, especially as I suspect that the driver premits several SQL statements separated by semicolon in execute and executemany. We really don't want to add a SQL parser to pgdb. Making all statements transaction-initiating is at least much closer to standard behaviour than to *always* start transactions start prematurely. I guess it will remove problems like the one I mentioned earlier (repeated below) in more than 99% of the cases. This bug has implications far beyond timestamps. Imagine two transaction running with isolation level set to e.g. serializable. Transaction A updates the AMOUNT column in various rows of table X, and transaction B calculates the sum of all AMOUNTs in X. Lets say they run over time like this, with | marking transaction start and > commit (N.B. ASCII art follows, you need a fixed font to view this): ...|--A-->.......|--A-->........ ...........|-B->.........|-B->.. This works as expected... The first B-transaction sums up AMOUNTs after the first A-transaction is done etc, but imagine what happens if transactions implicitly begin too early as with the current pgdb: |-----A-->|---------A-->|------- |------------B->|----------B->|- This will cause B1 to sum up AMOUNTs before A1, and B2 will sum up AMOUNTs after A1, not after A2. From oren.tirosh at gmail.com Tue Jun 14 06:53:36 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 14 Jun 2005 03:53:36 -0700 Subject: ElementTree Namespace Prefixes References: <1118680405.635415.110740@f14g2000cwb.googlegroups.com> Message-ID: <1118746416.416870.266940@g49g2000cwa.googlegroups.com> > you forgot > > http://effbot.org/zone/element-infoset.htm > > which describes the 3-node XML infoset subset used by ElementTree. No, I did not forget your infoset subset. I was comparing it with other infoset subsets described in various XML specifications. I agree 100% that prefixes were not *supposed* to be part of the document's meaning back when the XML namespace specification was written, but later specifications broke that. Please take a look at http://www.w3.org/TR/xml-c14n#NoNSPrefixRewriting "... there now exist a number of contexts in which namespace prefixes can impart information value in an XML document..." "...Moreover, it is possible to prove that namespace rewriting is harmful, rather than simply ineffective." From mrmaple at gmail.com Wed Jun 15 10:39:28 2005 From: mrmaple at gmail.com (James Carroll) Date: Wed, 15 Jun 2005 10:39:28 -0400 Subject: dynamic In-Reply-To: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> References: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> Message-ID: Returning instances of some other class is not so horrible. They're called FactoryMethods usually. An example is when you have a polymorphic tree of image file reader objects, and you open an image file, it might return a JpegReader which ISA ImageReader or a TIFFReader which also ISA ImageReader, but you want all of the 'which class do I need for this data?' logic to be in one place. -Jim On 15 Jun 2005 03:12:07 -0700, Michele Simionato wrote: > Having a class that returns instances > of some other class is horrible, but > since you asked for it: > > class A(object): pass > class B(object): pass > > class Foo(object): > def __new__(cls, arg): > if arg=="a": > return A() > else: > return B() > > print Foo("a") > print Foo("b") > > Michele Simionato > > P.S. don't do it! > > -- > http://mail.python.org/mailman/listinfo/python-list > > From python at rcn.com Mon Jun 20 04:26:23 2005 From: python at rcn.com (Raymond Hettinger) Date: 20 Jun 2005 01:26:23 -0700 Subject: Why is there no instancemethod builtin? References: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> <1119197146.922190.38000@g44g2000cwa.googlegroups.com> <1119201221.143713.8890@z14g2000cwz.googlegroups.com> <1119202546.388847.114650@g14g2000cwa.googlegroups.com> Message-ID: <1119255983.409159.175480@g49g2000cwa.googlegroups.com> [George Sakkis] > The fact that strings don't have __iter__ is an implementation > detail. I can't think of any reason other than historic and perhaps > backwards compatibility for this; > iterables should IMHO by definition be exactly > the objects with __iter__). There would be no benefit other than satisfying that particular world view. It is a feature that all sequences are automatically iterable without having to write a custom __iter__ method. That makes life a bit easier for writers of sequence-like classes. [Michele Simionato] > I think strings do not have __iter__ on purpose, exactly to > distinguish them from other iterables, since sometimes it is nice > to consider them atomic, but I am not sure of this. You should > ask the developers. That is not correct. Since any sequence is automatically iterable (because of the presence of __getitem__), the inclusion of a separate __iter__ method is purely optional. The option to include a custom __iter__ method has been exercised only when it has offered some performance benefit. IOW, the inclusion of __iter__ for a sequence is an arbitrary implementation detail -- there is no other significance. > Anyway, the right definition of iterable is > (as I was told) "an object X such that iter(X) does not throw an > exception". Objects following the __getitem__ protocol >- such as strings -are iterables even if they do not have >an __iter__ method. An object is iterable if and only if it provides either __iter__ or __getitem__. Raymond From flupke at nonexistingdomain.com Mon Jun 6 18:54:46 2005 From: flupke at nonexistingdomain.com (flupke) Date: Mon, 06 Jun 2005 22:54:46 GMT Subject: poker card game revisited (code included) Message-ID: Hi, i've included the code so interested people can take a look. I've tried to expand on the thread of 26/05/2005 on "Checking for a full house". Code is suboptimal as I coded it rather quickly. I've added the "normal" classes one would expect from a cardgame: card, deck, hand etc. 1. I can detect most things except a straightflush. The problem with the code now is that it only returns 1 straight which is enough for mere "straight" detection but won't suffice for hand comparison and especially detecting straight flushes. For use in straight flush detection, the function would need to return all possible straights and then these would need to be checked to see if they are flushes. For instance a list [4,4,5,5,6,7,8] yields 4 different straights. A hand like [4,4,5,5,6,7,8,9] gets even worse. I can't see how i can do this using sets, i'll need to come up with another method since the suit is important. 2. Hand comparison. For this to succeed the getrank function would need to return the exact 5 cards that represent the highest hand. This could be less than 5 cards if one uses wildcards. Then you not only have the correct rank but also the highest hand so you can compare in case there are ties. 3. x wild. For games like "deuces wild", what would be the best way to manage those? I tought about removing them from a hand before shipping it of to the getrank function? Any ideas? Regards, Benedict Verheyen ===================== CODE ===================== """ Attempt for a poker cardgame representation Benedict Verheyen Code additions from web (http://www.ibiblio.org/obp/thinkCSpy/) and newsgroup comp.lang.python esp. Raymond Hettinger """ import random class Card(object): """ Represents a single card 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace """ suitList = ["Clubs", "Diamonds", "Hearts", "Spades"] rankList = [ "narf", "narf", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"] def __init__(self, suit=0, rank=0): """ Initialise a card @type suit: int @param suit: suit of the card (see suitList) @type rank: int @param rank: rank of the card (see rankList) """ self.suit = suit self.rank = rank def __str__(self): """ Pretty print a card """ return self.rankList[self.rank] + " of " + self.suitList[self.suit] def __cmp__(self, other): """ Compare 2 cards @type other: card @param other: the card to compare with """ # check the suits if self.suit > other.suit: return 1 if self.suit < other.suit: return -1 # suits are the same... check ranks if self.rank > other.rank: return 1 if self.rank < other.rank: return -1 # ranks are the same... it's a tie return 0 class Deck(object): """ Represents a deck of cards. We can have different decks of cards """ DECK_NORMAL = 1 # 52 cards def __init__(self,decktype=DECK_NORMAL): """ Makes a deck of cards @type decktype: type of deck @param decktype: what type of deck is it? (DECK_NORMAL,...) """ self.cards = [] for suit in range(4): for rank in range(2, 15): self.cards.append(Card(suit, rank)) def printdeck(self): """ Pretty print the deck """ for card in self.cards: print card def __str__(self): """ Pretty print the deck """ s = "" for i in range(len(self.cards)): s = s + " "*i + str(self.cards[i]) + "\n" return s def sort(self,rank=True,suit=False): """ Sort the deck """ def sortonrank(x,y): if x.rank > y.rank: return 1 if x.rank < y.rank: return -1 return 0 def sortonsuit(x,y): if x.suit > y.suit: return 1 if x.suit < y.suit: return -1 return 0 def sortonboth(x,y): return cmp(x,y) if ( rank == True and suit == False): self.cards.sort(sortonrank) elif ( suit == True and rank == False ): self.cards.sort(sortonsuit) else: self.cards.sort(sortonboth) # roept sort van card op def shuffle(self,nshuffle=1): """ Shuffle the deck of cards. This happens by swapping cards @type nshuffle: int @param nshuffle: how many times do we shuffle """ import random nCards = len(self.cards) # swap cards on place i and j for shuffle in range(nshuffle): print " shuffle %s " % shuffle for i in range(nCards): j = random.randrange(i, nCards) [self.cards[i], self.cards[j]] = [self.cards[j], self.cards[i]] def removecard(self, card): """ Removes a card from the deck. Do not use this function if you want to keep playing with the same deck afterwards! @type card: card @param card: card you want to remove """ if card in self.cards: self.cards.remove(card) return 1 else: return 0 def removecardindex(self,index): """ Remove a card at the given index. You get the card so you can return it to the deck later """ if ( index >= 0 and index <= len(self) ): return self.cards.pop(index) def addcard(self,card): """ Add the card back to the bottom of the deck @type card: card @param card: card you want to add to the deck """ self.cards.append(card) def popcard(self): """ Get the top card and deal it """ return self.cards.pop() def isempty(self): """ Is the deck empty? """ return (len(self.cards) == 0) def deal(self, hands, ncards=999): """ Deal a number of cards to the hands. ncards are dealt to each hand. @type hands: list @param hands: list of hands to deal to @type ncards: int @param ncards: number of cards to deal to each hand """ nhands = len(hands) for hand in hands: for i in range(ncards): if self.isempty(): break # break if out of cards card = self.popcard() # take the top card # hand = hands[i % nhands] # whose turn is next? hand.addcard(card) # add the card to the hand # print " deal card %s to %s " % (card,hand) def __len__(self): """ How many cards are there in the deck? """ return len(self.cards) class Hand(Deck): """ A hand is a kind of deck that contains cards """ def __init__(self, name=""): """ Make a hand of cards @type name: string @param name: hand belongs to person with this name """ self.cards = [] self.name = name """ def addcard(self,card) : self.cards.append(card) """ def __str__(self): """ Pretty print the hand """ s = "Hand " + self.name if self.isempty(): s = s + " is empty\n" else: s = s + " contains\n" return s + Deck.__str__(self) class CardGame(object): """ A card game """ def __init__(self): """ Start a card game by taking a deck of cards and shuffling it """ self.deck = Deck() self.deck.shuffle() class Rank(object): def __init__(self,rnk,name): self.rnk = rnk self.name = name def __str__(self): return self.name class HandComparator(object): pass class HandEvaluator(object): RANK_NOTHING = Rank(1,"High card") RANK_PAIR = Rank(2,"Pair") RANK_DOUBLEPAIR = Rank(3,"Double Pair") RANK_THREEOFAKIND = Rank(4,"Three of a Kind") RANK_STRAIGHT = Rank(5,"Straight") RANK_FLUSH = Rank(6,"Flush") RANK_FULLHOUSE = Rank(7,"Full House") RANK_FOUROFAKIND = Rank(8,"Four of a Kind") RANK_STRAIGHTFLUSH = Rank(9,"Straight Flush") RANK_FIVEOFAKIND = Rank(10,"Five of a Kind") def __init__(self): print "Ready to evaluate hands" def is_straight(self,hand,numwildcards=0): """Checks for a five card straight Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games). Outputs: highest card in a five card straight or 0 if not a straight. Original list is not mutated. Ace can also be a low card (i.e. A2345). >>> is_straight([14,2,3,4,5]) 5 >>> is_straight([14,2,3,4,6]) 0 >>> is_straight([10,11,12,13,14]) 14 >>> is_straight([2,3,5], 2) 6 >>> is_straight([], 5) 14 >>> is_straight([2,4,6,8,10], 3) 12 >>> is_straight([2,4,4,5,5], 2) 6 """ hand = set(hand) if 14 in hand: hand.add(1) for low in (10,9,8,7,6,5,4,3,2,1): needed = set(range(low, low+5)) if len(needed & hand) + numwildcards >= 5: lhand = [x for x in hand] ind = lhand.index(low+4) str = lhand[ind-4:ind+1] return low+4 return -1 def is_group(self,hand,numwildcards=0): """Checks for pairs, threes-of-kind, fours-of-a-kind, and fives-of-a-kind Inputs: list of non-wildcards plus wildcard count 2,3,4, ... 10, 11 for Jack, 12 for Queen, 13 for King, 14 for Ace Hand can be any length (i.e. it works for seven card games) Output: tuple with counts for each value (high cards first) for example (3, 14), (2, 11) full-house Aces over Jacks for example (2, 9), (2, 7) two-pair Nines and Sevens Maximum count is limited to five (there is no seven of a kind). Original list is not mutated. >>> groups([11,14,11,14,14]) [(3, 14), (2, 11)] >>> groups([7, 9, 10, 9, 7]) [(2, 9), (2, 7)] >>> groups([11,14,11,14], 1) [(3, 14), (2, 11)] >>> groups([9,9,9,9,8], 2) [(5, 9), (2, 8)] >>> groups([], 7) [(5, 14), (2, 13)] """ result = [] counts = [(hand.count(v), v) for v in range(2,15)] for count, value in sorted(counts, reverse=True): newcount = min(5, count + numwildcards) # Add wildcards upto five numwildcards -= newcount - count # Wildcards remaining if newcount > 1: result.append((newcount, value)) return result def is_flush(self,hand,numwildcards=0): result = [] counts = [(hand.count(v), v) for v in range(0,4)] for count, suit in sorted(counts, reverse=True): newcount = min(5, count + numwildcards) # Add wildcards upto five numwildcards -= newcount - count # Wildcards remaining if newcount >= 5: # we have a flush, return the flush suit # result.append((newcount, value)) return suit return -1 def is_straightflush(self,hand,numwildcards=0): return -1 def getrank(self,hand,numwildcards=0): result_group = None result_straight = None result_flush = None result_sf = None nrofresult = 0 rank = None cardranks = [card.rank for card in hand.cards] cardsuits = [card.suit for card in hand.cards] # check for groups result_group = self.is_group(cardranks,numwildcards) rank = self.__rankgroup(result_group) # if rank is lower than a four of a kind, a straight flush is # still better """ if (rank[0] < HandEvaluator.RANK_FIVEOFAKIND): result_sf = is_straightflush(hand """ # if rank is lower than a fullhouse, a flush might be higher if (rank[0] < HandEvaluator.RANK_FULLHOUSE): result_flush = self.is_flush(cardsuits,numwildcards) if ( result_flush > -1 ): return self.__rankflush(result_flush) # if rank is lower than a straight, it's useful to check for a # straight if (rank[0] < HandEvaluator.RANK_STRAIGHT): result_straight = self.is_straight(cardranks,numwildcards) if ( result_straight > -1 ): return self.__rankstraight(result_straight) # return the rank return rank def __namerank(self,rank): return Card.rankList[rank] def __namesuit(self,suit): return Card.suitList[suit] def __rankgroup(self,group): pair = 0 trips = 0 ranks = [] if (len(group) == 0 ): return (HandEvaluator.RANK_NOTHING,ranks) for count,rank in group: ranks.append(self.__namerank(rank)) if ( count >= 5 ): return (HandEvaluator.RANK_FIVEOFAKIND,ranks) elif ( count == 4 ): return (HandEvaluator.RANK_FOUROFAKIND,ranks) elif ( count == 3 ): trips += 1 elif ( count == 2 ): # can lead to a double pair # check to see if we have a next pair pair += 1 # Full house? if ( trips >= 2 ): return (HandEvaluator.RANK_FULLHOUSE,ranks) if ( trips == 1 and pair >= 1 ): return (HandEvaluator.RANK_FULLHOUSE,ranks) # Trips if ( trips >= 1 ): return (HandEvaluator.RANK_THREEOFAKIND,ranks) # Check for a pair or a double pair if ( pair >= 2 ): return (HandEvaluator.RANK_DOUBLEPAIR,ranks) elif ( pair == 1 ): return (HandEvaluator.RANK_PAIR,ranks) def __rankflush(self,suit): ranks = [] ranks.append(self.__namesuit(suit)) return (HandEvaluator.RANK_FLUSH,ranks) def __rankstraight(self,highcard): ranks = [] ranks.append(self.__namerank(highcard)) return (HandEvaluator.RANK_STRAIGHT,ranks) def getprintablerank(self,handeval): rank = handeval[0] cards = handeval[1] what = "" if ( rank == HandEvaluator.RANK_PAIR or rank == HandEvaluator.RANK_THREEOFAKIND or rank == HandEvaluator.RANK_FOUROFAKIND or rank == HandEvaluator.RANK_FIVEOFAKIND ): what = "%s of %s's " % (rank, cards[0]) elif ( rank == HandEvaluator.RANK_FULLHOUSE ): what = "%s, %s's over %s's" % (rank, cards[0], cards[1]) elif ( rank == HandEvaluator.RANK_DOUBLEPAIR ): what = "%s, %s's and %s's" % (rank, cards[0], cards[1]) elif ( rank == HandEvaluator.RANK_NOTHING ): what = "%s" % rank elif ( rank == HandEvaluator.RANK_STRAIGHT ): what = "%s, %s high" % (rank,cards[0]) elif ( rank == HandEvaluator.RANK_FLUSH ): what = "%s of %s" % (rank,cards[0]) return what if __name__ == "__main__": # Deal to 5 players, first 3 cards, then 1 and another 3 todeal = [] for hnd in range(0,5): todeal.append(Hand("Player %s" % (hnd + 1) )) d = Deck() d.shuffle(3) print " Dealing 2 cards to all players " d.deal(todeal,3) print " Dealing 1 cards to all players " d.deal(todeal,1) print " Dealing 2 cards to all players " d.deal(todeal,3) print " What are the hands of the players " ev = HandEvaluator() for hand in todeal: print "%s" % hand rank = ev.getrank(hand) print "%s" % ev.getprintablerank(rank) print "*"*40 print " What's left in the deck?" print "%s" % d print " %s cards left in the deck " % len(d) From gregpinero at gmail.com Wed Jun 29 07:06:16 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 29 Jun 2005 07:06:16 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: <1x6lpi6z.fsf@python.net> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> Message-ID: <312cfe2b050629040624d06a28@mail.gmail.com> I'd like to see some database API's to the most common databases included. It would make Python much more useful for web development. I've come across situations where a web host supports python and supports MySQL yet it's taken me days to get the MySQLAPI installed with running setup in my home directory etc. And I don't know what options you have if you don't have shell access? It definately seems to me that some API's to popular database would be conducive to a "batteries included" approach. -Greg On 6/29/05, Thomas Heller wrote: > Simon Brunning writes: > > > On 6/28/05, John Roth wrote: > >> I'd definitely like to see ctypes. I can agree with the segfault > >> issue, but I think that some design work would eliminate that. > > > > I'm not sure that it would. Ctypes allows you, as one colleague > > memorably put it, to "poke the operating system with a stick". You are > > always going to be able to use ctypes to provoke spectacular crashes > > of the kind that you can never get with 'ordinary' Python. > > Right. > > > Having said that, I'd like to see ctypes in the standard library > > anyway, with a suitably intimidating warning in the docs about the > > trouble you can get yourself into with it. > > To me, this sounds that *at least* a PEP would be needed to convince > Guido. Or, to record the reasoning why it cannot be included. > > Thomas > -- > http://mail.python.org/mailman/listinfo/python-list > From shama.bell at gmail.com Thu Jun 2 18:58:41 2005 From: shama.bell at gmail.com (shama.bell at gmail.com) Date: 2 Jun 2005 15:58:41 -0700 Subject: mac address Message-ID: <1117753121.178377.24110@g14g2000cwa.googlegroups.com> Hello, I am a newbie and i have problems filling an array with the mac address read from the command line. The mac address is FF:FF:FF:FF:FF:FF options, args = parser.parse_args() # options.d contains the address destAddress = options.d data = array('L', '\0' * 24) The array should contain the data as follows: data[0] = 0xFF data[1] = 0xFF ........ data[5] = 0xFF Any help is appreciated -SB From jmdeschamps at cvm.qc.ca Thu Jun 23 12:13:45 2005 From: jmdeschamps at cvm.qc.ca (jean-marc) Date: 23 Jun 2005 09:13:45 -0700 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: <1119540719.150128.66470@g14g2000cwa.googlegroups.com> References: <42b99d7b$0$21804$626a14ce@news.free.fr> <1119540719.150128.66470@g14g2000cwa.googlegroups.com> Message-ID: <1119543225.467923.166300@g44g2000cwa.googlegroups.com> Singletoned wrote: > Rocco Moretti wrote: > > Steven D'Aprano wrote: > > > > That's the joys of a mostly self-taught programming knowledge: you miss > > > out on all the buzzwords. > > > > Being mostly self taught myself, I have a tendancy to use infrequently > > encountered terms in related but technically inappropriate contexts, > > confusing the better informed people I deal with. ;-) > > Indeed. I find I use even more buzzwords because I can just make up as > many as I want. This thread 'branch' (humm, is this an appropriate term for the last few quotes, going to Steven's?) is soothing in reminding us we are not alone. That there is a sort of distributed 'Alma Mater' of the 'Teach-It-Yourself School of Computing', producing a virtual FOAF group (Is FOAF, Friend Of A Friend or Flock Of A Feather?) jm From rune.strand at gmail.com Mon Jun 27 23:01:45 2005 From: rune.strand at gmail.com (Rune Strand) Date: 27 Jun 2005 20:01:45 -0700 Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: <1119927705.432472.65820@z14g2000cwz.googlegroups.com> Brett Hoerner wrote: > Another problem with cmd.com is when I run IPython, if I have an error, > or tab or anything, I get the speaker beep (ala linux) but I can't find > a way to turn it off. This is a huge problem because I cannot disable > my system speaker on my laptop (not even in BIOS like my old one, and > it's an "error", it bypasses the fact that all my sound is muted in > Windows) and I get incredibly loud beeps all the time (because I suck) > which would not be acceptable while I'm coding on the sly in boring > class. I know that problem... it's extremely annoying! Here's one way to solve it; 1. Start 'Device manager'. 2. On the menu, click 'View' and check off "Show hidden devices" 3. Locate 'Beep' 'under Non-Plug and Play Drivers' 4. Right-click 'Beep', select 'Disable' From darkpaladin79 at hotmail.com Thu Jun 30 23:43:00 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 30 Jun 2005 23:43:00 -0400 Subject: How to run commands in command line from a script In-Reply-To: Message-ID: Alright well I'm quite a noob and when I run a simple command to change the current directory, nothing happens. I made a little test script to show it: import os cwd = os.getcwd() print cwd os.system('cd = C:\Program Files') print cwd then the result: C:\Python24\Python Scripts C:\Python24\Python Scripts The cd never changed. . . Can somebody explain this? I think I need to add something simple, i didnt quite get the example ' os.system('./some --command') ' -Ivan >From: Robert Kern >To: python-list at python.org >Subject: Re: How to run commands in command line from a script >Date: Thu, 30 Jun 2005 20:01:29 -0700 > >Ivan Shevanski wrote: > > I know there is an easy way to do this, and I just can not remember. I >have > > already searched where I thought the module would be. . . I just want to >run > > some name specific commands. Is this easily possible? > >Quick and dirty: > > import os > os.system('./some --command') > >More robust: Use the subprocess module. > >-- >Robert Kern >rkern at ucsd.edu > >"In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter > -- _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From dotpyFE at gmail.com Thu Jun 9 19:46:16 2005 From: dotpyFE at gmail.com (Lucas Raab) Date: Thu, 09 Jun 2005 23:46:16 GMT Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: Terry Reedy wrote: > "wooks" wrote in message > news:1118336828.878458.202840 at z14g2000cwz.googlegroups.com... > > > Perhaps you have never seen a newgroup ruined by commercial announcements > like I have. > > Terry J. Reedy > > > O wise one, we bow to you with your deep knowledge. -- -------------------------- Lucas Raab lvraab"@"earthlink.net dotpyFE"@"gmail.com AIM: Phoenix11890 MSN: dotpyfe "@" gmail.com IRC: lvraab ICQ: 324767918 Yahoo: Phoenix11890 From littlejohn.75 at news.free.fr Thu Jun 23 04:44:18 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 23 Jun 2005 08:44:18 GMT Subject: os.system(cmd) isn't working References: <3hv2j3Fit96kU1@individual.net> Message-ID: <42ba7661$0$31769$636a15ce@news.free.fr> Le Thu, 23 Jun 2005 01:19:11 -0500, Paul Watson a ?crit : > "Gregory Pi?ero" wrote in message > news:mailman.787.1119499378.10512.python-list at python.org... > Hi guys, > > I'm trying to run this statement: > > os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' > "www.blendedtechnologies.com"') > > The goal is to have firefox open to that website. I suggest to use the subprocess module. You don't have insert " around a path with embedded spaces and you can give the exact executable pathname, set the directory for the child process, etc import os import os.path import subprocess path_exe = r'C:\Program Files\Mozilla Firefox\firefox.exe' assert os.path.exists(path_exe) url = "http://www.blendedtechnologies.com" child = subprocess.Popen( (path_exe, url), executable = path_exe) rc = child.wait() > I'm using Python 2.3 on Windows XP pro service pack 2. I think that subprocess is a new Python2.4 module, but you should be able to find a 2.3 version (perhaps effbot.org) > > I'd greatly appriciate any help. From dalke at dalkescientific.com Mon Jun 6 16:46:38 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 06 Jun 2005 20:46:38 GMT Subject: the python way? References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> <3gjksrFcmvf4U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > To make it short, my version is: > > import random > def reinterpolate2(word, vocals='aeiouy'): > wlist = list(word) > random.shuffle(wlist) > vees = [c for c in wlist[::-1] if c in vocals] > cons = [c for c in wlist[::-1] if c not in vocals] Why the [::-1]? If it's randomly shuffled the order isn't important. > short, long = sorted((cons, vees), key=len) > return ''.join(long[i] + short[i] for i in range(len(short))) + ''.join(long[len(short):]) All the cool kids are using 2.4 these days. :) Another way to write this is (assuming the order of characters can be swapped) N = min(len(short), len(long)) return (''.join( [c1+c2 for (c1, c2) in zip(cons, vees)] + cons[N:] + vees[N:]) The main change here is that zip() stops when the first iterator finishes so there's no need to write the 'for i in range(len(short))' If the order is important then the older way is if len(cons) >= len(vees): short, long = vees, cons else: short, long = cons, vees return (''.join( [c1+c2 for (c1, c2) in zip(short, long)] + long[len(short):]) 'Course to be one of the cool kids, another solution is to use the roundrobin() implementation found from http://www.python.org/sf/756253 from collections import deque def roundrobin(*iterables): pending = deque(iter(i) for i in iterables) while pending: task = pending.popleft() try: yield task.next() except StopIteration: continue pending.append(task) With it the last line becomes return ''.join(roundrobin(short, long)) Anyone know if/when roundrobin() will be part of the std. lib? The sf tracker implies that it won't be. Andrew dalke at dalkescientific.com From kay.schluehr at gmx.net Fri Jun 10 16:06:01 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Jun 2005 13:06:01 -0700 Subject: Dealing with marketing types... In-Reply-To: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <1118431497.113944.261450@z14g2000cwz.googlegroups.com> flyingfred0 wrote: > A small software team (developers, leads and even the manager when he's > had time) has been using (wx)Python/PostgreSQL for over 2 years and > developed a successful 1.0 release of a client/server product. > > A marketing/product manager has brought in additional management and > "architecture" experts to propose moving the entire thing to a Java > (application server) platform for the next release. They want a > "scalable, enterprise solution" (though they don't really know what that > means) and are going crazy throwing around the Java buzzwords (not to > mention XML). The product managers and technology responsibles ( marketing people do less technology decisions at least in those german companys I know from inside ) may not know which is the "best" technology on the market ( who really knows? ), but he clearly knows the discourse about technology and he is right in not spending to much trusts in the sensitivities, vanities and the pets of his developers ( Some like dotNet, others like Java. Some believe that Perl is the hit and others stick to "Ruby on Rails".) > The developers (including myself) are growing uneasy; the management is > continuing to push their requirements and ignore the engineers. I think > there's still hope, but I'm at a loss for ideas beyond pointing out the > success stories of Python and Zope and language comparisons between > Python and Java. The difference between J2EE and Zope may be that SUN promotes it's new major releases half a year before they enter the market ( EJB3 ) while Zope 3 ( Zope X3 to be accurate ) vanishes for half a year after it is released ( if you read the docs e.g. the 'roadmap' in the Zope 3 wiki you may have the impression the project is completely dead ). > What experiences have those in the Python community had in these kinds > of situations? Python projects are submarines. You have to care not to go up to soon. Kay From myles at geocities.com Mon Jun 27 19:56:05 2005 From: myles at geocities.com (Myles Strous) Date: 27 Jun 2005 16:56:05 -0700 Subject: FlashMX and Py2exe doesn't fly... References: <1119910271.719937.101370@g43g2000cwa.googlegroups.com> Message-ID: <1119916565.394691.190190@z14g2000cwz.googlegroups.com> Grooooops wrote: > Flash and Python could be a VERY powerful pair of tools for building > quick apps, Yet I don't see much on the web about it. > > I was excited to see that it is possible to make them play together > here: > http://www.klaustrofobik.org/blog/archives/000235.html > > Unfortunately, these folks seem to have gotten stuck on compiling the > py files to exe, and since I don't see reference to it anywhere else, I > was wondering if anyone here knew why it didn't work, or if anyone had > ideas about how to make it work. They seem to have fixed it (haven't tried it myself) in a later discussion: see http://www.klaustrofobik.org/blog/archives/000236.html Regards, Myles. From steve at REMOVETHIScyber.com.au Sat Jun 25 21:49:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 11:49:21 +1000 Subject: Favorite non-python language trick? References: Message-ID: On Sat, 25 Jun 2005 15:44:14 -0400, Nicolas Fleury wrote: > Steven D'Aprano wrote: >> One of the things I liked in Pascal was the "with" keyword. You could >> write something like this: >> >> with colour do begin >> red := 0; blue := 255; green := 0; >> end; >> >> instead of: >> >> colour.red := 0; colour.blue := 255; colour.green := 0; >> >> Okay, so maybe it is more of a feature than a trick, but I miss it and it >> would be nice to have in Python. >> > > With PEP343 (I guess in Python 2.5), you will be able to do something like: > with renamed(colour) as c: > c.red = 0; c.blue = 255; c.green = 0 > > I think however it is bad. Better solutions to me would be: > > colour.setRgb(0, 255, 0) But that is no help, because the setRgb method will be implemented as def setRgb(r, g, b): self.red = r; self.green = g; self.blue = b which is exactly the usage case for a with statement: def setRgb(r, g, b): with self: .red = r; .green = g; .blue = b > or > > c = myVeryLongNameColour > c.red = 0; c.blue = 255; c.green = 0 Namespace pollution. It might not matter if c is a temporary variable inside a function or method, but it does matter if your top-level code is full of such constructs. Or for that matter, your interactive Python session. -- Steven. From http Wed Jun 1 14:40:25 2005 From: http (Paul Rubin) Date: 01 Jun 2005 11:40:25 -0700 Subject: creating a hex value References: <1285743.rKB6TKaXDy@teancum> Message-ID: <7xbr6pzzs6.fsf@ruckus.brouhaha.com> David Bear writes: > I'm not seeing it in my python essential ref. how can I do > > delim = 0x15 delim = chr(0x15) From user at unknown.invalid Thu Jun 2 20:18:03 2005 From: user at unknown.invalid (Koncept) Date: Thu, 02 Jun 2005 20:18:03 -0400 Subject: REQ: Small Perl to Python conversion needed Message-ID: <020620052018031433%user@unknown.invalid> Howdie Python folks! I am very new to Python ( 3rd day now ) and it has already earned its place as my fav. language to work in. I hope to continue, and I really would appreciate some good resources if anybody would care to contribute. My current head-scratcher concerns something I can do in Perl which I would like to have duplicated for Python. I have noticed that it is not possible to increment an unset value in Python, so I would like to know how to duplicate the following bit of code using Python dictionaries. #!/usr/bin/perl # Parse comma delimited lines and create a final frequency hash # Real example would read a file line by line my %dict = {}; my @lines = ( "1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5" ); foreach(@lines) { map( $dict{ $_ }++, split( "," ) ); } foreach( sort byKeys keys %dict ) { print "Key: $_\tFrequency: ", "*" x $dict{ $_ }, "\n" if $dict{ $_ } =~ /\d+/g; } sub byKeys { $dict{$b} <=> $dict{$a} } __DATA__ Results: Key: 5 Frequency: ***** Key: 4 Frequency: **** Key: 3 Frequency: *** Key: 2 Frequency: ** Key: 1 Frequency: * -- Koncept << "The snake that cannot shed its skin perishes. So do the spirits who are prevented from changing their opinions; they cease to be a spirit." -Nietzsche From sjmachin at lexicon.net Thu Jun 2 18:52:06 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 08:52:06 +1000 Subject: Performance Issues please help In-Reply-To: References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> <1117723908.636248.302410@g14g2000cwa.googlegroups.com> Message-ID: <429F8D96.5000105@lexicon.net> Michael Spencer wrote: > minc, minr, maxc, maxr = box[e] > # note correction for c == 0 > # also Peter's simplification > box[e] = ( c and (c < minc and c or minc), > minr, > c > maxc and c or maxc, > r) > This may be slightly faster (when c > 0), and slightly less opaque: minc, minr, maxc, maxr = box[e] # note correction for c == 0 # also Peter's simplification if c < minc: minc = c box[e] = ( minc, minr, c > maxc and c or maxc, r) From leo at lspace.org Fri Jun 10 03:56:55 2005 From: leo at lspace.org (Leo Breebaart) Date: 10 Jun 2005 07:56:55 GMT Subject: Sending mail from 'current user' in Python Message-ID: <3gsve7Fe8957U1@individual.net> I am writing a utility in Python and I'd like to add a command-line option "--mailto
" that will cause an e-mail summary to be sent to
when the utility finishes running. My first thought was to use smtplib.sendmail(), and basically this works like a charm, except that this function expects a valid 'sender' address as a parameter. Every single smtplib example I've found so far shows a hardcoded 'sender' address, but as my utility can be run by any user on any system I am looking for a way to obtain or create a valid default value. I can get the username info (at least on Unix) via the 'pwd' module, but that still leaves me with the domainname, or rather the mailname, and I have not been able to spot a way of finding that from within Python. (I could try opening /etc/mailname by hand, but how standard is that filename/location?) I've also tried opening a pipe to sendmail, and feeding the message to that instead. This too works great (and does give an appropriate default 'From'), but that also turns my problem into the problem of finding the location of the sendmail program, which doesn't seem like much of an improvement, portability-wise. Finally, if at all possible I'd also like to get this working on Windows, so I'd rather stick with the standard smtplib if I can. Does anybody here have any thoughts on this? -- Leo Breebaart From rkern at ucsd.edu Fri Jun 24 06:03:38 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 24 Jun 2005 03:03:38 -0700 Subject: A tool for Python - request for some advice In-Reply-To: <1119606284.258828.233250@g14g2000cwa.googlegroups.com> References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> <42B7C93B.4030306@po-box.mcgill.ca> <1119606284.258828.233250@g14g2000cwa.googlegroups.com> Message-ID: TPJ wrote: > I've heard about this "EasyInstall" and I like this idea. > > If EI becomes a part of Python's standard library, my script will use > it. Why wait? Just make it the second thing that the script installs after Python itself. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tendengarci at yahoo.com Thu Jun 9 19:16:38 2005 From: tendengarci at yahoo.com (tendengarci at yahoo.com) Date: 9 Jun 2005 16:16:38 -0700 Subject: inactive Spambayes w/ Outlook Message-ID: <1118358998.183038.192940@g14g2000cwa.googlegroups.com> I had installed spambayes with outlook 2003 a while ago and it worked great. Then I did who know what it stopped working. I would click on the 'delete spambayes' toolbar icon but nothing would happen. I clicked on the 'spambayes' icon for options but nothing happened. I uninstalled and reinstalled a number of times with no luck. I just downloaded and installed version 1.1a1 and still no luck. I would love to get this working again. Thanks, I appreciate your help john From sbucking at gmail.com Thu Jun 9 09:01:48 2005 From: sbucking at gmail.com (sbucking at gmail.com) Date: 9 Jun 2005 06:01:48 -0700 Subject: splitting strings with python In-Reply-To: References: <1118308380.823382.146430@g47g2000cwa.googlegroups.com> Message-ID: <1118322108.179956.62480@f14g2000cwb.googlegroups.com> one problem is that str1 is unicode (japanese kanji), and str2 is japanese kana can i still use re.findall(~)? thanks for your help! From guy.lateur at b-b.be Tue Jun 14 06:33:39 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 14 Jun 2005 10:33:39 GMT Subject: Where is Word? References: Message-ID: <7oyre.120385$tQ6.6542490@phobos.telenet-ops.be> Thank you very much; I'll check that out shortly. g "Tim Golden" schreef in bericht news:mailman.431.1118745058.10512.python-list at python.org... OK, a slightly more intelligent idea in place of my previous one. You can use win32api.ShellExecute (from the pywin32 extensions) which is like a beefed-up os.startfile. In particular, it allows you to pass parameters to the command. So... import win32api win32api.ShellExecute ( 0, # hwnd "open", # action; could be "print" etc. "winword.exe", # application "c:/temp/temp.txt", #params ".", # working directory 1 # show/don't show ) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kkylheku at gmail.com Mon Jun 20 15:38:06 2005 From: kkylheku at gmail.com (Kaz Kylheku) Date: 20 Jun 2005 12:38:06 -0700 Subject: references/addrresses in imperative languages In-Reply-To: References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: <1119296285.996667.84480@g43g2000cwa.googlegroups.com> Walter Roberson wrote: > In article <1119220461.626477.56110 at g49g2000cwa.googlegroups.com>, > Xah Lee wrote: > >In hindsight analysis, such language behavior forces the programer to > >fuse mathematical or algorithmic ideas with implementation details. A > >easy way to see this, is to ask yourself: how come in mathematics > >there's no such thing as "addresses/pointers/references". > > There is. Each variable in predicate calculas is a reference. > No matter how large the formulae, a change in a variable > is, in mathematics, immediately propagated to all occurances > of the variable (potentially changing the references of other > variables). Variables don't change in mathematics, at least the run-of-the-mill everyday mathematics. :) > If the predicate calculas variables were not equivilent to references, > then the use of the variable in a formula would have to be a > non-propogating copy. and a change to the original value whence not > be reflected in all parts of the formula and would not change > what the other variables referenced. > > Consider for example the proof of Goedel's Incompleteness > theorem, which involves constructing a formula with a free > variable, and constructing the numeric encoding of that > formula, and then substituting the numeric encoding in as > the value of the free variable, thus ending up with > a number that is "talking about" iteelf. All these substitutions ``work'' in a way that is analogous to functional programming. For example, substituting a variable into a formula generates a new formula with occurences of that variable replaced by the given value. You haven't destroyed the old formula. > The process of > the proof is *definitely* one of "reference" to a value > in the earlier stages, with the formula being "evaluated" > at a later point -- very much like compiling a program > and then feeding the compiled program as input to itelf. Actually no. The process specifically avoids the pointer problem by using an arithmetic coding for the formula, the Goedel numbering. The formula talks about an encoded version of itself. That's how the self-reference is smuggled in, via the Goedel numbering. > You > cannot do it without a reference, because you need to > have the entire number available as data at the time > you start evaluating the mathematical formula. The final result just /is/ self-referential. It's not constructed bit by bit like a data structure inside a digital computer that starts out being non-self-referential and is then backpatched to point to itself. A mathematical derivation may give you the idea that something is changing in place, because you always hold the most recent version of the formula at the forefront of your mind, and can visualize the whole process as a kind of in-place animation in your head. But really, at each step you are making something completely new which stands on its own. From vinodmap at gmail.com Fri Jun 24 22:34:06 2005 From: vinodmap at gmail.com (vm) Date: 24 Jun 2005 19:34:06 -0700 Subject: http POST only returning GET data Message-ID: <1119666846.766429.68550@f14g2000cwb.googlegroups.com> Hi, for some reason my POST is not working properly. I am basically just trying to get a simple stock quote from yahoo by posting the ticker symbol (GE as an example) into finance.yahoo.com. However, when I POST, I do get a response back, but it is just the main page finance.yahoo.com and it doesn't seem as if the POST got through. I am using Python 2.2. I get a status and reason of 200 and OK respectively. I've searched through these groups on previous POST problems, but none have seemed to help so far. Any help would be greatly appreciated, or if there is a previous post that describes this same problem, please let me know. In addition, when I change the headers from back and forth between "multipart/form-data" and "application/x-www-form-urlencoded", there seems to be no change. How do I know which Content-type to use for each page. When I look at the Content-type on the yahoo page, it says "text/html; charset=iso-8859-1" -- but if I enter this in, I get other errors. How do I know which Content-type to use when I pass it as headers? Thank you very much. ###################################################### import urllib,httplib url = "finance.yahoo.com" fields = { "s": "ge" } params = urllib.urlencode(fields) ##headers = {"Content-type": "application/x-www-form-urlencoded", ## "Accept":"text/plain"} headers = {"Content-type": "multipart/form-data", "Accept":"text/plain"} httpSess = httplib.HTTPConnection(url) httpSess.request("POST","/",params,headers) response = httpSess.getresponse() print "status=%s, reason=%s" % (response.status,response.reason) data = response.read() print "OUTPUT = \n\n%s\n\n" % data ###################################################### From steven.bethard at gmail.com Fri Jun 17 18:40:56 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Jun 2005 16:40:56 -0600 Subject: Why is there no instancemethod builtin? In-Reply-To: References: Message-ID: John Reese wrote: > I now do: > > if isinstance(x, list): > > It is my understanding that this is what people do nowadays. I wouldn't go that far. I don't have an isinstance check for lists anywhere in my entire codebase. Why do you think you need to check to see if something is of type list? Why don't you just use it as needed, and find out, e.g.: try: itr = iter(x) except TypeError: # do whatever you need to do if it's not iterable else: # do whatever you need to do if it *is* iterable STeVe From david.baelde at ens-lyon.fr Thu Jun 9 06:58:12 2005 From: david.baelde at ens-lyon.fr (David Baelde) Date: Thu, 09 Jun 2005 12:58:12 +0200 Subject: Abstract and concrete syntax References: <11af9le2v96r1ac@news.supernews.com> Message-ID: Well, thanks for the answers. I guess the fact is that python does not want to be a functional programming language. This concept is quite large, and since there is a proper notion of function with closure, I'd say python is already quite a functional programming language. Even if assignations and side effects are used all the time (which makes python easier to learn than a stricter functional programming language in my opinion). I agree that statements as expressions could allow obscure code. But it's so more beautiful concept, makes things simpler to understand! Moreover, doing this would have kept backward compatibility. Anyway, I guess it's dead. The design of programming languages is a complicated thing... __ David From brian at zope.com Sun Jun 5 12:15:09 2005 From: brian at zope.com (Brian Lloyd) Date: Sun, 5 Jun 2005 12:15:09 -0400 Subject: Announce: Python for .NET 1.0 RC2 released Message-ID: Hi all - I'm happy to announce the release of Python for .NET 1.0 RC2. You can download it from: http://www.zope.org/Members/Brian/PythonNet Highlights of this release: - Changed some uses of Finalize as a static method name that confused the Mono compiler and people reading the code. Note that this may be a breaking change if anyone was calling PythonEngine.Finalize(). If so, you should now use PythonEngine.Shutdown(). - Tweaked assembly lookup to ensure that assemblies can be found in the current working directory, even after changing directories using things like os.chdir() from Python. - Fixed some incorrect finalizers (thanks to Greg Chapman for the report) that may have caused some threading oddities. - Tweaked support for out and ref parameters. If a method has a return type of void and a single ref or out parameter, that parameter will be returned as the result of the method. This matches the current behavior of IronPython and makes it more likely that code can be moved between Python for .NET and IP in the future. - Refactored part of the assembly manager to remove a potential case of thread-deadlock in multi-threaded applications. - Added a __str__ method to managed exceptions that returns the Message attribute of the exception and the StackTrace (if available). Thanks to all who have sent in issue reports, patches and suggestions for this and past releases. Enjoy! ;) Brian Lloyd brian at zope.com V.P. Engineering 540.361.1716 Zope Corporation http://www.zope.com From hancock at anansispaceworks.com Thu Jun 9 11:00:04 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 9 Jun 2005 10:00:04 -0500 Subject: (OT) lincense protection generator In-Reply-To: <3ADD2CE9-7EE9-44E3-A2BC-5C341DAD15E2@curi.us> References: <3ADD2CE9-7EE9-44E3-A2BC-5C341DAD15E2@curi.us> Message-ID: <200506091000.04092.hancock@anansispaceworks.com> On Thursday 02 June 2005 05:46 pm, Elliot Temple wrote: > Why not check if all files you use are in appropriate directories, > but not worry about same computer? This is pretty trivial, by the way --- just use dirlist recursively, use tuples, and hash the result. All you want is an idiot-proof tamper tag --- you aren't trying to defend against malice. As for which computer is in use --- when I was doing tech support, I provided a command for registering for tech support which called "uname" to automatically collect machine information. It would've been easy enough to set this up as the standard way to contact tech support. Most likely you are working with Windows clients, so you'll need something other than "uname", but I'm sure there is something appropriate. You can do it by examining information in Python's sys module, too, which I think should be portable. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From cpunerd4 at gmail.com Sat Jun 18 10:31:32 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 07:31:32 -0700 Subject: extreme newbie In-Reply-To: References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: <1119105092.240065.224910@g44g2000cwa.googlegroups.com> what I mean by secure is that no one can steal the code. I want to create comercial applications eventually. (although I will work on open source I hope, so don't get mad at me) and calling me cpunerd4 will be fine. From Oyvind.Ostlund at cern.ch Tue Jun 14 11:35:39 2005 From: Oyvind.Ostlund at cern.ch (Oyvind Ostlund) Date: Tue, 14 Jun 2005 17:35:39 +0200 Subject: Using httplib to read a file online Message-ID: <9D1BA87B48D4F440A0D9E371471F45A51BF741@cernxchg21.cern.ch> I am trying to read a file online, and was just testing a bit. This is what I tried. -------------------------------------- import sys, httplib showlines = 6 try: servername, filename = sys.argv[1:] # cmdline args? except: servername, filename = 'noteme.com', '/index.php' print servername, filename server = httplib.HTTP(servername) # connect to httpsite/server server.putrequest('GET', filename) # send request andheaders server.putheader('Accept', 'text/html') # POST requests workhere too server.endheaders() # as do cgi script file names errcode, errmsh, replyheader = server.getreply() # read reply info headers if errcode != 200: # 200 means success print 'Error sending request', errcode print 'Message', errmsh print 'RepHeader', replyheader else: file = server.getfile() # file obj for data received data = file.readlines() file.close() # show lines with eolnat end for line in data[:showlines]: print line, # to save, write datato file ----------------------------- There is a server called noteme.com and a file called index.php on it, but why doesn't it work. If I changed it to 'vbforums.com' and 'index.php' then it worked. What is the difference? Anyone have a qlue?'' Thanks in advance - ?? - From bdesth.quelquechose at free.quelquepart.fr Mon Jun 13 16:23:39 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 13 Jun 2005 22:23:39 +0200 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: <42ade58b$0$25394$636a15ce@news.free.fr> Andrea Griffini a ?crit : (snip) > What I know is that every single competent programmer > I know (not many... just *EVERY SINGLE ONE*) started > by placing firmly concrete concepts first, and then > moved on higher abstractions (for example like > structured programming, OOP, functional languages ...). I don't know if I qualify as a "competent programmer" (you'd have to ask my co-workers), but I started with hi-level scripting languages, event-driven programming, and OO. Only then did I learn lower-level languages (C, Pascal, and bits of 68k assembly). Being familiar with fondamental *programming* concepts like vars, branching, looping and functions proved to be helpful when learning C, since I only had then to focus on pointers and memory management. From doodle4 at gmail.com Wed Jun 1 16:05:39 2005 From: doodle4 at gmail.com (ashtonn@gmail.com) Date: 1 Jun 2005 13:05:39 -0700 Subject: using builtin array References: <1117641183.057537.118020@z14g2000cwz.googlegroups.com> Message-ID: <1117656339.288904.23360@f14g2000cwb.googlegroups.com> I am constructing a packet, with the first 6 bytes being the destination address, followed by src, and type. The remaining space will be filled with data. I need to use an array because of the buffer_info method i am calling. -SB From rkern at ucsd.edu Tue Jun 28 15:48:40 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 28 Jun 2005 12:48:40 -0700 Subject: Set/Get attribute syntatic sugar In-Reply-To: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: Peter Hansen wrote: > ???? ???????? wrote: > >>There is a syntactic sugar for item access in >>dictionaries and sequences: >> >>o[e] = v <-> o.__setitem__(e, v) >>o[e] <-> o.__getitem__(e) >> >>where e is an expression. >> >>There is no similar way for set/get attribute for objects. >>If e is a given name, then >> >>o.e = v <-> o.__setattr__(e, v) >>o.e <-> o.__getattr__(e) >> >>Anybody thought about this issue? > > Perhaps not, but now that you've pointed it out they've taken the time > machine back and fixed the problem before it arose: > > >>> class C: > ... def __setattr__(self, e, v): > ... print 'setting %s to %s' % (e, v) > ... self.__dict__[e] = v > ... > >>> o = C() > >>> v = 'mystring' > >>> o.e = v > setting e to mystring > >>> o.e > 'mystring' > >>> I think he means something like this: e = 'i_am_an_attribute' o.(e) = 10 o.i_am_an_attribute == 10 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From flupke at nonexistingdomain.com Wed Jun 8 05:03:48 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 08 Jun 2005 09:03:48 GMT Subject: poker card game revisited (code included) In-Reply-To: References: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> Message-ID: Erik Max Francis wrote: > flupke wrote: > >> Which projects are you talking about? I only found a library in c to >> evaluat ranks but i didn't find the code to be very understandable. > > > pokersource is the main was I was thinking about, yes. > >> With histogram do you mean something like this: >> Card hand: 2 clubs, 3 diamonds, 10 of diamonds, 4 of hearts, 3 of hearts >> >> Histogram 1: list [2,3,4,10] >> 2 --------------------- 14 >> Histogram 2: list [1,2,1,0,0,0,0,0,1,0,0,0,0] >> or >> list [1,2,1,1] >> so index 0 is count of rank at index 0 of Histogram 1 >> index 1 is count of rank at index 1 of Histogram 1 > > > Histograms usually involve putting things in bins and counting the > number by bin. Here the bins are just the ranks of the cards, and so > you're counting the frequency of the ranks. Once that's done, you want > to arrange the frequencies into a mapping of its own, which points to > the list of ranks that have that frequency. That way you can easily > pick things off: If there is a hit in the four bin, you have quads. If > there's a hit in the three bin and either another in the three or one in > the two bin, you have a boat. If there's a hit in the three bin but > _not_ another in three or two, then it's trips. And so on. > >> As for straights, if i understand correctly, you make all possible >> straights of the cards in the hand and then see if one matches? > > > Not quite. You break down the cards by what matters -- ranks and suits > -- and then make sets based on these. Then, standing by, you have the > sets of valid straights (by rank), and then to test for straights, you > iterate through the straight sets and make intersections with the rank > set for the hand in question. If the intersection is the same as the > straight set, then it's a straight. (Do this by reverse order of the > relative values of the straights, and stop when you find the first one, > to get the highest straight.) The most efficient way to do this is with > a bitmask, so that's how it's usually done. > Thanks for the info. I succeeded in doing a straight flush check yesterday but not using the method described. My code works now but using bitmasks might actually be faster to use for hand detection and comparison. I'm not sure that it will be easier to read and understand the code though. I'll play a bit with bitmasks and see what gives. Thanks, Benedict From jan.danielsson at gmail.com Mon Jun 6 18:52:16 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Tue, 07 Jun 2005 00:52:16 +0200 Subject: Creating file of size x In-Reply-To: <56qdnYcDS9f3TDnfRVn-tw@speakeasy.net> References: <42a4cea6$1@griseus.its.uu.se> <56qdnYcDS9f3TDnfRVn-tw@speakeasy.net> Message-ID: <42a4d256$1@griseus.its.uu.se> Erik Max Francis wrote: >> Is there any way to create a file with a specified size? > > What do you want to put in the file? Once you've answered that > question, the solution should present itself. Check blocks from an FEC-encoder (Freenet, more specifically). The problem is that the design I'm working on won't guarantee what order the blocks will be returned in -- so I need to be able to seek to block n's location and write the ckeck block. Next block could be m, where m < n. So, they aren't continous. From steven.bethard at gmail.com Sat Jun 25 18:49:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Jun 2005 16:49:09 -0600 Subject: python-dev Summary for 2005-06-01 through 2005-06-15 Message-ID: [The HTML version of this Summary is available at http://www.python.org/dev/summary/2005-06-01_2005-06-15.html] ===================== Summary Announcements ===================== --------------------------------- Bug Day: Saturday, June 25th 2005 --------------------------------- AMK organized another `Python Bug Day`_ on Saturday, June 25th. Hope you got a chance to help out! .. _Python Bug Day: http://wiki.python.org/moin/PythonBugDay Contributing Threads: - `Bug day on the 25th? `__ [SJB] ---------------------- FishEye for Python CVS ---------------------- Peter Moore has kindly set up `Fish Eye for the Python CVS repository`_. FishEye is a repository browsing, searching, analysis and monitoring tool, with great features like RSS feeds, Synthetic changesets, Pretty ediffs and SQL like searches. Check it out! .. _Fish Eye for the Python CVS repository: http://fisheye.cenqua.com/viewrep/python/ Contributing Threads: - `FishEye on Python CVS Repository `__ [SJB] -------------------------------- PyPy Sprint: July 1st - 7th 2005 -------------------------------- The next `PyPy`_ sprint is scheduled right after EuroPython 2005 in Gothenborg, Sweden. It will focus mainly on translating PyPy to lower level backends, so as to move away from running PyPy on top of the CPython interpreter. There will be newcomer-friendly introductions, and other topics are possible, so if you have any interest in PyPy, now is the time to help out! .. _PyPy: http://codespeak.net/pypy Contributing Threads: - `Post-EuroPython 2005 PyPy Sprint 1st - 7th July 2005 `__ [SJB] --------------------------------- Reminder: Google's Summer of Code --------------------------------- Just a reminder that the friendly folks at Python have set up a `wiki`_ and a `mailing list`_ for questions about `Google's Summer of Code`_. For specific details on particular projects (e.g. what needs done to complete Python SSL support) participants may also ask questions to the Python-Dev list. .. _wiki: http://wiki.python.org/moin/CodingProjectIdeas .. _mailing list: http://mail.python.org/mailman/listinfo/summerofcode .. _Google's Summer of Code: http://code.google.com/summerofcode.html [SJB] ---------------------- hashlib Review Request ---------------------- Gregory P. Smith noted that he has finished up the hashlib work he started on a few months ago for patches `935454`_ and `1121611`_ (where the final patch is). He feels that the patch is ready, and would like anyone interested to review it; the patch incorporates both OpenSSL hash support and SHA256+SHA512 support in a single module. `The documentation`_ can be accessed separately, for convenience. .. _935454: http://python.org/sf/935454 .. _1121611: http://python.org/sf/1121611 .. _The documentation: http://electricrain.com/greg/hashlib-py25-doc/module-hashlib.html Contributing Threads: - `hashlib - faster md5/sha, adds sha256/512 support `__ [TAM] ========= Summaries ========= ---------------- PEP 343 Progress ---------------- The PEP 343 discussions were mostly concluded. Guido posted the newest version of the PEP to both Python-Dev and Python-List and the discussions that followed were brief and mostly in agreement with the proposal. The PEP 343 syntax was modified slightly to require parentheses if VAR is a comma-separated list of variables. This made the proposal forward-compatible to extending the with-block for multiple resources. In the favored extension, the with-block would take multiple expressions in a manner analogous to import statements:: with EXPR1 [as VAR1], EXPR2 [as VAR2], ...: BLOCK However, if this extension becomes part of Python, it will likely enter some time after Python 2.5, once users have a better idea of what with-block use-cases look like. There were also some brief discussions about how with-blocks should behave in the presence of async exceptions like the KeyboardInterrupt generated from a ^C. While it seemed like it would be a nice property for with-blocks to guarantee that the __exit__ methods would still be called in the presence of async exceptions, making such a guarantee proved to be too complicated. Thus the final conclusion, as summarized by Nick Coghlan, was that "with statements won't make any more guarantees about this than try/finally statements do". Contributing Threads: - `PEP 343 rewrite complete `__ - `For review: PEP 343: Anonymous Block Redux and Generator Enhancements `__ - `PEP 343 - next steps `__ - `PEP 343 question `__ [SJB] -------------- Do-While Loops -------------- Raymond Hettinger asked for a "dowhile" loop of the form:: dowhile : which would run once before testing the , and then proceed as a normal while-loop. He was subsequently referred to `PEP 315`_, which proposes a slightly different syntax for a similar purpose. The discussion expanded to not only do-while loops, but also loops with break conditions at locations other than the beginning and the end of a loop. A variety of syntax proposals were suggested, but none seemed compellingly better than the current syntax:: while True: ... if : break ... which supports putting the condition(s) at any location in the loop. .. _PEP 315: http://www.python.org/peps/pep-0315.html Contributing Threads: - `Wishlist: dowhile `__ [SJB] ------------------------------------ Reference Counting in Module Globals ------------------------------------ Both Michael Hudson and Skip Montanaro noticed that Py_INCREFs appeared to be unnecessary when adding an object to a module's globals. Armin Rigo explained that after a module is initialized, the import mechanism makes a "hidden" copy of the module's dict so that the module can be reloaded. This means that objects added as module globals will always have an extra reference count in this hidden dict. However, Armin Rigo agreed with Michael Hudson that this explanation was no longer applicable after an interpreter shutdown. The best conclusion he could draw in this a situation: "it's all quite obscure". Contributing Threads: - `refcounting vs PyModule_AddObject `__ - `[Python-checkins] python/dist/src/Modules _csv.c, 1.37, 1.38 `__ [SJB] ----------------------------------------- Reorganising the standard library (again) ----------------------------------------- The ever-popular topic of reorganising the standard library came up again this fortnight, courtesy of Reinhold Birkenfeld. The questions posed included hierarchy (flat/nested), third party modules, size (batteries included or not), and the standard GUI toolkit. As usual, there was a great deal of discussion, but not a great deal of consensus about any of these (other than that including ElementTree in the standard library would be good), and given the amount of breakage this would involve (and that Guido didn't weigh in at all), it seems unlikely that much will change before Python 3000; although Josiah Carlson indicated that he had a patch that would avoid a lot of breakage. Contributing Threads: - `Thoughts on stdlib evolvement `__ [TAM] -------------------------- First Mac-tel, now Py-tel? -------------------------- Guido mentioned that Intel has a free (as in beer) C `compiler for Linux`_, and that a friend of his (who is involved in its production and marketing) would like to see how it performs with Python. The compiler wasn't news to some of the -dev crowd, though, with Martin v. L?wis pointing out a `bug report on the compiler`_, as well as a `patch`_, and a `message indicating that some people had problems`_ with the resulting interpreter. Martin pointed out that there were some old (2002 and 2004) results indicating that the Intel compiler was slightly faster, but couldn't find any results for the latest version. Michael Hoffman gave summaries of more testing, which gave a 16% speed increase. He felt that, while this was significant, he wasted a lot of time dealing with resulting problems with extension modules, and so it doesn't use as much any more. .. _compiler for Linux: http://www.intel.com/software/products/compilers/clin/index.htm .. _bug report on the compiler: http://python.org/sf/1162001 .. _patch: http://python.org/sf/1162023 .. _message indicating that some people had problems: http://mail.python.org/pipermail/python-list/2005-March/270672.html Contributing Threads: - `Compiling Python with Intel compiler? `__ [TAM] ------------------ sys.path Behaviour ------------------ Reinhold Birkenfeld noticed that sys.path's first element is '' in interactive sessions, but the directory containing the script otherwise, and wondered if this was intentional. Guido clarified that he's always liked it this way, so that if you use os.path.join to join it with a script name you don't get a spurious ".\" preprended. The "absolutizing" of sys.path entries, however, is reasonably new; Bob Ippolito pointed out that is also `problematic with regards to path hooks`_. He has a `patch to fix it`_, but hasn't had a chance to commit it; Phillip J. Eby noted that the patch doesn't fix completely fix it, however, and indicated that fixing site.py with respect to `PEP 302`_ will be quite challenging. .. _problematic with regards to path hooks: http://mail.python.org/pipermail/python-dev/2005-April/052885.html .. _patch to fix it: http://python.org/sf/1174614 .. _PEP 302: http://python.org/peps/pep-0302.html Contributing Threads: - `sys.path in interactive session `__ [TAM] ---------------- More on old bugs ---------------- The discussion about what to do with old bugs continued this fortnight. Against the concern about prematurely closing old bugs, there was the suggestion that given that there are such a huge number of open bug reports, and since closed bugs can be reopened, this wasn't such a problem. It was suggested that the act of closing a bug might trigger activity to get it fixed, if necessary. The thread died off before a consensus was reached, unfortunately. Contributing Threads: - `Closing old bugs `__ [TAM] --------------------------------- Improved pseudo-switch statements --------------------------------- Skip Montanaro has been playing around with getting the Python compiler to recognize switch-like statements and generate O(1) code out of them. The rules are that the object being compared ('x') can be any expression, but must be precisely the same in each elif clause, the comparison operator must be "==", and the right-hand-side of the test must evaluate to a simple hashable constant. However, if evaluating 'x' has side-effects, then this would break code. Various people felt that it was unwise to allow 'x' to be any expression; Anthony Baxter suggested that one could allow any local object that didn't define a comparison operator. Contributing Threads: - `Multiple expression eval in compound if statement? `__ [TAM] =============== Skipped Threads =============== - `Adventures with Decimal `__ - `Weekly Python Patch/Bug Summary `__ - `AST manipulation and source code generation `__ - `Vestigial code in threadmodule? `__ - `[Python-checkins] python/dist/src/Lib sre_compile.py, 1.57, 1.58 `__ - `Split MIME headers into multiple lines near a space `__ - `python running in several threads `__ - `problem installing current cvs `__ - `b32encode and NUL bytes `__ - `Example workaround classes for using Unicode with csv module... `__ - `Weekly Python Patch/Bug Summary `__ - `[Python-checkins] python/dist/src/Doc/lib libtokenize.tex, 1.5, 1.6 `__ - `Five patch reviews & patch request `__ - `AIX 4.3, Python 2.4.1 fails in test_exceptions with a core dump `__ - `PEP 342 - Enhanced Iterators `__ - `A bug in pyconfig.h under Linux? `__ - `Dynamic class inheritance && something else `__ - `Weekly Python Patch/Bug Summary `__ ======== Epilogue ======== ------------ Introduction ------------ This is a summary of traffic on the `python-dev mailing list`_ from June 01, 2005 through June 15, 2005. It is intended to inform the wider Python community of on-going developments on the list on a semi-monthly basis. An archive_ of previous summaries is available online. An `RSS feed`_ of the titles of the summaries is available. You can also watch comp.lang.python or comp.lang.python.announce for new summaries (or through their email gateways of python-list or python-announce, respectively, as found at http://mail.python.org). This is the fifth summary written by the python-dev summary cabal of Steve Bethard, Tim Lesher, and Tony Meyer. To contact us, please send email: - Steve Bethard (steven.bethard at gmail.com) - Tim Lesher (tlesher at gmail.com) - Tony Meyer (tony.meyer at gmail.com) Do *not* post to comp.lang.python if you wish to reach us. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to advance the development and use of Python. If you find the python-dev Summary helpful please consider making a donation. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation with a credit card, check, or by PayPal helps. -------------------- Commenting on Topics -------------------- To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! ------------------------- How to Read the Summaries ------------------------- The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation for new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. Please note that this summary is written using reStructuredText_. Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it. I do suggest learning reST, though; it's simple and is accepted for `PEP markup`_ and can be turned into many different formats like HTML and LaTeX. Unfortunately, even though reST is standardized, the wonders of programs that like to reformat text do not allow me to guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _c.l.py: .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _PEP Markup: http://www.python.org/peps/pep-0012.html .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. _last summary: http://www.python.org/dev/summary/ .. _original text file: http://www.python.org/dev/summary/2005-06-01_2005-06-15.ht .. _archive: http://www.python.org/dev/summary/ .. _RSS feed: http://www.python.org/dev/summary/channews.rdf From Sebastien.Boisgerault at gmail.com Wed Jun 15 09:06:14 2005 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 15 Jun 2005 06:06:14 -0700 Subject: FAQ: __str__ vs __repr__ References: <42b021ba$1@griseus.its.uu.se> Message-ID: <1118840774.643768.218300@o13g2000cwo.googlegroups.com> Jan Danielsson a ?crit : > Sorry, but I Just Don't Get It. I did search the 'net, I did read the > FAQ, but I'm too dumb to understand. > > As far as I can gather, __str__ is just a representation of the > object. ... yep, and this representation is built for human eyes. Don't worry too much if it does not display every bit of information contained in your object. Pretty printing rules ... >>> str(0.1) 0.1 >>> str("it's a bad idea") "it's a bad idea" > However, I don't understand what __repr__ should be. It is an *exact* (if possible) description of the object's content, nicely packaged into a string. >>> repr(0.1) 0.10000000000000001 >>> repr("it's a bad idea") '"it\'s a bad idea"' > There's a phrase > in the documentation which makes it highly confusing for a beginner like > me: "If at all possible, this should look like a valid Python expression > that could be used to recreate an object with the same value (given an > appropriate environment).". It means that the equality eval(repr(x)) == x should hold. Cheers, SB From jepler at unpythonic.net Mon Jun 27 12:11:33 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 27 Jun 2005 11:11:33 -0500 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: <11c02rpkqriad6c@news.supernews.com> References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <3i9jdvFkhd21U1@individual.net> <11c02rpkqriad6c@news.supernews.com> Message-ID: <20050627161133.GD30048@unpythonic.net> On Mon, Jun 27, 2005 at 08:21:41AM -0600, John Roth wrote: > Unfortunately, I've seen that behavior a number of times: > no output is None, one output is the object, more than one > is a list of objects. That forces you to have checks for None > and list types all over the place. maybe you can at least push this into a single convenience function... def destupid(x, constructor=tuple, sequencetypes=(tuple, list)): if x is None: return constructor() if isinstance(x, sequencetypes): return x return constructor((x,)) Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From grante at visi.com Tue Jun 28 23:09:56 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Jun 2005 03:09:56 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c3c3uipbjcg58@corp.supernews.com> <11c3cib5nv1d65a@corp.supernews.com> Message-ID: <11c4484kb40jc76@corp.supernews.com> On 2005-06-28, Jarek Zgoda wrote: > Grant Edwards napisa?(a): > >>>>>To be blunt, I have no idea what this has to do with Python. >>>>Monty Python was mostly Brits? >>> >>>Wasn't they all Brits? >> >> Nope. Terry Gilliam was from Minneapolis. > > Are you sure there are no Brits in Minneapolis? There are plenty of Brit's in Minneapolis. My favorite radio DJ is one of them. Perhap's Gilliam has lived in Britain long enough to be considered a Brit, but he was born in Minneapolis, graduated from College in LA, and didn't move to Britain until he was something like 27. I believe he has British citizenship, so if that's the criterion, he's a Brit now. However, back when he was in Monty Python, he'd only lived in England for few years. -- Grant Edwards grante Yow! How's it going in at those MODULAR LOVE UNITS?? visi.com From rkern at ucsd.edu Mon Jun 27 17:45:49 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 27 Jun 2005 14:45:49 -0700 Subject: rsync protocol in python In-Reply-To: <4046073.1XfbebpUv1@teancum> References: <4046073.1XfbebpUv1@teancum> Message-ID: David Bear wrote: > I was wondering if anyone has implemented the rsync protocol in python. GIYF. http://directory.fsf.org/pysync.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tracy at reinventnow.com Mon Jun 6 14:32:31 2005 From: tracy at reinventnow.com (tracyshaun) Date: 6 Jun 2005 11:32:31 -0700 Subject: idiom for constructor? References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <1118082751.402682.314720@g14g2000cwa.googlegroups.com> How about just doing this: class Foo(object): __slots__ = ('a','b','c','d') def __init__(self, *args): for (name, arg) in zip(self.__slots__, args): setattr(self, name, arg) --T From greg at puyo.cjb.net Tue Jun 7 04:27:23 2005 From: greg at puyo.cjb.net (Greg McIntyre) Date: 7 Jun 2005 01:27:23 -0700 Subject: the python way? In-Reply-To: <1118127739.226122.280830@g47g2000cwa.googlegroups.com> References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> <1118127739.226122.280830@g47g2000cwa.googlegroups.com> Message-ID: <1118132843.634917.216350@g14g2000cwa.googlegroups.com> I like this solution. For some reason it made me want to write a Ruby version of it. Possibly something about the title and the fact that Ruby enthusiasts are always going on about "the Ruby way". VOWELS = 'aeiouy'.split('') def reinterpolate(word) letters = word.split('').sort_by{rand} vowels = letters.find_all{|l| VOWELS.include?(l) } consonants = letters - vowels return vowels.zip(consonants).map{|v, c| "#{c}#{v}" }.join('') end puts reinterpolate("encyclopedias") From tim.golden at viacom-outdoor.co.uk Thu Jun 30 06:42:03 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Jun 2005 11:42:03 +0100 Subject: Control Printer Queue On Windows 2000/XP Message-ID: <9A28C052FF32734DACB0A288A3533991EBB95D@vogbs009.gb.vo.local> [binarystar] | Hi folks, | | I am writing a script to print a few thousand pdf documents and I need | to have some control over the number of jobs that are sent to the | printer queue at time ... something along the lines of | | if number_jobs > MAX_JOBS: | time.sleep(10) | else: | #Print More Files | | | I have been investigating the win32print utility | http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32 | /win32print.html | | ... but can not see how to get print queue information eg the | number of | jobs pending .. atleast my attempts are failing Assuming I understand the need, you can do something like this with WMI: import wmi c = wmi.WMI () print len (c.Win32_PrintJob ()) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From lambacck at gmail.com Wed Jun 22 21:18:03 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Wed, 22 Jun 2005 21:18:03 -0400 Subject: Detect windows shutdown In-Reply-To: <4660fe300506221801765dc76f@mail.gmail.com> References: <4660fe300506221801765dc76f@mail.gmail.com> Message-ID: There is an event that win32 sends to each thread to tell it to shut down. You can grab that with the win32all extension (I am not on windows right now so I can't look it up in the documentation). -Chris On 6/22/05, Konstantin Veretennicov wrote: > On 6/22/05, Austin wrote: > > My program is running on windows and it is wrritten by Python and wxPython, > ... > > Is there any way to dectect windows shutdown or reboot? > > Will wx.EVT_END_SESSION or wx.EVT_QUERY_END_SESSION help? > > - kv > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From fuzzyman at gmail.com Wed Jun 29 14:55:32 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jun 2005 11:55:32 -0700 Subject: Inheriting from object Message-ID: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> Hello, To create a classic (old style) class, I write : class foo: pass To do the equivalent as a new style class, I write : class foo(object): pass *Should* I in fact write : class foo(object): def __init__(self, *args, **kwargs): object.__init__(self) ? Also, can anyone explain any tangible benefit of inheriting from object, when not explicitly using any features of new style classes ? Thanks :-) Fuzzyman http://www.voidspace.org.uk/python From fredrik at pythonware.com Thu Jun 2 06:17:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 2 Jun 2005 12:17:41 +0200 Subject: creating a hex value References: <1285743.rKB6TKaXDy@teancum> Message-ID: David Bear wrote: >I have a file that I need to parse. Items in it are delimited by a hex 15 > (0x015). I know it must be trivial to assign a hex value to a variable but > I'm not seeing it in my python essential ref. how can I do > > delim = 0x15 > while: > ln = file.read() > if ln[0] == delim: > do something > > I've looked at the hex function but it doesn't sound like what I want. you can use use ord(ln[0]) == delim or ln[0] == '\x15' or ln[0] == chr(delim) or ln.startswith("\x015") or some other variation. fwiw, I'm pretty sure file.read() doesn't do what you want either (unless you're 100% sure that the file only contains a single item). if the file isn't larger than a few megs, consider using items = file.read().split("\x15") From steve at REMOVEMEcyber.com.au Tue Jun 14 00:15:21 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Tue, 14 Jun 2005 14:15:21 +1000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: <42AE59D9.7010704@REMOVEMEcyber.com.au> D H wrote: > But what you are getting at is more akin to our mental model of what the > computer is doing when we write and run a program. Without a > fundamental understanding of memory and addresses, a programmer can make > certain mistakes that reveal this lack of understanding. But that > doesn't mean they have to learn about memory management at the very > beginning of their instruction. Finally somebody who gets it :-) Every home handyman needs to know the difference between a claw hammer and a tack hammer and rubber hammer, and why you shouldn't use a claw hammer to knock dints out of steel sheeting, but they don't need to learn them all on the first time they look at a nail. I'm reminded about the concept "lies for children", used by Ian Stewart and Jack Cohen (mathematician and biologist respectively) in some of their books. The point they make is that much of what we teach each other -- even adults -- is "lies for children". The Earth is not a sphere, even though we can often get away with pretending it is. High and low tides aren't caused by the moon. Testosterone doesn't cause aggression. DNA is not a blueprint. And adding two strings together is not a simple operation, despite appearances. "Lies for children" in this sense are not *bad*, they are a necessary step towards a more sophisticated understanding. Imagine trying to learn about projectile motion if you needed to understand general relativity and friction just to get started. Now imagine you are a ballistic missile scientist, and you assume that the problem of firing a missile from here to there is independent of the shape of the Earth's gravitional field, air resistance and relativity. You've just missed your target by a kilometre. Ooops. Learning when you can ignore implementation details is just as important a skill as learning how to use variables. Just as you wouldn't try teaching closures to people who haven't yet learnt what a function is, you don't want to bog people down with implementation details too early -- but if you don't teach them *at all*, you are creating second-class programmers who will write slow, buggy, hard-to-maintain code. -- Steven. From caseyhHAMMER_TIME at istar.ca Tue Jun 28 20:51:58 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Wed, 29 Jun 2005 00:51:58 GMT Subject: Newbie: Help Figger Out My Problem References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> <42c174ab$1@nntp0.pdx.net> <1119987053.884256.211190@g49g2000cwa.googlegroups.com> Message-ID: It may be shorter but it keeps the entire list in memory and has to iterate over the list twice! Does he/she need the entire list? import random heads = 0 flips = 1000000 for i in xrange(flips): if random.randint(0,1): heads += 1 print "Heads:%s" % heads print "Tails:%s" % (flips - heads) "Devan L" wrote: >import random >flips = 100 >results = [random.randint(0,1) for i in range(flips)] >heads = results.count(0) >tails = results.count(1) >print "Heads:%s" % heads >print "Tails:%s" % tails >I think this is more compact. -- Regards, Casey From david.reitter at gmail.com Fri Jun 10 15:43:26 2005 From: david.reitter at gmail.com (David Reitter) Date: Fri, 10 Jun 2005 20:43:26 +0100 Subject: match groups: optional groups not accessible In-Reply-To: <20050610123846.fc34s9m28y40ok08@login.werra.lunarpages.com> References: <20050610123846.fc34s9m28y40ok08@login.werra.lunarpages.com> Message-ID: <338488A2-55A9-471C-A2A9-4703E4563890@gmail.com> On 10 Jun 2005, at 20:38, Michael Chermside wrote: > David Reitter writes: > >> Why does the following result in an IndexError? >> > [...] > >>>>> import re >>>>> m = re.match('(?Pmaybe)?yes', "yes") >>>>> m.group(1) >>>>> m.group('maybe') >>>>> >> Traceback (most recent call last): >> File "", line 1, in ? >> IndexError: no such group >> > > Because the name of the named group in your example is 'm' not > 'maybe'. 'maybe' > is the text to match. Oh shoot! how couldn't i see this! thanks very much for pointing it out... - D From daniel.dittmar at sap.corp Wed Jun 29 09:37:46 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 29 Jun 2005 15:37:46 +0200 Subject: Python syntax high-lighting and preservation on web In-Reply-To: References: Message-ID: Gregory Pi?ero wrote: > Hey guys, > > Does anyone know where I can pick up a style sheet (css) and/or other > files/programs I might need to display python code on my website with > tab preservation(or replace with spaces) and colored syntax? I want > something similar to the python code on a page like this: see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 css only won't help you as someone has to insert the span tags so that the style sheet has something to match. Daniel From future_retro at yahoo.co.uk Wed Jun 22 08:15:23 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 22 Jun 2005 05:15:23 -0700 Subject: python create WMI instances In-Reply-To: References: Message-ID: <1119442523.795295.31210@g14g2000cwa.googlegroups.com> Create isn't a method of Win32_Printer so I couldn't get that to work. .Create is a method of Win32_Process which (wait for it..) creates a new process. Unfortunatly there is no method to add a printer. the method .AddPrinterConnection will allow me to add a connection to an existing print share but I want to create a printer with the option of sharing it. I think I'll have to do this with spawninstance. Tim Golden wrote: > [Marc Wyburn] > | > | Hi all, I am struggling with a vb - python code conversion. I'm using > | WMI to create printers on remote machines using (in VB); > | > | set oPrinter = oService.Get("Win32_Printer").SpawnInstance_ > | > | oPrinter.DriverName = strDriver > | oPrinter.PortName = strPort > | oPrinter.DeviceID = strPrinter > | oPrinter.Put_(kFlagCreateOnly) > | > | In python I have logged onto the WMI service on the remote machine and > | I can run things like c.new.AddPrinterConnection so I know that I am > | connected and working OK. I don't get any errors when I create a new > | object with SpawnInstance_ but when I try to set the value of > | oPrinter.Drivername I get an error saying that the Drivername object > | doesn't exist. Does anyone know how to set the values of the object > | using either the method above or with the WMI module? I think the WMI > | module only allows access to modify methods such ADDPrinterConnection > | or Create (from Win32_Service). > > Not sure if I can help here or not, but just in case... > > As far as I understand you, the fact that you're creating > on a remote machine is just an incidental, ie you'd have > the same problem doing this locally. > > Part of the problem is that when VB does something > like: > > oPrinter.DriverName = strDriver > > what's really happening behind the scenes is something > like: > > oPrinter.Properties_ ("DriverName").Value = strDriver > > Now you can do that in Python. (In fact, that's what > the wmi module does when it overrides __setattr__, followed > by a Put_). So if you want to translate code fairly literally, > then carry on as you were, but substitute the latter code for > the former. > > Having said that, the wmi module *can* create new instances > of classes. The problem is that I had/have little knowledge > of how WMI works in this area, so what I've done may not > be right. The method you're looking for is .new (aliased > as .new_instance_of) and if you use help on that method, > you'll get this: > > new(self, wmi_class) unbound wmi.WMI method > Create a new , typically something like > Win32_Process, eg: > > c = wmi.WMI ("remote_machine") > for p in c.Win32_Process (name="notepad.exe"): print p > c.new ("Win32_Process").Create (CommandLine="notepad.exe") > for p in c.Win32_Process (name="notepad.exe"): print p > p.Terminate () > for p in c.Win32_Process (name="notepad.exe"): print p > > Now this example works, but I notice from the code > that what I did to make it work was to remove the > SpawnInstance_ which I had, and replace it by an > instance retrieval. ie I just do a Get on the class. > > I'll try to find some examples around of what you're > doing which, up till now, I've not really needed to > do. Meanwhile, I hope the above info is of some use. > > Feel free to respond with questions or comments. This > can only get clearer! > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From cdkrug at worldnet.att.net Mon Jun 20 10:10:56 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Mon, 20 Jun 2005 14:10:56 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? References: <_ttte.94827$VH2.91696@tornado.tampabay.rr.com> Message-ID: On Mon, 20 Jun 2005 06:36:42 GMT, Ron Adam wrote: > Ron Adam wrote: > >> You might be able to use a dictionary of tuples. >> >> call_obj = {(type_obj1,0):obj1a, >> (type_obj1,0):obj1b, >> (type_boj2,1):obj2a, >> (type_obj2,1):obj2b, >> etc... } >> call_obj[(type_of_obj,order)]() >> >> >> Regards, Ron > > This won't work like I was thinking it would. > > But to get back to your is there a ? operator question... > > Try this. > > def foo(): > return "foo" > > def boo(): > return "boo" > > print (foo, boo)[1>0]() # prints "boo" > print (foo, boo)[1<0]() # prints "foo" > > Regards, > Ron Another thought: Often complicated conditional logic is a flag that we need to refactor. An accounting package I built has an official list of approved vendors, but allows users to provisionally add a new vendor, which is corrected later. The bulk of this system only understands, "This document has-a vendor" with a "vendor factory" that returns the appropriate type of vendor. All of the logic specific to the specific subclass is internal to the subclasses themselves. From ggrp1.20.martineau at dfgh.net Wed Jun 22 16:14:19 2005 From: ggrp1.20.martineau at dfgh.net (Martin Miller) Date: 22 Jun 2005 13:14:19 -0700 Subject: case/switch statement? References: <200506131204.40950.hancock@anansispaceworks.com> Message-ID: <1119471259.814294.225130@g14g2000cwa.googlegroups.com> Skip Montanaro wrote: > Terry> Yeah, and I find this even more so: > > Terry> case = { > Terry> 5: do_this, > Terry> 6: do_that, > Terry> } > Terry> case.get(x, do_default)() > > Terry> Which is looking pretty close to a case statement, anyway. > > Sure, modulo namespace issues. > > Skip The namespace issue alluded to doesn't exist when using the very similar approach suggested earlier in this thread by Andrew Durdin -- shown again below in a [very] contrived example illustrating access to the local namespace: greeting = "Hello there, " x = 2 exec { 1: """greeting += 'Tom'""", 2: """greeting += 'Dick'""", 3: """greeting += 'Harry'""", }.get(x, """greeting += 'Unknown'""") print greeting Martin From rbt at athop1.ath.vt.edu Mon Jun 6 16:39:43 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 06 Jun 2005 16:39:43 -0400 Subject: Destructive Windows Script In-Reply-To: References: Message-ID: Terry Reedy wrote: > "Dennis Lee Bieber" wrote in message > news:ioh7a1liqm1qpu0a1l0qmmb7n3gqehtl26 at 4ax.com... > >>My previous facility didn't even accept mil-spec wipes -- all >>disk drives leaving the facility had to go through a demagnitizer, > > > OT but I am curious: does a metallic case act as a metallic shield, so that > the case needs to be opened to do this? (Conversely, is a magnet near a > disk drive a danger to it?) Absolutely. Small HDD's (like laptops) are especially vulnerable to magnetic force. From gsakkis at rutgers.edu Mon Jun 20 13:37:05 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 20 Jun 2005 10:37:05 -0700 Subject: Back to the future - python to C++ advice wanted References: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> <1119081214.366589.119720@g43g2000cwa.googlegroups.com> Message-ID: <1119289025.622564.39020@g49g2000cwa.googlegroups.com> "Kay Schluehr" wrote: > I recommend studying C++ idioms carefully. > > http://www1.bell-labs.com/user/cope/Patterns/C++Idioms/EuroPLoP98.html Thanks for the link; very useful indeed. > If Georges starts on greenfields he may have a look at Qt and it's > object library which is not only concerned with widgets. > > http://doc.trolltech.com/3.3/ > > BOOST is more high brow and I guess that it compiles slow because it > uses templates extensively. Template metaprogramming as a compile time > language was a funny discovery. Here is some prove of it's > capabilities: > > http://osl.iu.edu/~tveldhui/papers/2003/turing.pdf Many thanks to Kay and Bruno for suggesting Boost; I browsed through its numerous libraries and they're quite impressive ! They seem indispensable, especially for python (or other very high level language) programmers going back to C++. Some libraries that seem to be very relevant to pythoneers are: - any: brings dynamic typing in C++ - tuple; 'nuff said - iterator: out-of-the-box equivalents of itertools.{imap,ifilter,izip,count}, reversed(), and others not existing or applicable in python - tokenizer, string_algo and regex: similar functionality to str.* and re.* - bind, mem_fn, function, functional, lambda: first class callables, currying, higher order (functional) programming - assign: syntactic sugar through operator overloading for (relatively) readable container initialization: map next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6); is actually valid and equivalent to next = dict([(1,2), (2,3), (3,4), (4,5), (5,6)]) - many, many more goodies, with or without respective standard python equivalent (threads, graphs, math utils, serialization, metaprogramming, etc). - and last but not least, Boost.Python. I don't think it's just a coincidence that among all languages they chose Python to make interoperable with C++ :-) Thanks again, George From could.net at gmail.com Mon Jun 27 21:29:29 2005 From: could.net at gmail.com (could ildg) Date: Tue, 28 Jun 2005 09:29:29 +0800 Subject: delphi to python converter In-Reply-To: <1119887129.5222.23.camel@localhost.localdomain> References: <1119887129.5222.23.camel@localhost.localdomain> Message-ID: <311b5ce1050627182932b57ba7@mail.gmail.com> The only thing you can do at present is to convert by yourself with hand, recode them line by line. On 6/27/05, Thys Meintjes wrote: > Greets, > > I have need of a Delphi/pascal to python converter. Googling didn't > suggest any obvious leads so I'm trying here... > > Thanks > Thys > > -- > http://mail.python.org/mailman/listinfo/python-list > From trentm at ActiveState.com Tue Jun 7 11:06:58 2005 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 7 Jun 2005 08:06:58 -0700 Subject: ANN: ActivePython 2.4.1 for Mac OS X is now available! Message-ID: <20050607150658.GB5985@ActiveState.com> Today ActiveState is announcing support for Mac OS X. I'm happy to announce that ActivePython 2.4.1 for Mac OS X is now available for free download from: http://www.ActiveState.com/Products/ActivePython/ This brings the number of free ActivePython platforms to four -- with the existing Linux, Solaris and Windows free downloads. Meanwhile, some of you may be interested to know that we are busily working on bringing Komodo to Mac OS X. We expect to offer a beta in August and release later this year. To keep up-to-date with our Mac OS X progress, betas and announcements, we invite you to join our new mailing list: osx-announce at ActiveState.com You can join the OS X announce list on the ActiveState Programmer Network (ASPN): http://listserv.activestate.com/mailman/listinfo/osx-announce What is ActivePython? --------------------- ActivePython is ActiveState's quality-assured binary distribution of Python. Builds for Linux, Mac OS X, Solaris and Windows are made freely available. ActivePython includes the Python core and core extensions (zlib 1.2.1, bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4) and is fully compatible with other Python distributions of the same version. ActivePython also includes a wealth of Python documentation, including: - the core Python docs; - Andrew Kuchling's "What's New in Python" series; - the Non-Programmer's Tutorial for Python; - Mark Pilgrim's excellent "Dive into Python"; and - a snapshot of the Python FAQs, HOWTOs and PEPs. Once installed on the Mac, you can find the ActivePython documentation here: /Library/Documentation/Help/ActivePython 2.4 Help/index.html An online version of the docs can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html Thanks, and enjoy! Trent, Python Tech Lead -- Trent Mick TrentM at ActiveState.com From nospam at here.com Tue Jun 14 10:37:12 2005 From: nospam at here.com (Matt Feinstein) Date: Tue, 14 Jun 2005 10:37:12 -0400 Subject: Problem with 'struct' module References: <11atq5o3sa0jt50@corp.supernews.com> Message-ID: <0pqta19omp5ev42ou299ir38itdv74rmri@4ax.com> On Tue, 14 Jun 2005 14:24:56 -0000, Grant Edwards wrote: > >Your example is not using standard alignment. It's using >native alignment: > > By default, C numbers are represented in the machine's native > format and byte order, and properly aligned by skipping pad > bytes if necessary (according to the rules used by the C > compiler). > > Alternatively, the first character of the format string can > be used to indicate the byte order, size and alignment of > the packed data, according to the following table: > > Character Byte order Size and alignment > @ native native > = native standard > < little-endian standard > > big-endian standard > ! network (= big-endian) standard > > If the first character is not one of these, "@" is assumed. > > Native byte order is big-endian or little-endian, depending > on the host system. For example, Motorola and Sun > processors are big-endian; Intel and DEC processors are > little-endian. > > Native size and alignment are determined using the C compiler's > sizeof expression. This is always combined with native byte > order. > > Standard size and alignment are as follows: no alignment is > required for any type (so you have to use pad bytes); short is > 2 bytes; int and long are 4 bytes; long long (__int64 on > Windows) is 8 bytes; float and double are 32-bit and 64-bit > IEEE floating point numbers, respectively. > > Note the difference between "@" and "=": both use native > byte order, but the size and alignment of the latter is > standardized. Thanks. I clearly missed the point of the explanation... Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From nothingcanfulfill at gmail.com Thu Jun 30 22:36:32 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 30 Jun 2005 19:36:32 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <1120185392.950869.317930@g14g2000cwa.googlegroups.com> Hmm...I think it's time I do better justice to what I previously wrote. http://www.artima.com/weblogs/viewpost.jsp?thread=98196 The above article was linked by Python's PEP... From newsgroups at jhrothjr.com Wed Jun 1 21:14:17 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 1 Jun 2005 19:14:17 -0600 Subject: prob with ActiveState and FireFox on Win32 (XP and W2K) References: <1117672027.924838.245780@g47g2000cwa.googlegroups.com> Message-ID: <119snbbsk7vur7c@news.supernews.com> "curtin" wrote in message news:1117672027.924838.245780 at g47g2000cwa.googlegroups.com... > hi, > i just downloaded the latest version of ActiveState's IDE (pywin 2.4.X) > and have noticed that i can't have firefox/ActiveState open at the same > time. if i try to create a 'new' script, the AS IDE blocks till i > tear down firefox. this is on an XP and W2K box. > > i did some digging on ActiveState's site, and googled but no luck. > > anyone see this before? Haven't seen it, but I do have a question: do you have Firefox extensions? If so, disable them and see if the problem persists. I certainly don't see it with PythonWin and Firefox. Of course, neither is the latest version, and I have no Firefox extensions. John Roth > > thanks, > > craig > From geert.van.muylem at utimaco.be Thu Jun 30 11:16:24 2005 From: geert.van.muylem at utimaco.be (geert.van.muylem at utimaco.be) Date: Thu, 30 Jun 2005 17:16:24 +0200 Subject: PyImport_Import fails on linux Message-ID: Hi all, I'm currently migrating an application from a windows platform to linux. I have somewhere a module which uses embedded python: (a python script where I want to call some functions...) // Initialize the python library Py_Initialize(); PyObject *pName = PyString_FromString("RASBatch"); // Load the Python module m_pModule = PyImport_Import(pName); if (m_pModule != NULL) { ... } else { ... } Loading the module always returns NULL... When starting python on the command line, I can import the python script and execute the function which i want to call from my C module. I've tried also copying the script on several locations... Anyone any idea? (Using python 2.2 on suse8.2) Thanks in advance! Geert -------------- next part -------------- An HTML attachment was scrubbed... URL: From rkern at ucsd.edu Fri Jun 10 18:02:38 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 10 Jun 2005 15:02:38 -0700 Subject: using python from c/c++ In-Reply-To: <20050610125615.oymplav2mj48g8wc@login.werra.lunarpages.com> References: <20050610125615.oymplav2mj48g8wc@login.werra.lunarpages.com> Message-ID: Michael Chermside wrote: > What would be quite nice would be a sort of inverse to SWIG... a > tool to mechanically create C wrappers around a Python program. I > haven't heard of such a beast, but perhaps someone else will write > in to point one out. And how! http://elmer.sourceforge.net -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From devlai at gmail.com Tue Jun 28 15:20:45 2005 From: devlai at gmail.com (Devan L) Date: 28 Jun 2005 12:20:45 -0700 Subject: regulars expressions ? In-Reply-To: <1119986016.228538.63930@g14g2000cwa.googlegroups.com> References: <42c18cc9$0$6342$636a15ce@news.free.fr> <1119986016.228538.63930@g14g2000cwa.googlegroups.com> Message-ID: <1119986445.170799.80540@o13g2000cwo.googlegroups.com> Oh, oops, sorry, that code doesn't respect the quotes. Use this code: re.findall(r'(".+?"|\S+)(?:,|$)', yourtexthere) From finite.automaton at gmail.com Thu Jun 9 16:48:34 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 9 Jun 2005 13:48:34 -0700 Subject: Any way to not create .pyc files? References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> <8cGdnaHABLhlEzXfRVn-oQ@powergate.ca> Message-ID: <1118350114.634141.95920@g49g2000cwa.googlegroups.com> > You didn't really describe the nature of the problem. Perhaps the whole > .pyc thing is a bit of a red herring, and the real problem lies > elsewhere? What are the actual symptoms of your problem? Yes, the .pyc thing could be a red herring. I was hoping to find an easy way to disable them to see if it mysteriously solved the problem. I apologize in advance: This is not going to be a satisfying answer. :( All that I know about the problem comes second-hand from the admins who encountered it. They didn't save any tracebacks or error messages or even screenshots (really helpful, I know). At one point last week, users started reporting that they were encountering problems running our Python application (the one that uses the package on the network drive). The admins noticed that lots of .pyc files had been inadvertantly created when someone with write access had run the application. The admins deleted all of the .pyc files, and users were once again able to run the application. I suspect this hadn't come up before because very few people have write access, and those who do are not usually users. I don't know the nature of the problems encountered. I have tried to recreate a scenario wherein .pyc files cause a problem (mostly by going through permutations of file permissions and remapping drives), but with no luck. I have asked the admins to intentionally recreate the situation so I can get more information, but it may take days for that to happen. I don't have write access to the network drive, so I can't do it myself. I'll post a follow-up when (if) I get more information. From roy at panix.com Sun Jun 12 08:11:47 2005 From: roy at panix.com (Roy Smith) Date: Sun, 12 Jun 2005 08:11:47 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42ABAB62.4040205@lexicon.net> Message-ID: John Machin wrote: > > I know I'm going out on a limb by asking this, but why do you think future > > software engineers should know about memory management? > > Perhaps we have a terminology problem here i.e. different meanings of > "software engineer". Philippe started talking about "CS" courses, > whereas you may be referring to people who have done an "IT" course or > achieved a certification in the use of app development tool X. No, you've missed the point entirely. No, the problem is that I'm out on the limb, and you're still comfortably standing on the ground leaning up against the trunk. Climb up and come out on the limb with me. Now, stop hugging the trunk and take a few steps out here with me. Don't worry about how it's swaying, and whatever you do, don't look down. The point I was trying to make was that as computer science progresses, stuff that was really important to know a lot about becomes more and more taken for granted. This is how we make progress. I used to worry about memory busses at the milivolt and microsecond level. I knew about termination impedances and wired-OR logic, and power budgets and all that good stuff. Today all I know about memory is you go to www.crucial.com, type in your Visa card number, and the nice UPS guy shows up with some SIMMs in a few days. I expect that's all most current CS students know as well. Is that bad? Is their education somehow lacking because they don't understand why "memory bus" and "transmission line" belong in the same sentence? Not at all. All that's happened is that very important stuff has become so standardized that they don't have to worry about it any more and can spend their time and energy thinking about other problems that need to be solved today. There are lots of really important, hard, theoretical problems that today's CS majors need to be solving. User interfaces for the most part still suck. Self-configuring and self-healing high speed networks on a global scale. AI hasn't really progressed in 30 years. Computer vision and speech. Robotics. Cryptography and security. And what about flying cars? Just like you can't even begin to think about building today's GUI-driven desktop applications if you're still worrying about individual logic gates, you can't begin to think about solving some of these really hard problems (and others we haven't even imagined) if you're still worrying about memory buffer reference counting and garbage collection. Yesterday's research projects are today's utilities and tomorrow's historical footnotes. From jan.danielsson at gmail.com Tue Jun 14 09:08:33 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Tue, 14 Jun 2005 15:08:33 +0200 Subject: Going crazy... In-Reply-To: References: <42ae2729$1@griseus.its.uu.se> Message-ID: <42aed582$1@griseus.its.uu.se> Gary Herron wrote: [---] >> I just tried typing the above in Python, and it - obviously - doesn't >> work, so it must be some other syntax. >> >> > Not with tuples, lists or dictionaries. However a more recent addition > to the language is Sets, and they support set differences: > >>>> from sets import Set >>>> Set([1,2,3,4,5,6]) - Set([2,3,6]) > Set([1, 4, 5]) That's it! Thanks; I knew I had seen it. That's a pretty cool feature; which I have use for in a library I'm writing. From renting at astron.nl Thu Jun 30 05:20:22 2005 From: renting at astron.nl (Adriaan Renting) Date: Thu, 30 Jun 2005 11:20:22 +0200 Subject: Debugger Confusion Message-ID: I use the debugger that comes with Eric3, but it is only free for Linux/ OS X, as it needs PyQt. asside from setting (conditional) breakpoints, one of it's features is that it can show you a browsable tree of all your variables. something like this: class MyClass | L-- string 'username' - 'myuser' | L-- list L-[0] - 1 L-[1] - 'some value' You should know by now that I like this IDE ;-) Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> "Robert Brewer" 06/28/05 11:02 PM >>> Rex Eastbourne wrote: > I'm a little confused about which debugging utilities do what, and > which I should use for my Python code. I'd like to be able to step > through my code, insert breakpoints, etc. I haven't been able to do > this yet (I'm using Emacs on Windows). I have seen references to GDB, > GUD, PDB, and others. Which ones do I need? 1. At the point you would like to start the debugger, insert the following 2 lines: import pdb pdb.set_trace() 2. Run your script from the command line. 3. When your script executes the above lines, the pdb debugger will start up, and give you a prompt. Type 'h' at the prompt (and hit 'enter'), and you'll be shown a list of pdb commands. 's' to step through your code, 'c' to continue processing (and stop the debugger, essentially). The prompt is interactive, so you can inspect program variables as you like. Start with that, and come back if you have any more questions. :) Robert Brewer System Architect Amor Ministries fumanchu at amor.org -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Tue Jun 14 03:59:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 09:59:44 +0200 Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: Ron Adam wrote: > True, but I think this is considerably less clear. The current for-else > is IMHO is reversed to how the else is used in an if statement. nope. else works in exactly the same way for all statements that support it: if the controlling expression is false, run the else suite and leave the statement. From noreply at gcgroup.net Thu Jun 16 12:04:48 2005 From: noreply at gcgroup.net (William Gill) Date: Thu, 16 Jun 2005 16:04:48 GMT Subject: access properties of parent widget in Tkinter In-Reply-To: <42b17114$1_2@newspeer2.tds.net> References: <42b17114$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > William Gill wrote: > >> I am trying to get & set the properties of a widget's parent widget. >> What I have works, but seems like a long way around the block. First >> I get the widget name using w.winfo_parent(), then i convert the name >> to a reference using nametowidget(). >> >> self.nametowidget(event.widget.winfo_parent()).hasChanged= True > > > Personally I think it is bad design for a widget to assume anything > about its enclosing environment. What about passing a StringVar or > IntVar to the child widget and letting it work with that? > > Kent A little more research into stringVar, and the stringVar.trace() method may be one way to go. It may be simpler, or more convoluted having so many stringVar objects. I'll do some experimenting, but I'm still open to other ideas. Bill From lbates at syscononline.com Thu Jun 30 17:28:20 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 30 Jun 2005 16:28:20 -0500 Subject: Newbie backreference question In-Reply-To: References: Message-ID: <42C463F4.2040005@syscononline.com> a='test string' print a.split()[:-1] I'm assuming that you want the last space separated word? Larry Bates paulm wrote: > Hi, > In perl I can do something like: > > $a = 'test string'; > $a =~ /test (\w+)/; > $b = $1; > print $b . "\n"; > > and my output would be "string". > > How might this snippet be written in python? > > Thanks to all... From steve at REMOVETHIScyber.com.au Mon Jun 27 08:23:34 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Mon, 27 Jun 2005 22:23:34 +1000 Subject: noob question References: Message-ID: On Mon, 27 Jun 2005 07:14:07 +0000, Alan Gauld wrote: > The only place I've ever found Hungarian notation useful was > in C which is a weird mix of static typing and no-typing, > and there the prefix code gives a clue as to what kind of > value you might expect to find. But when I moved to C++ I > dropped the prefixes because they added no value. > > In Python Hungarian notation is meaningless since variables > aren't typed anyway. Not quite true. Objects are typed in Python: py> type('') py> type(1) but names ("variables", almost) can be dynamically changed from one type to another: py> x = 1 # x starts as an int py> x = '~' # now it is a string py> x = [1] # and now a list Even though names can refer to an object of any type, the actual objects themselves are always strongly typed: "hello" is always a string, {} is always a dict, and so on. The best use of Hungarian notation is the original use, as introduced in the application development team at Microsoft (before the operating system team got their hands on it, and broke it). Rather than prefixing variable names with the type which the compiler already knows (eg "sName" for a string, "iAge" for an integer), the original use of Hungarian notation was to use a prefix which explains what the data is for: the "type" of object, but not types which compilers understand. Here are some good uses for Hungarian notation: ixCurrent = 0 # ix~ means index into a list or array cFound = 0 # c~ means a count dxObject = object.width() # d means difference No compiler in the world can tell that adding the width of an object in pixels to the count of how many objects were found gives a meaningless result. But a human programmer should immediately see the bug in: ixHam = dxEgg + cTomato even if they don't remember what Ham, Egg and Tomato represent. Remember that space probe a few years back that crashed into Mars because some NASA engineer forgot to convert metric to imperial or vice versa? That sort of mistake is easy to make when you have something like this: initialSpeed = 3572.8 # feet per second # ~~~ # five pages of code # ~~~ deceleration = 3.5 # metres per second squared # ~~~ # five more pages of code # ~~~ timeNeeded = initialSpeed/deceleration Now imagine seeing this line instead: timeNeeded = iInitialSpeed/mDeceleration With just a glance you can see that there needs to be a conversion from imperial (i~) to metric (m~) or vice versa, or else your $20 billion dollar space probe turns the engines off too early and becomes a $20 billion hole in the ground. The history and justification for Hungarian notation is explained here: http://www.joelonsoftware.com/articles/Wrong.html -- Steven. From mhoy4 at cox.net Fri Jun 10 13:19:27 2005 From: mhoy4 at cox.net (Mike Hoy) Date: Fri, 10 Jun 2005 10:19:27 -0700 Subject: try: except: ValueError Message-ID: <1118423967.6123.5.camel@laptop.solodiver> hi my goal is to handle the problem of a user typing a letter or symbol rather than a number I found something called try: and ValueError: Anyway this is what i attempted: #menuloop menuChoice = 7 printMenu() while menuChoice != 0: try: menuChoice = int("1 = write | 2 = view | 0 = quit")) except ValueError: print "enter a number" if menuChoice == 1: writeEntry() elif menuChoice == 2: viewEntry() elife menuChoice == 0: pass else: printMenu() print "bye" this works as though I never added try: and except ValueError: at all. the program just doesn't use them at all. if a user types a&s it still errors 'a&s' is not defined what am i doing wrong here? From python at rcn.com Mon Jun 13 04:04:53 2005 From: python at rcn.com (Raymond Hettinger) Date: 13 Jun 2005 01:04:53 -0700 Subject: Dynamic Lists, or...? References: <1118511053.455332.231570@g44g2000cwa.googlegroups.com> Message-ID: <1118649893.551622.289740@g49g2000cwa.googlegroups.com> # Professional driver on a closed course. # Don't try this at home. data = """ rose, 1, 500 lilac, 1, 300 lilly, 1, 400 rose, 0, 100 """ data = data.replace(', 1, ', ' += ') data = data.replace(', 0, ', ' -= ') class DefaultDict(dict): def __getitem__(self, key): return self.get(key, 0) d = DefaultDict() exec data in {}, d print d.items() From gsakkis at rutgers.edu Thu Jun 30 18:37:45 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 15:37:45 -0700 Subject: Newbie backreference question References: <42C463F4.2040005@syscononline.com> Message-ID: <1120171065.884074.216240@z14g2000cwz.googlegroups.com> "paulm" wrote: > No, sorry - my bad. I am looking to assign the > backreference to another variable so it can be treated > seperately. So perhaps: > > $a = 'test string two'; > $a =~ /test \w{2}([\W\w]+)/; > $b = $1; > print $b . "\n"; > > producing "ring two". > > I have read the docs and faqs but remain too dense > to comprehend. > > Thanks again... Did you have a look at my other reply ? It's still the same, just change the regexp: import re a = 'test string two' b = re.match(r'test \w{2}(.+)', a, re.DOTALL).group(1) print b By the way, if you want to catch any single character (including new lines), '.' with re.DOTALL flag is more clear than [\W\w]. George From powderkeg at snow.email.ne.jp Thu Jun 2 02:53:02 2005 From: powderkeg at snow.email.ne.jp (Mark Sargent) Date: Thu, 02 Jun 2005 15:53:02 +0900 Subject: Moving Places, Subtracting from slices/lists Message-ID: <429EACCE.8050101@snow.email.ne.jp> Hi All, playing around with the tut now. How can I get this code to remove the original instance of 'roof'.? >>> hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin'] >>> for x in hotcat[:]: ... if x == 'roof': hotcat.insert(6,x) ... >>> hotcat ['Cat', 'roof', 'on', 'a', 'hot', 'tin', 'roof'] Perhaps a replace or something after the 2nd line of the for function.? >>> hotcat = ['Cat', 'roof', 'on', 'a', 'hot', 'tin'] >>> for x in hotcat[:]: ... if x == 'roof': hotcat.insert(6,x) ... hotcat[x:len(x)] = [] ... Traceback (most recent call last): File "", line 3, in ? TypeError: slice indices must be integers I feel I'm close to it. Cheers. Mark Sargent. From exarkun at divmod.com Wed Jun 8 17:55:04 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 8 Jun 2005 17:55:04 -0400 Subject: pack heterogeneous data types In-Reply-To: <1118267340.026766.188450@g14g2000cwa.googlegroups.com> Message-ID: <20050608215504.15830.1660307831.divmod.quotient.3093@ohm> On 8 Jun 2005 14:49:00 -0700, ashokbellur at gmail.com wrote: >Hello, > >How do i pack different data types into a struct or an array. Examples >would be helpful. > >Say i need to pack an unsigned char( 0xFF) and an long( 0xAAAAAAAA) >into a single array? The reason i need to do this is send a packet over >a network. >>> import struct >>> struct.pack('!BL', 0xff, 0xaaaaaaaa) '\xff\xaa\xaa\xaa\xaa' >>> Jp From tzot at sil-tec.gr Tue Jun 28 08:46:01 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 15:46:01 +0300 Subject: What is different with Python ? (OT I guess) References: <42AED7B3.8060009@carmen.se> Message-ID: <6kh2c151vvhda93jghhm8qcrf9v64llf7t@4ax.com> On Thu, 16 Jun 2005 14:29:49 +0100, rumours say that Tom Anderson might have written: >At one point, a friend and i founded a university to give our recreational >random hackery a bit more credibility (well, we called ourself a >university, anyway; it was mostly a joke). We called the programming >department 'Executable Poetry'. That's a good idea for a t-shirt: "Python: executable poetry" (kudos to Steve Holden for mailman.1390.1112714031.1799.python-list at python.org where the term PIPO (Poetry In, Poetry Out) could be born) and then, apart from t-shirts, the PSF could sell Python-branded shampoos named "poetry in lotion" etc. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From peter at engcorp.com Thu Jun 2 14:32:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 14:32:53 -0400 Subject: date and time range checking In-Reply-To: References: Message-ID: Maksim Kasimov wrote: > what is the "pythonic" way to check is the date/time value in the given > periods range? Something like this, though I won't make strong claims of "pythonicness". If you want to use the "in" keyword you'll want a custom class and overriding of __contains__. import time from datetime import datetime def make_datetime(s, fmt='%Y-%m-%d %H:%M'): '''convert string to datetime''' ts = time.mktime(time.strptime(s, fmt)) return datetime.fromtimestamp(ts) def inRange(s, ranges): dt = make_datetime(s) for begin,end in ranges: if begin <= dt <= end: return True else: return False ranges = [(make_datetime(b), make_datetime(e)) for (b,e) in [ ('2005-06-08 12:30', '2005-06-10 15:30'), ('2005-06-12 12:30', '2005-06-14 15:30'), ]] print inRange('2005-06-11 12:30', ranges) From d at e.f Fri Jun 24 16:53:56 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 15:53:56 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <8-2dnaaqFsZ07yHfRVn-iA@comcast.com> Terry Reedy wrote: > "Tom Anderson" wrote in message > news:Pine.LNX.4.62.0506241625460.14603 at urchin.earth.li... > > >>sometimes in python. No, it's not really possible in a typeless language, >>and yes, there are implementations based on decorators, but frankly, >>they're awful. > > > Python has strongly typed objects. Only names are typeless. Again, you are splitting hairs. His point still stands that it is not possible to do method overloading in python (unless you use decorator hacks). It may be possible to add this feature when type declarations and type checking are added to a future version of python. From max at alcyone.com Mon Jun 20 11:58:52 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 20 Jun 2005 08:58:52 -0700 Subject: Python choice of database In-Reply-To: References: <9yBte.372$W74.334@newssvr30.news.prodigy.com> Message-ID: Philippe C. Martin wrote: > You mean pickling a dictionnary of 5000/16K objects ? Yes. You said speed was not an issue; pickling only 5000 objects, each no more than 16 kB, is easily handled by any remotely modern machine (and even plenty which are not very modern). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I used to walk around / Like nothing could happen to me -- TLC From peter at engcorp.com Tue Jun 28 14:36:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Jun 2005 14:36:40 -0400 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <342dnUPzuo5YBVzfRVn-pg@powergate.ca> Dennis Lee Bieber wrote: > On Tue, 28 Jun 2005 08:18:55 -0400, Matt Feinstein > declaimed the following in comp.lang.python: > > >>FORTH is 'way outside the mainstream of current programming, while > > > Unless one is coding low-level objects on a MUCK (and even that, > on the MUCKs I sometimes visit, requires sysop approval to access the > MUF interpreter -- the mundanes make do with MPI, a LISP-like language). Not "unless"... perhaps "because"? Whatever a MUCK is, it's definitely not part of the "mainstream of current programming", even if you're the one doing it... -Peter From philippe at philippecmartin.com Sun Jun 5 08:57:01 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Sun, 05 Jun 2005 12:57:01 GMT Subject: csv and iterator protocol References: <42a2596f$1_2@newspeer2.tds.net> Message-ID: Thanks Kent, I had a bug in my test program: it works fine with strings Philippe Kent Johnson wrote: > Philippe C. Martin wrote: >> Can I initialize csv with input data stored in RAM (ex: a string) ? - so >> far I cannot get that to work. Or to rephrase the question, what Python >> "RAM" structure supports the "iterator protocol" ? > > Many, including strings, lists and dicts. For your needs, a list of > strings will work, or a cStringIO initialized from your data. > > Kent From rune.strand at gmail.com Tue Jun 28 01:02:06 2005 From: rune.strand at gmail.com (Rune Strand) Date: 27 Jun 2005 22:02:06 -0700 Subject: Better console for Windows? In-Reply-To: <1119928421.011284.183810@o13g2000cwo.googlegroups.com> References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> <1119927705.432472.65820@z14g2000cwz.googlegroups.com> <1119928421.011284.183810@o13g2000cwo.googlegroups.com> Message-ID: <1119934926.078849.306140@f14g2000cwb.googlegroups.com> Annoyed by windows? Check this URL: http://www.annoyances.org/exec/show/category01 ;-) From bogus@does.not.exist.com Mon Jun 20 16:35:02 2005 From: bogus@does.not.exist.com () Date: Mon, 20 Jun 2005 20:35:02 -0000 Subject: No subject Message-ID: #! rnews 902 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Couple functions I need, assuming they exist? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 15 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Mon, 20 Jun 2005 20:12:51 GMT Xref: news.xs4all.nl comp.lang.python:382593 Charles Krug writes: [snip] > The target of the problems (my daughter) ... [snip] That sounds familiar :-). See: http://www.seanet.com/~hgg9140/math/index.html http://www.seanet.com/~hgg9140/math/k6.html -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From nospam at here.com Tue Jun 28 08:18:55 2005 From: nospam at here.com (Matt Feinstein) Date: Tue, 28 Jun 2005 08:18:55 -0400 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: On 27 Jun 2005 20:16:12 -0700, "BORT" wrote: >Please forgive me if this is TOO newbie-ish. > >I am toying with the idea of teaching my ten year old a little about >programming. I started my search with something like "best FREE >programming language for kids." After MUCH clicking and high-level >scanning, I am looking at Python and Forth. Both have advocates that >say each is a great approach to learning computers. FORTH is 'way outside the mainstream of current programming, while Python is, if anything, excessively buzz-word compliant. If you want to teach your kid something that will a basis for learning anything about current practices in programming, teach him Python. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From tim.peters at gmail.com Sat Jun 25 00:07:02 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 25 Jun 2005 00:07:02 -0400 Subject: Tracing down segfault In-Reply-To: References: Message-ID: <1f7befae050624210768c29500@mail.gmail.com> [Tony Meyer] > I have (unfortunately) a Python program that I can consistently (in a > reproducible way) segfault. However, I've got somewhat used to Python's > very nice habit of protecting me from segfaults and raising exceptions > instead, and am having trouble tracking down the problem. > > The problem that occurs looks something like this: > > Program received signal SIGSEGV, Segmentation fault. > 0x00a502aa in ?? () > (gdb) bt > #0 0x00a502aa in ?? () > Cannot access memory at address 0x0 > > Which looks something like accessing a NULL pointer to me. Worse, if you can't get a stack trace out of gdb, it suggests that bad C code has corrupted the C stack beyond intelligibility. The original SIGSEGV was _probably_ due to a NULL pointer dereference too (although it could be due to any string of nonsense bits getting used as an address). The _best_ thing to do next is to rebuild Python, and as many other packages as possible, in debug mode. For ZODB/ZEO, you do that like so: python setup.py build_ext -i --debug It's especially useful to rebuild Python that way. Many asserts are enabled then, and all of Python's memory allocations go thru a special debug allocator then with gimmicks to try and catch out-of-bounds stores, double frees, and use of free()'d memory. > The problem is finding the code that is causing this, so I can work around > it (or fix it). Unfortunately, the script uses ZEO, ZODB, > threading.Threads, and wx (my code is pure Python, though), You didn't mention which version of any of these you're using, or the OS in use. Playing historical odds, and assuming relatively recent versions of all, wx is the best guess. > and I'm having trouble creating a simple version that isolates the problem > (I'm pretty sure it started happening when I switched from thread to > threading, but I'm not sure why that would be causing a problem; It's unlikely to be the true cause. Apart from some new-in-2.4 thread-local storage gimmicks, all of the threading module is written in Python too. NULL pointers are a (depressingly common) C problem. > I am join()ing all threads before this happens). So only a single thread is running at the time the segfault occurs? Is Python also in the process of tearing itself down (i.e., is the program trying to exit?). One historical source of nasties is trying to get more than one thread to play nicely with GUIs. > Does anyone have any advice for tracking this down? Nope, can't think of a thing -- upgrade to Windows . From hancock at anansispaceworks.com Sun Jun 19 23:25:13 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 19 Jun 2005 22:25:13 -0500 Subject: references/addrresses in imperative languages In-Reply-To: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: <200506192225.13166.hancock@anansispaceworks.com> On Sunday 19 June 2005 05:34 pm, Xah Lee wrote: > in coding Python yesterday, i was quite stung by the fact that lists > appened to another list goes by as some so-called "reference". e.g. > > t=range(5) > n=range(3) > n[0]='m' > t.append(n) > n[0]='h' > t.append(n) > print t Day one in learning Python, yes --- "names bind to objects" NOT "variables are filled with values". This is one case where prior experience with C warps your brain. > in the following code, after some 1 hour, finally i found the solution > of h[:]. (and that's cheating thru a google search) > > def parti(l,j): > '''parti(l,j) returns l partitioned with j elements per group. If j > is not a factor of length of l, then the reminder elements are dropped. > Example: parti([1,2,3,4,5,6],2) returns [[1,2],[3,4],[5,6]] > Example: parti([1,2,3,4,5,6,7],3) returns [[1,2,3],[4,5,6]]''' > n=len(l)/j > r=[] # result list > h=range(j) # temp holder for sublist > for n1 in range(n): > for j1 in range(j): > h[j1]=l[n1*j+j1] > r.append( h[:] ) > return r Too bulky? How about: def parti(L, j): return [L[k*j:(k+1)*j] for k in range(len(L)/j)] e.g.: >>> >>> parti([1,2,3,4,5,6,7],3) [[1, 2, 3], [4, 5, 6]] >>> parti([1,2,3,4,5,6],2) [[1, 2], [3, 4], [5, 6]] > PS is there any difference between > t=t+[li] > t.append(li) No, but t=t+[li] is quite different from t.append([li]) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From peter at engcorp.com Thu Jun 16 16:20:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 16 Jun 2005 16:20:23 -0400 Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') In-Reply-To: References: Message-ID: Maxwell Hammer wrote: > This is related to an earlier post 'Help with thread related > tracebacks'...for which I have had no feedback yet :-( If the question was well formulated, and it's been more than a couple of days, you should consider reposting. It's very unusual for a post with such a subject (if it was a clear question) to get _no_ feedback around here. > How should a thread complete i.e. how should it exit? As with any function, just return... > Reading the python online docs one gets the idea that simply returning is > OK - but I'm not sure. > Is it ok to do a sys.ext()? Use 'return' or just let them run out with no > 'return' ??? sys.exit() merely raises a SystemExit exception. In the main thread this will terminate the application (assuming no non-daemon threads are still running), while in a non-main thread it should simply be ignored. If you aren't trying to exit from a function call within the thread, using "return" or just falling off the end of the run() method (if you've subclasses Thread) or the target function (if you used the "target=xxx" approach) is quite sufficient and acceptable. Note that "return" is identical to "return None" which is identical to just falling off the end of a function in Python. Some might consider a simple unadorned "return" to be the most expressive and readable. -Peter From pdemb at gazeta.pl Mon Jun 13 16:05:34 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Mon, 13 Jun 2005 22:05:34 +0200 Subject: implicit variable declaration and access References: Message-ID: <87fyvm6n01.fsf@hector.domek> Tom Anderson writes: [snap] > The MAtrix had evarything in it: guns, a juimping off teh walls, > flying guns, a bullet tiem, evil computar machenes, numbers that > flew, flying gun bullets in slowar motian, juimping into a gun, dead > police men, computar hackeing, Kevin Mitnick, oven trailers, a old > womans kitchen, stairs, mature women in clotheing, head spark plugs, > mechaanical squids, Japaneseses assasins, tiem traval, volcanos, > a monstar, slow time at fastar speed, magic, wizzards, some dirty > place, Kung Few, fighting, a lot of mess explodsians EVARYWHERE, > and just about anything else yuo can names! ...with greetings to Carnivore ;) From markus_GETRIDOFALLCAPSwankus at hotmail.com Tue Jun 28 20:31:08 2005 From: markus_GETRIDOFALLCAPSwankus at hotmail.com (Markus Wankus) Date: Tue, 28 Jun 2005 20:31:08 -0400 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> References: <11bs1bc5jotvg9c@news.supernews.com> <42BF6995.1050606@boonthavorn.com> <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> Message-ID: Stephen Kellett wrote: > In message , Simon > Brunning writes > >> Eclipse's refactorings are a great boon, I find. Refectoring is never >> *fully* automatic, of course, but the ability to, for example, select >> a chunk of code and have it extracted into a separate method with all >> needed arguments and the return value worked out for you is very >> helpful. All you have to do is give the new method a name. And this >> sort of thing can certainly improve readability. > > > This is not an attach on you Simon, but if people are relying on that > type of thing for increases in software productivity they are hiring the > wrong people. > > Stephen Have you ever tried anything that provides real, usable refactoring like Eclipse does with Java? I guarantee if you used it more than a few times your view would most likely change. The fact is, code evolves. You simply cannot write high-quality software in one pass. Good refactoring tools save time, and therefore money. I sure wouldn't hire anyone who thought otherwise... Markus. From ptmcg at austin.rr.com Fri Jun 24 09:28:46 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 24 Jun 2005 06:28:46 -0700 Subject: trouble subclassing str In-Reply-To: References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> Message-ID: <1119619726.756391.175800@z14g2000cwz.googlegroups.com> >From purely Python terms, there is a distinction that one of these classes (PaddedStr) is immutable, while the other is not. Python only permits immutable objects to act as dictionary keys, so this would one thing to differentiate these two approaches. But on a more abstract, implementation-independent level, this is a distinction of inheritance vs. composition and delegation. Inheritance was one of the darling concepts in the early days of O-O programming, with promises of reusability and development speed. But before long, it turned out that inheritance comes with some unfriendly baggage - dependencies between subclasses and superclasses made refactoring more difficult, and modifications to supertypes had unwanted effects on subclasses. Sometimes subclasses would use some backdoor knowledge of the supertype data, thereby limiting flexibility in the superclass - this phenomenon is often cited as "inheritance breaks encapsulation." One check for good inheritance design is the Liskov Substitution Principle (LSP) (Thanks for the Robert Martin link, Kent - you beat me to it). Borrowing from the Wiki-pedia: "In general, the principle mandates that at all times objects from a class can be swapped with objects from an inheriting class, without the user noticing any other new behaviour. It has effects on the paradigms of design by contract, especially regarding to specification: - postconditions for methods in the subclass should be more strict than those in the superclass - preconditions for methods in the subclass should be less strict than those in the superclass - no new exceptions should be introduced in the subclass" (http://en.wikipedia.org/wiki/Liskov_substitution_principle) One thing I like about this concept is that is fairly indepedent of language or implementation features. I get the feeling that many such rules/guidelines seem to be inspired by limitations or gimmicks that are found in programming language X (usually C++ or Java), and then mistakenly generalized to be universal O-O truths. Looking back to PaddedStr vs. MyString, you can see that PaddedStr will substitute for str, and for that matter, the MyString behavior that is given could be a reasonable subclass of str, although maybe better named StarredStr. But let's take a slightly different MyString, one like this, where we subclass str to represent a person's name: class Person(str): def __new__(cls,s,data): self = str.__new__(cls,s) self.age = data return self p = Person("Bob",10) print p,p.age This is handy enough for printing out a Person and getting their name. But consider a father and son, both named "Bob". p1 = Person("Bob",10) p2 = Person("Bob",35) # p1's dad, also named Bob print p1 == p2 # prints 'true', should it? print p1 is p2 # prints 'false' Most often, I see "is-a" confused with "is-implemented-using-a". A developer decides that there is some benefit (reduced storage, perhaps) of modeling a zip code using an integer, and feels the need to define some class like: class ZipCode(int): def lookupState(self): ... But zip codes *aren't* integers, they just happen to be numeric - there is no sense in supporting zip code arithmetic, nor in using zip codes as slice indices, etc. And there are other warts, such as printing zip codes with leading zeroes (like they have in Maine). So when, about once a month we see on c.l.py "I'm having trouble sub-classing ," I can't help but wonder if telling the poster how to sub-class an XYZ is really doing the right thing. In this thread, the OP wanted to extend str with something that was constructable with two arguments, a string and an integer, as in s1 = MyString("some text", 100). I tried to propose a case that would be a good example of inheritance, where the integer would be used to define and/or constrain some str attribute. A *bad* example of inheritance would have been one where the 100 had some independent characteristic, like a font size, or an age value to be associated with a string that happens to contain a person's name. In fact, looking at the proposed MyClass, this seems to be the direction he was headed. When *should* you use inheritance? Well, for a while, there was such backlash that the response was "Never". Personally, I use inheritance in cases where I have adopted a design pattern that incorporates it, such as Strategy; otherwise, I tend not to use it. (For those of you who use my pyparsing package, it is loaded with the Strategy pattern. The base class ParserElement defines an abstract do-nothing parsing implementation, which is overridden in subclasses such as Literal, Word, and Group. All derived instances are treated like the base ParserElement, with each subclass providing its own specialized parseImpl or postParse behavior, so any subclass can be substituted for the base ParserElement, satisfying LSP.) I think the current conventional wisdom is "prefer composition over inheritance" - never say "never"! :) -- Paul From benji at benjiyork.com Fri Jun 24 08:20:35 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 24 Jun 2005 08:20:35 -0400 Subject: Sorting part of a list In-Reply-To: <1119614874.396629.236570@g49g2000cwa.googlegroups.com> References: <3i29tfFjgph8U1@news.dfncis.de> <1119614874.396629.236570@g49g2000cwa.googlegroups.com> Message-ID: <42BBFA93.1080504@benjiyork.com> Fuzzyman wrote: > a = ll[2:] > a.sort() > ll[2:] = a > > To do a partial sort, in place, you'll have to subclass list Or be using 2.4: >>> ll = [3, 1, 4, 2] >>> ll[2:] = sorted(ll[2:]) >>> ll [3, 1, 2, 4] -- Benji York From sjmachin at lexicon.net Sat Jun 18 20:16:50 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 19 Jun 2005 10:16:50 +1000 Subject: Regex for repeated character? In-Reply-To: References: <5J9se.136$Q75.39412@newshog.newsread.com> <42B3C7AA.7090907@lexicon.net> Message-ID: <42B4B972.8070301@lexicon.net> Terry Hancock wrote: > On Saturday 18 June 2005 02:05 am, John Machin wrote: > >>Doug Schwarz wrote: >> >>>In article <5J9se.136$Q75.39412 at newshog.newsread.com>, >>> Leif K-Brooks wrote: >>> >>>>How do I make a regular expression which will match the same character >>>>repeated one or more times, >>> >>>How's this? >>> >>> >>> [x[0] for x in re.findall(r'((.)\2*)', 'abbcccddddcccbba')] >>> ['a', 'bb', 'ccc', 'dddd', 'ccc', 'bb', 'a'] >> >>I think it's fantastic, but I'd be bound to say that given that it's the >>same as what I posted almost two days ago :-) > > > Guess there's only one obvious way to do it, then. ;-) > Yep ... but probably a zillion ways in re.compile(r"perl", re.I).match(other_languages) From davecook at nowhere.net Wed Jun 29 02:08:35 2005 From: davecook at nowhere.net (Dave Cook) Date: Wed, 29 Jun 2005 06:08:35 GMT Subject: ANN: PyDev 0.9.5 released References: <42A720BD.5050701@esss.com.br> Message-ID: On 2005-06-28, Fabio Zadrozny wrote: > PyDev - Python IDE (Python Development Enviroment for Eclipse) version > 0.9.5 has just been released. Does it work with the newly released Eclipse 3.1? Dave COok From dalke at dalkescientific.com Sat Jun 4 02:38:24 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 04 Jun 2005 06:38:24 GMT Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Nicolas Fleury wrote: > There's no change in order of deletion, it's just about defining the > order of calls to __exit__, and they are exactly the same. BTW, my own understanding of this is proposal is still slight. I realize a bit better that I'm not explaining myself correctly. > As far as I > know, PEP343 has nothing to do with order of deletion, which is still > implementation-dependant. It's not a constructor/destructor thing like > in C++ RAII, but __enter__/__exit__. I'm mixing (because of my lack of full comprehension) RAII with your proposal. What I meant to say was in the PEP with locking(someMutex) with opening(readFilename) as input with opening(writeFilename) as output ... it's very well defined when the __exit__() methods are called and in which order. If it's with locking(someMutex) with opening(readFilename) as input with opening(writeFilename) as output with the __exit__()s called at the end of the scope (as if it were a __del__, which it isn't) then the implementation could still get the __exit__ order correct, by being careful. Though there would be no way to catch an exception raised in an __exit__. I think. >> Your approach wouldn't allow the following > > No, I said making the ':' *optional*. I totally agree supporting ':' is > useful. Ahh, I think I understand. You want both with abc: with cde: pass and with abc with def and to have the second form act somewhat like RAII in that the __exit__() for that case is called when the scope ends. Hmm. My first thought is I don't like it because I'm a stodgy old traditionalist and don't like the ambiguity of having to look multiple tokens ahead to figure out which form is which. I can see that it would work. Umm, though it's tricky. Consider with abc with defg: with ghi with jkl: 1/0 The implementation would need to track all the with/as forms in a block so they can be __exit__()ed as appropriate. In this case ghi.__exit() is called after jkl.__exit__() and before defg.__exit__ The PEP gives an easy-to-understand mapping from the proposed change to how it could be implemented by hand in the existing Python. Can you do the same? > True. But does it look as good? Particularly the _ part? I have not idea if the problem you propose (multiple with/as blocks) will even exist so I can't comment on which solution looks good. It may not be a problem in real code, so not needing any solution. Andrew dalke at dalkescientific.com From renato.ramonda at gmail.com Wed Jun 29 19:26:55 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Thu, 30 Jun 2005 01:26:55 +0200 Subject: How to find Windows "Application data" directory?? In-Reply-To: References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> <1120017647.696243.154880@f14g2000cwb.googlegroups.com> <7xbr5pkdnb.fsf@ruckus.brouhaha.com> Message-ID: <37Gwe.22823$TR5.108@news.edisontel.com> Trent Mick ha scritto: > Note that the APPDATA environment variable is only there on *some* of > the Windows flavours. It is there on Win2k and WinXP. It is not there on > WinME. Dunno about Win95, Win98, WinNT... but you may not care about > those old guys. That's (I guess) because the DOS spawn (win9x family) was single user and did not really have concepts like home directories, profiles, separate settings for each user... hell, it did not even have users! :-D -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From deets at web.de Sat Jun 25 08:51:52 2005 From: deets at web.de (Diez B. Roggisch) Date: Sat, 25 Jun 2005 14:51:52 +0200 Subject: OT: Re: Looking For Geodetic Python Software In-Reply-To: References: <447po2-iqt.ln1@eskimo.tundraware.com> <3hvrhjFj3qfmU1@uni-berlin.de> <7xu0jodc5u.fsf@ruckus.brouhaha.com> <3i2arqFjdihuU1@uni-berlin.de> Message-ID: <3i52b9Fjnp5uU1@uni-berlin.de> > The article implied that the automated system would allow for > /shorter paths/ (the shortest path is the great circle, so this > statement indicates that trans-oceanic flights are not using great > circle/GPS routing). Most likely, the flights are using 50 minute "plumb > lines", with a heading change at the 50 minute mark, so current position > and new heading can be reported to ATC. GPS may be supplying the pilots > with position info, but they may not be free to make the constant > heading changes... The automated system may send this information > digitally at much higher rate than 50 minutes, allowing ATC to plot near > realtime positions. Looks as if I stand corrected - I remember clearly when we were introduced to great circles in school, that the example given were intercontinental flights. So it appears that they use a discretization scheme that our teacher embezzled. Terry Pratchett calls that "Lies for kids". On further thinking, it makes sense that it's not allowed to constantly change heading - it makes the course estimation for e.g. approaching aircrafts complicated. Thanks for pointing that out! Diez From thomas at thomas-lotze.de Sun Jun 12 08:21:58 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sun, 12 Jun 2005 14:21:58 +0200 Subject: Controlling a generator the pythonic way References: Message-ID: Thomas Lotze wrote: > Does anybody here have a third way of dealing with this? Sleeping a night sometimes is an insightful exercise *g* I realized that there is a reason why fiddling with the pointer from outside the generator defeats much of the purpose of using one. The implementation using a simple method call instead of a generator needs to store some internal state variables on an object to save them for the next call, among them the pointer and a tokenization mode. I could make the thing a generator by turning the single return statement into a yield statement and adding a loop, leaving all the importing and exporting of the pointer intact - after all, someone might reset the pointer between next() calls. This is, however, hardly using all the possibilities a generator allows. I'd rather like to get rid of the mode switches by doing special things where I detect the need for them, yielding the result, and proceeding as before. But as soon as I move information from explicit (state variables that can be reset along with the pointer) to implicit (the point where the generator is suspended after yielding a token), resetting the pointer will lead to inconsistencies. So, it seems to me that if I do want to use generators for any practical reason instead of just because generators are way cool, they need to be instantiated anew each time the pointer is reset, for simple consistency reasons. Now a very simple idea struck me: If one is worried about throwing away a generator as a side-effect of resetting the tokenization pointer, why not define the whole tokenizer as not being resettable? Then the thing needs to be re-instantiated very explicitly every time it is pointed somewhere. While still feeling slightly awkward, it has lost the threat of doing unexpected things. Does this sound reasonable? -- Thomas From jstroud at mbi.ucla.edu Fri Jun 3 22:27:22 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 3 Jun 2005 19:27:22 -0700 Subject: Scope In-Reply-To: References: Message-ID: <200506031927.22807.jstroud@mbi.ucla.edu> On Friday 03 June 2005 07:17 pm, Elliot Temple wrote: > Nothing is wrong with it in this case. I just want to know if Python > can do what I said. Read the python-list "working with pointers" thread from Tuesday. Good answers were posted there. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From ajikoe at gmail.com Wed Jun 8 10:53:14 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 8 Jun 2005 07:53:14 -0700 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: <7r-dnd4Q5rThYDvfRVn-pA@powergate.ca> References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> <7r-dnd4Q5rThYDvfRVn-pA@powergate.ca> Message-ID: <1118242394.785323.303070@f14g2000cwb.googlegroups.com> Hello All, Thanks for the response. I use mysql and find something strange lately while load text file to my database table using LINES TERMINATED BY '\r\n', And I found that mysql think I have '\r\r\n'. this is happened because in one of my code I use 'w' to write element of string + '\r\n'. now I understand why this happened. Actually I prefer to use 'w' and 'r' because the termination of the line will always '\n'. By changing mycode to always use 'w' and write element of string +'\n' instead of +'\r\n' and let my mysql code use LINES TERMINATED '\r\n' I think solve this problem. :) pujo From sjmachin at lexicon.net Thu Jun 9 18:24:40 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 10 Jun 2005 08:24:40 +1000 Subject: A question about time In-Reply-To: <42a8ac25@griseus.its.uu.se> References: <42a8ac25@griseus.its.uu.se> Message-ID: <42A8C1A8.8080502@lexicon.net> Jan Danielsson wrote: > Hello all, > > I have a list of servers which an application connects to. If the > connection fails, the application should mark the server as temporarily > unavailable, and should try to use the server again after x units of time. > > In C, I would do this: > > server.invalidUntil = time(NULL) + 5*60; // five minute delay > > ..and the check: > > if(time(NULL) > server.invalidUtil) > { > // use server > } > > So the whole thing very simple... But how do I do that in Python? > > I have found datetime.datetime.now(), but I don't understand what > "format" it returns the time in. I assume it's an object of some sort.. Everything in Python is an object. Objects can be inspected. The builtin function repr(obj) gives a diagnostic and often compilable REPResentation of the object, and str(obj) [think STRing] gives a "pretty" picture. Sometimes repr() and str() produce the same results. To understand what "format" it's in, read the documentation; in this case, it's found at: http://www.python.org/doc/2.4.1/lib/datetime-datetime.html and play around with the command-line interpreter (example below) or your favourite IDE. >>> import datetime >>> t1 = datetime.datetime.now(); t2 = t1 + datetime.timedelta(minutes=5) [somewhat later] >>> t3 = datetime.datetime.now() >>> for x in t1, t2, t3: print str(x), repr(x) ... 2005-06-10 07:39:15.312000 datetime.datetime(2005, 6, 10, 7, 39, 15, 312000) 2005-06-10 07:44:15.312000 datetime.datetime(2005, 6, 10, 7, 44, 15, 312000) 2005-06-10 07:56:03.031000 datetime.datetime(2005, 6, 10, 7, 56, 3, 31000) >>> t3 > t2 True > But how do I do if I want the current time as an integer (unix > timestamp) in Python? The Python time module would be a good starting point. From andreas at kostyrka.org Wed Jun 29 05:40:27 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 29 Jun 2005 11:40:27 +0200 Subject: strange __call__ In-Reply-To: References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> Message-ID: <20050629094027.GB24238@heaven.kostyrka.org> Just a guess, but setting "__X__" special methods won't work in most cases because these are usually optimized when the class is created. It might work if a.__call__ did exist before (because class a: contained a __call__ definition). Andreas On Wed, Jun 29, 2005 at 09:15:45AM +0100, Michael Hoffman wrote: > Rahul wrote: > > Consider the following: > > def a(x): > > return x+1 > > > > def b(f): > > def g(*args,**kwargs): > > for arg in args: > > print arg > > return f(*args,**kwargs) > > return g > > > > a.__call__ = b(a.__call__) > > > > now calling a(1) and a.__call__(1) yield 2 different results!! > > i.e. for functions a(1) doesnt seem to be translated to a.__call__ if > > you assign a new value to a.__call__? > > I don't know why this happens, but setting the __call__ attribute of a > is a pretty strange thing to do. Why not just set a instead? The > original function a(x) will still be stored as a closure in what is > returned from b(). > > If this is of purely academic interest then the answer is I don't know. :) > -- > Michael Hoffman > -- > http://mail.python.org/mailman/listinfo/python-list From bdesth.quelquechose at free.quelquepart.fr Wed Jun 1 17:42:31 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Jun 2005 23:42:31 +0200 Subject: bug with isinstance() ? In-Reply-To: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> References: <1117657881.206934.289600@g14g2000cwa.googlegroups.com> Message-ID: <429e2664$0$20737$626a14ce@news.free.fr> Mac a ?crit : > Under certain circumstances isinstance() seems to return incorrect > value for me. I'm using Python 2.3 (latest from Debian's unstable). > Here's a sample program... the multi-module nature of the code is key. > > > === test.py === > > class Foo: > pass > > def test(): > from test2 import make_me_a_foo > foo = make_me_a_foo() > if isinstance(foo, Foo): > print "is a Foo" > else: > print "is NOT a Foo!" > > if __name__ == "__main__": > test() > > > === test2.py === > > from test import Foo > > def make_me_a_foo(): > return Foo() > > > --8<-- > > When I run "python test.py", I get "is NOT a Foo!", when the object > clearly IS a Foo! Am I missing something, Yes > or is this a bug? Nope try adding: print foo.__class__ after the second line of your test() function. From Gerald.Klix at klix.ch Wed Jun 8 08:33:13 2005 From: Gerald.Klix at klix.ch (Gerald Klix) Date: Wed, 08 Jun 2005 14:33:13 +0200 Subject: Knowing the signature of a function In-Reply-To: References: Message-ID: <42A6E589.4080509@klix.ch> Use the inspect module like: >>> def tf( a, b, c, *arguments, **keywordArguments ): ... print "tf" ... >>> import inspect >>> inspect.getargspec( tf ) (['a', 'b', 'c'], 'arguments', 'keywordArguments', None) >>> Xavier D?coret schrieb: > Hello, > > I have the following code: > > def foo(x,y): > pass > > How can I query the function object foo to know the number of parameters > it expects. I can find it is a function using callable(f), I can find > some information (listed by dir(foo)) such as the name of the > function,etc.. but nowhere I can find the number of arguments. > > I would like to know wether the function expects one or zero arguments. -- GPG-Key: http://keyserver.veridis.com:11371/search?q=0xA140D634 From anna-s at internet.is Wed Jun 8 19:44:05 2005 From: anna-s at internet.is (Anna M.) Date: Wed, 8 Jun 2005 23:44:05 -0000 Subject: Tabnanny? In-Reply-To: <200506082045.02940.dsa@unilestemg.br> Message-ID: <20050608234409.8737C7AB7E@mail.internet.is> Thank you so much and so it goes . . . from random import randint def idxLargest(list, n): idxMx = 0 for i in range(1, n, 1): if list[i] > list[idxMx]: idxMx = i return idxMx def radixSort(data): sorting = [data] tmp = [] for i in range(10): tmp.append([]) idx = idxLargest(data, len(data) max = data[idx] passes = len(max) + 1 for i in range(1, passes + 1, 1): sorter = tmp for bucket in sorting: for next in bucket: nr = next%(10**i) radix = (nr/10**(i-1)) sorter[radix].append(next) sorting = sorter return sorting n = 10 a = 0 b = 200 test = [] for i in range(n): test.append(randint(a,b)) print test test = radixsort(test) print test >Hi Anna ! > >Please post your code, so we can take a look to see what is happening. > >See ya ! > >Em Quarta 08 Junho 2005 23:36, Anna M. escreveu: >> Hello, i am very new to this. Only heard of python a week ago and have >> never posted before anywhere. But I am trying to rewrite a program that >I >> made in C++ in Python, a radixSort I did as a school project. I get a >> Tabnanny Tokenizing Error that says Token Error: EOF in multi-line >> statement. I gather from the internet that it means I have a tab-error. >I >> just can't seem to find it. Is this something you can help me with? >Could >> I post my code here and you could look at it or is that a bit to much ;) >> >> Many thanks, >> >> Anna -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org -- http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Wed Jun 8 14:26:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 08 Jun 2005 14:26:11 -0400 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> Message-ID: <_JqdnZLLKdzIpTrfRVn-uA@powergate.ca> Fredrik Lundh wrote: > for a number of situations where __ne__ cannot be derived from __eq__, > see: > > http://www.python.org/peps/pep-0207.html That "number" being "one"? I can see only one comment that seems to describe that situation, where it refers to "IEEE 754 floating point numbers do not satisfy [== being the complement of !=]". (Though that may be justification enough for the feature...) -Peter From cdkrug at worldnet.att.net Tue Jun 21 09:05:32 2005 From: cdkrug at worldnet.att.net (Charles Krug) Date: Tue, 21 Jun 2005 13:05:32 GMT Subject: Python choice of database References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: On Mon, 20 Jun 2005 23:42:21 -0800, EP wrote: > Oren suggested: > >> How about using the filesystem as a database? For the number of records >> you describe it may work surprisingly well. A bonus is that the >> database is easy to manage manually. > > I tried this for one application under the Windows OS and it worked fine... > > until my records (text - maybe 50KB average) unexpectedly blossomed > into the 10,000-1,000,000 ranges. If I or someone else (who > innocently doesn't know better) opens up one of the directories with > ~150,000 files in it, the machine's personality gets a little ugly (it > seems buggy but is just very busy; no crashing). Under 10,000 files > per directory seems to work just fine, though. > > For less expansive (and more structured) data, cPickle is a favorite. > Related question: What if I need to create/modify MS-Access or SQL Server dbs? From Bill at SynectixLtd.com Wed Jun 29 12:16:17 2005 From: Bill at SynectixLtd.com (Bill Davy) Date: Wed, 29 Jun 2005 16:16:17 +0000 (UTC) Subject: Python/IDLE - text in different colours References: Message-ID: OK, I (sort of) tried that. Used chr() to avoid issues of which editor and rant the following: import sys ESC = chr(27) DarkRed = ESC + "[31;2m" ResetColour = ESC + "[0m" print "Initial colour" sys.stdout.write(DarkRed) ; sys.stdout.flush() print "Is this dark red?" sys.stdout.write(ResetColour) ; sys.stdout.flush() print "Final colour" The output (in blue, using IDLE) was: Initial colour Is this dark red? Final colour So, have I missed soemthing? By the way, in the output there is a little square box before the [ in the last two lines. Does the window Idle sets up emulate VT100? Hey ho, but many thanks. My user will just have to strain his eyes. Bill PS Thanks for the URL. Interesting. "TouTaTis" wrote in message news:Xns9684B0E245DE6toutatisxsFOURallnl at 194.109.133.242... > "Bill Davy" wrote in > news:d9rfb9$ob7$1 at nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com: > >> To make life easier for my users, I'd like to colour my prompt string >> (as handed to raw_input()) a different colour to that produced by >> print. I'm using Python 2.4.1 and IDLE 1.1.1 on Windows XP. Is it >> possible, and if so, how? >> tia, >> Bill >> >> > > Communicating with a Program > > Say we want the shell to distinguish more clearly, the output of external > programs from the input prompt, the commands, and the shell feedback. We > want the output of external programs to be indented and displayed in a > different colour than the other text. > > Setting the colour of the text is fairly easy using ANSI terminal escape > sequences. For instance, to set the text colour to dark red, write " > [31;2m" to the terminal (where is the escape code - in emacs use > "C-q ESC" to write ). We can reset the output colour using " > 0m". > > Printing the output of external programs in dark red, we can do using the > execute() function: > > def runCommand(command): > print 'Running:', command > > # set output colour: > sys.stdout.write("[31;2m") ; sys.stdout.flush() > > os.system(command) > > # reset output colour > sys.stdout.write("[0m") > > (Here we need to flush the stdout file to make sure that the escape code > is written to the terminal before the output of the program) > > http://www.daimi.au.dk/~mailund/scripting2005/lecture-notes/process-management.html > From steve at REMOVETHIScyber.com.au Fri Jun 24 14:37:20 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 25 Jun 2005 04:37:20 +1000 Subject: Is there something similar to ?: operator (C/C++) in Python? References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: On Fri, 24 Jun 2005 12:54:34 -0500, D H wrote: > Riccardo Galli wrote: >> On Fri, 24 Jun 2005 09:00:04 -0500, D H wrote: >> >> >>>>Bo Peng wrote: >>>> >>>> >>>>>I need to pass a bunch of parameters conditionally. In C/C++, I can >>>>>do func(cond1?a:b,cond2?c:d,.....) >>>>> >>>>>Is there an easier way to do this in Python? >>>> >>>> >>>The answer is simply no, just use an if statement instead. >> >> >> That's not true. >> One used form is this: >> result = cond and value1 or value2 > > So anywhere someone uses x?y:z you recommend they use "x and y or z" > instead, or else "[y,z][x]", but not: > > if x: > val = y > else: > val = z That's not what he said at all. Nowhere did Riccardo suggest that one or the other method was better than if..else. The *most* he did was to suggest a personal opinion that cond and value1 or value2 was "nice". > I still would recommend just using an if statement, even though it is > not easier to type than a ternary expression. That's fine. Recommend it all you like. But it isn't the only way, and it isn't even arguably the best or easiest or simplest way. > It is the most readable > and understandable equivalent in Python. To you maybe. Actually, to me also. But "easier" doesn't just mean "easier to read" -- it also means "easier to write", "easier to maintain", "easier to insert in one-liners", "easier to put in lambda functions", and maybe even "easier to delete when I no longer need it". For at least some of these requirements, the if..else solution is the worst, not the best, solution. > And since his question was > about an easier way to do it in Python, and I don't believe your > alternative are any easier either, I believe the answer is still no. There's an easy way to settle this once and for all. If somebody can come up with a good empirical test for "easier" (easier what?), we can run some tests, get some hard figures for, eg, how many calories are expended in typing one form over the other, and find out which is easier. Until then, the question is at least partly a matter of personal taste, and as such, there is no justification for such sweeping generalities as "the answer is simply no, just use an if statement instead". -- Steven. From mandus at gmail.com Sat Jun 25 15:31:04 2005 From: mandus at gmail.com (Mandus) Date: Sat, 25 Jun 2005 19:31:04 +0000 (UTC) Subject: How does one write a function that increments a number? References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> Message-ID: Sun, 26 Jun 2005 04:14:19 +1000 skrev Steven D'Aprano: > On Fri, 24 Jun 2005 21:53:03 -0700, anonymousnerd at gmail.com wrote: > >> Apologies if this question seems stupid: How does one write a >> function that increments a value in Python? When I tried, the variable >> never changed. >> The session went like this: >>>>> def incr(counter): >> counter = int(counter) >> counter += 1 >> >>>>> counter = 1 >>>>> incr(counter) >>>>> print counter >> 1 > > Why does it need to be a function? Why complicate matters? Isn't it > simpler to just do this: [snip] I guess he have some reason for it... it's because python do call by value, not by reference for such simple variables. If you absolutely want to do this, you can try: def incr(counter): counter[0] += 1 counter=[1] incr(counter) print counter[0] But I agree with Steven, this is probably not what you want to do :) -- Mandus - the only mandus around. From powderkeg at snow.email.ne.jp Fri Jun 3 03:58:47 2005 From: powderkeg at snow.email.ne.jp (Mark Sargent) Date: Fri, 03 Jun 2005 16:58:47 +0900 Subject: Moving Places, Subtracting from slices/lists In-Reply-To: <429FF56F.5010402@snow.email.ne.jp> References: <429EACCE.8050101@snow.email.ne.jp> <429FF56F.5010402@snow.email.ne.jp> Message-ID: <42A00DB7.4030703@snow.email.ne.jp> >what does [hotcat[1]] do.? > > > ah, quite simple really, adds roof to the end of hotcat...thanx.. Mark Sargent. From sjmachin at lexicon.net Sat Jun 11 21:16:26 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 12 Jun 2005 11:16:26 +1000 Subject: how to operate the excel by python? In-Reply-To: <1118375729.127295.90870@g43g2000cwa.googlegroups.com> References: <1118375729.127295.90870@g43g2000cwa.googlegroups.com> Message-ID: <42AB8CEA.50606@lexicon.net> Rune Strand wrote: > The key is Python for Windows : > http://starship.python.net/crew/mhammond/win32/ > > See here for an Excel dispatch example: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325735 > > When doing such operations, I generally save all the Excel files to CSV > files and do the operations on them using the csv module. > Problems with that approach: 1. Unfortunately, "save as CSV" is very much a WYSIWYG operation. If the "number formats" are not sensible, loss of information can result. Example: user gets (text) data file which needs extra columns added. User loads it into Excel, adds extra data, saves as csv. One column is an identifier which just happens to be numeric -- say a 12-digit credit card number 123456789012. The user doesn't care that this is showing on the Excel screen as 1.23457E+11 (default format) as he is using the 6-digit customer account number 654321 to find the extra data he needs to add. He may not even see the 1.23457E+11 because it's in column BQ and he's inserting 3 columns in front of column E. To avoid that problem, one has to check all the columns and reformat those that do not display all the data. This is not something that a user can be relied on to do, even when stated clearly in a procedure manual. 2. The tedium and error-proneness of "saving as": (a) you get given a file named "fubar.csv" but it was "fubar.csv.xls" before the user renamed it. (b) Excel files can have multiple worksheets, which have to be saved each as a separate csv file. Consequently, an approach which reads the .XLS file directly has attractions. One such approach, which unlike the COM approach doesn't need Excel to be on the reading machine, and doesn't even need Windows, is the free "xlrd" module [of which I am the author] -- see http://www.lexicon.net/sjmachin/xlrd.htm or http://www.python.org/pypi/xlrd/ Regards, John From programmer.py at gmail.com Tue Jun 28 14:46:27 2005 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 28 Jun 2005 13:46:27 -0500 Subject: I need help figuring out how to fix this code. In-Reply-To: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: On 6/28/05, Nathan Pinno wrote: > Hi all, > [snip!] It looks like your indentation is off for the if statement. It should be aligned with the "name = raw_input" statement above it. Also, elif name == ["Madonna", "Cher"]: will never evaluate to true. Assume someone enters "guido" for their name, then you're doing this comparison. "guido" == ["Madonna", "Cher"] A string will never equal a list. Now, a string could be in a list. if name in ("Madonna", "Cher"): print "Sorry, you can't come in." hth, jw > #This program asks for a password, then asks for the user's name after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" > > What's wrong with the code? How do I fix it, so that it works? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > From claird at lairds.us Thu Jun 2 13:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 02 Jun 2005 17:08:03 GMT Subject: calling ksh script from python References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: In article , Donn Cave wrote: . . . >Meanwhile, it might be worthwhile to reconsider the use >of ksh here, if you have any choice in the matter. Ksh >is fine for interactive use, but has some unfortunate >flaws as a programming shell, and due to proprietary issues >one commonly encounters an alternative implementation that's >even worse. On most modern platforms, sh will have a pretty >good programming feature set, and will be more reliable >(especially if it isn't just ksh by another name.) . . . Infidel. While I sure feel that way about csh(1), it surprises me you'd criticize ksh(1) so. 'Fact, 'mong all the *sh-s, I *recommend* ksh for programming. May- be the two of us see things differently. From tjreedy at udel.edu Mon Jun 6 15:20:33 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 6 Jun 2005 15:20:33 -0400 Subject: Destructive Windows Script References: Message-ID: "Dennis Lee Bieber" wrote in message news:ioh7a1liqm1qpu0a1l0qmmb7n3gqehtl26 at 4ax.com... > My previous facility didn't even accept mil-spec wipes -- all > disk drives leaving the facility had to go through a demagnitizer, OT but I am curious: does a metallic case act as a metallic shield, so that the case needs to be opened to do this? (Conversely, is a magnet near a disk drive a danger to it?) > wiped everything, including control tracks, and played with the > R/W head and positioning magnets. I take this to mean the the drive is non-functional and might have well been melted, except that demagnetising is cheaper. TJR From christoph.rackwitz at gmail.com Wed Jun 15 13:13:33 2005 From: christoph.rackwitz at gmail.com (Christoph Rackwitz) Date: 15 Jun 2005 10:13:33 -0700 Subject: New WYSIWYG Python IDE in the works References: Message-ID: <1118855613.799063.137200@o13g2000cwo.googlegroups.com> root wrote: > Hello all > > I am currently developing a new WYSIWYG RAD tool for python. > There are screenshots and a small video demo on the site. > Please visit at http://www.geocities.com/visualfltk > > Cheers > JMan From kent37 at tds.net Sun Jun 5 22:07:38 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Jun 2005 22:07:38 -0400 Subject: Iterate through a list calling functions In-Reply-To: <1117993793.371018.200280@g47g2000cwa.googlegroups.com> References: <1117993793.371018.200280@g47g2000cwa.googlegroups.com> Message-ID: <42a3afa6$1_1@newspeer2.tds.net> George Sakkis wrote: > That's a typical case for using an OO approach; just make a class for > each validator and have a single polymorphic validate method (I would > make validators __call__able instead of naming the method 'validate'): > > # Abstract Validator class; not strictly necessary but good for > documentation > class Validator(object): > def __call__(self,field,value): > '''Validate a value for this field. > Return a string representation of value on success, or None on > failure. > ''' > raise NotImplementedError("Abstract method") > > > class DecimalValidator(Validator): > def __call__(self,name,value): > '''Test whether numeric value is a decimal.''' Why is this better than an isDecimal function? def isDecimal(name, value): ''' Test whether numeric value is a decimal.''' seems simpler and more straightforward to me. > def validateField(name, value, validators): > """ Validates field input """ > results = {} > for validate in validators: > result = validate(name,value) > if result is not None: > results[name] = result > # XXX: if more than one validators succeed, > # all but the last result will be overwritten > return results No change needed in the loop above... > > # test > validators = [DecimalValidator(), ZipCodeValidator()] validators = [ isDecimal, isZipCode ] Kent From simonwittber at gmail.com Wed Jun 1 04:40:22 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 1 Jun 2005 01:40:22 -0700 Subject: pickle alternative In-Reply-To: References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <1117524878.988878.181820@g44g2000cwa.googlegroups.com> <1117527950.319411.193030@g44g2000cwa.googlegroups.com> <1117606128.506536.234690@g14g2000cwa.googlegroups.com> Message-ID: <1117615222.581838.226820@g49g2000cwa.googlegroups.com> Andrew Dalke wrote: > This is with Python 2.3; the stock one provided by Apple > for my Mac. Ahh that is the difference. I'm running Python 2.4. I've checked my benchmarks on a friends machine, also in Python 2.4, and received the same results as my machine. > I expected the numbers to be like this because the marshal > code is used to make and read the .pyc files and is supposed > to be pretty fast. It would appear that the new version 1 format introduced in Python 2.4 is much slower than version 0, when using the dumps function. Thanks for your feedback Andrew! Sw. From correiajREMOVECAPS at hotmail.com Tue Jun 7 14:47:07 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Tue, 07 Jun 2005 18:47:07 GMT Subject: separate IE instances? References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> <1118165668.863841.291290@z14g2000cwz.googlegroups.com> Message-ID: "Chris Curvey" wrote in message news:1118165668.863841.291290 at z14g2000cwz.googlegroups.com... > I would have given up on this a long time ago, but I can create two > IEXPLORE processes simultaneously (and get the behavior I want) by just > manually launching them from the Start menu. (Of course, that doesn't > mean that I can launch them programmatically, but I'm hoping that > someone can give me a definitive answer.) > Right, I hadn't quite understood your problem when I posted my reply. The code posted does work and allow navigation, etc. but you do have the problem with it sharing the same session cookies (I'm also on Win2k). And to answer Martin, you can definitely create as many iexplore.exe instances as you like in Windows. How to get Python to launch several instances with COM... not sure, although I'm 99% certain it is doable. I'll hunt around and see if I can find a solution which I'll post back. J From peter at engcorp.com Fri Jun 24 10:20:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 10:20:14 -0400 Subject: Favorite non-python language trick? In-Reply-To: <1119618780.475725.22580@o13g2000cwo.googlegroups.com> References: <1119618780.475725.22580@o13g2000cwo.googlegroups.com> Message-ID: utabintarbo at gmail.com wrote: >>with colour do begin >>red := 0; blue := 255; green := 0; >>end; >> >>instead of: >> >>colour.red := 0; colour.blue := 255; colour.green := 0; > > Why not: > from color import * > > red := 0 > blue := 255 > green := 0 What do you think this actually does? It doesn't do anything remotely resembling either of the things quoted above. In fact, the "from color import *" line is pretty much useless here. -Peter From bardinjw at yahoo.com Wed Jun 22 19:05:24 2005 From: bardinjw at yahoo.com (jim bardin) Date: Wed, 22 Jun 2005 16:05:24 -0700 (PDT) Subject: Is this a bug? I don't know where to start Message-ID: <20050622230524.82193.qmail@web52809.mail.yahoo.com> Is this a python bug, or do i not understand something? http://www.linuxquestions.org/questions/showthread.php?s=&threadid=336118 It seems to me that this should output each value once, but i get some seemingly random duplicates. If it is a bug, what do i file it under. I don't know what's wrong to cause this. thanks jim From rupole at hotmail.com Fri Jun 24 03:44:44 2005 From: rupole at hotmail.com (Roger Upole) Date: Fri, 24 Jun 2005 03:44:44 -0400 Subject: connecting to an exsisting COM server References: <1119549198.624156.171130@f14g2000cwb.googlegroups.com> Message-ID: <42bbbaf6$1_1@spool9-west.superfeed.net> Normally you get that if the application doesn't register itself with the Running Object Table. Do you know if the COM server in question registers itself ? Roger "jelle" wrote in message news:1119549198.624156.171130 at f14g2000cwb.googlegroups.com... > Hi, > > I'm using > win32com.client.GetObject(Class='Rhino3.Application') > to connect to an existing COM server. However when doing so: > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\site-packages\win32com\client\__init__.py", > line 80, in GetActiveObject > dispatch = pythoncom.GetActiveObject(resultCLSID) > com_error: (-2147221021, 'Operation unavailable', None, None) > > A com_error is raised. This problem has come up a few times on this > list, however that didn't help me to find a way of connecting to it. > What else could I try? > > Cheers, > > Jelle > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From benji at benjiyork.com Tue Jun 21 21:09:56 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 21 Jun 2005 21:09:56 -0400 Subject: Need Python web hosting ASAP In-Reply-To: <42B8B598.4000909@oz.net> References: <42B8B598.4000909@oz.net> Message-ID: <42B8BA64.4000007@benjiyork.com> I have been *very* happy with Hard Hat Hosting (http://hardhathosting.com). (I don't have any connection with them, other than being a satisfied customer for several years.) If you want more providers you might be interested in http://wiki.python.org/moin/PythonHosting. -- Benji York From donn at u.washington.edu Fri Jun 24 16:16:43 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 24 Jun 2005 13:16:43 -0700 Subject: trouble subclassing str References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> <1119619726.756391.175800@z14g2000cwz.googlegroups.com> <1119638083.069776.249140@g43g2000cwa.googlegroups.com> Message-ID: In article <1119638083.069776.249140 at g43g2000cwa.googlegroups.com>, "Paul McGuire" wrote: ... > This reminds me of some maddening O-O discussions I used to > have at a former place of employment, in which one developer cited > similar behavior for not having Square inherit from Rectangle - calling > Square.setWidth() would have to implicitly call setHeight() and vice > versa, in order to maintain its squarishness, and thereby broke Liskov. > I withdrew from the debate, citing lack of context that would have > helped resolve how things should go. At best, you can *probably* say > that both inherit from Shape, and can be drawn, have an area, a > bounding rectangle, etc., but not either inherits from the other. This Squares and Rectangles issue sounds debatable in a language like C++ or Java, where it's important because of subtype polymorphism. In Python, does it matter? As a user of Square, I'm not supposed to ask about its parentage, I just try to be clear what's expected of it. There's no static typing to notice whether Square is a subclass of Rectangle, and if it gets out that I tried to discover this issubclass() relationship, I'll get a lecture from folks on comp.lang.python who suspect I'm confused about polymorphism in Python. This is a good thing, because as you can see it relieves us of the need to debate abstract principles out of context. It doesn't change the real issues - Square is still a lot like Rectangle, it still has a couple of differences, and the difference could be a problem in some contexts designed for Rectangle - but no one can fix that. If you need Square, you'll implement it, and whether you choose to inherit from Rectangle is left as a matter of implementation convenience. Donn Cave, donn at u.washington.edu From steve at Foxhunt.com Tue Jun 28 20:41:57 2005 From: steve at Foxhunt.com (Steve Burke) Date: Tue, 28 Jun 2005 17:41:57 -0700 Subject: 6+ Month Python UI Contract Position in Mountain View, CA Message-ID: <465FE6B11AD0214A85CF3C009F9498FFB26725@foxhunt-exch.impactdom.local> I have a client in Mountain View, CA looking for an engineer who can work as part of a small team to develop a UI for a remote management/monitoring application for a new generation of Windows appliance. The work will involve application coding (Python on Apache), UI design documentation, and UI hands-on coding. The client's product is an appliance that ensures continuity of operations for mission-critical Microsoft applications. The required experience includes Python experience, UI development experience with non-Java technologies, and some experience developing web-based and/or keypad UIs for embedded Linux appliances. Development experience with remotely managed or "headless" systems would be a plus. If anyone is interested in this work, please forward your resume to me. Thanks very much. Regards, Steve Burke Sr. Recruiter Foxhunt Staffing, Inc. (650) 988-0339 x104 (650) 988-0354 fax steve at foxhunt.com www.foxhunt.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From JOHNWUN at aol.com Wed Jun 15 13:28:17 2005 From: JOHNWUN at aol.com (Grooooops) Date: 15 Jun 2005 10:28:17 -0700 Subject: Programmatic links in a TKinter TextBox In-Reply-To: References: <1118851935.958133.152710@g43g2000cwa.googlegroups.com> Message-ID: <1118856497.319705.62760@g14g2000cwa.googlegroups.com> Many thanks Jeff!!! This is what should be in the TK docs. Your example was very clear. And now I've learned some new stuff... :) For my project, I needed to add three pieces of data per link like this: text.insert(Tkinter.END, "link", ("a", "href:"+href,"another:This Is More Data", "last:and one more bit for fun")) I tweaked the above example here to catch multiple bits by adding a couple elif statements to the for loop, and removing the break lines. def click(event): w = event.widget x, y = event.x, event.y tags = w.tag_names("@%d,%d" % (x, y)) for t in tags: if t.startswith("href:"): print "clicked href %s" % t[5:] #commented out the break elif t.startswith("another:"): print "clicked href %s" % t[8:] # commented out the break elif t.startswith("last:"): print "clicked href %s" % t[5:] else: print "clicked without href" return "break" Thanks again, I hope others will find this as useful as I did.. From google at connes.org Tue Jun 28 15:59:24 2005 From: google at connes.org (Arthur Chereau) Date: 28 Jun 2005 12:59:24 -0700 Subject: Problem building Python bindings for subversion Message-ID: <1119988764.695754.52530@g44g2000cwa.googlegroups.com> Hi, I'm trying to setup viewcvs to work with subversion 1.2.0 on Linux with Python 2.4.1. The last viewcvs (from CVS) needs subversion python bindings. I installed swig and built subversion from source with it. Everything works fine until I try to build the Python bindings. When I try "make swig-py" I get the following, Python related, error: # make swig-py /bin/sh /usr/src/subversion-1.2.0/libtool --tag=CC --silent --mode=compile gcc -DLINUX=2 -D_REENTRANT -D_XOPEN_SOURCE=500 -D_BSD_SOURCE -D_SVID_SOURCE -D_GNU_SOURCE -DSWIGPYTHON -g -O2 -g -O2 -pthread -DNEON_ZLIB -DNEON_SSL -I/usr/src/subversion-1.2.0/subversion/bindings/swig -I/usr/src/subversion-1.2.0/subversion/include -I/usr/swig/share/swig/1.3.25 -DSVN_SWIG_VERSION=103025 -DSWIG_TABLE_TYPE=subversion -I/usr/src/subversion-1.2.0/apr/include -I/usr/src/subversion-1.2.0/apr-util/include -I/usr/Python/include/python2.4 -I/usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py -I./subversion/include -I./subversion -I/usr/src/subversion-1.2.0/neon/src -I/usr/subversion/include/neon -I/usr/src/subversion-1.2.0/apr/include -I/usr/src/subversion-1.2.0/apr-util/include -o subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.lo -c /usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.c In file included from /usr/Python/include/python2.4/Python.h:8, from /usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.c:20: /usr/Python/include/python2.4/pyconfig.h:844: warning: `_XOPEN_SOURCE' redefined *Initialization*:1: warning: this is the location of the previous definition In file included from /usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.c:44: /usr/swig/share/swig/1.3.25/runtime.swg:28: macro `SWIG_GetModule' used without args /usr/swig/share/swig/1.3.25/runtime.swg:34: macro `SWIG_GetModule' used without args make: *** [subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.lo] Error 1 Is there something I'm doing wrong ? Thanks, AC From Scott.Daniels at Acm.Org Sun Jun 12 12:17:56 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 12 Jun 2005 09:17:56 -0700 Subject: checking for when a file or folder exists, typing problems? In-Reply-To: References: Message-ID: <42ac591a$1@nntp0.pdx.net> Bryan Rasmussen wrote: > ... at one point in my program I check if a file exists using > if exists("c:\projects"): You should not be using a backslash in non-raw-string source to mean anything but "escape the next character." The above should either be written as: if exists(r"c:\projects"): or: if exists("c:\\projects"): I suspect you problem has to do with this difference, but perhaps not. Give exact short code that actually demonstrates the problem. --Scott David Daniels Scott.Daniels at Acm.Org From http Fri Jun 17 21:07:49 2005 From: http (Paul Rubin) Date: 17 Jun 2005 18:07:49 -0700 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> Message-ID: <7xr7f0o4ka.fsf@ruckus.brouhaha.com> "cpunerd4" writes: > I stumbled onto the python language by chance and it looks like a > great language. Although from what I've read so far (which isn't much) > I've guessed that python is purely an interpreted language unless its > compiled into another language (ie. it needs python installed in order > to run programs). Is this correct? Yes, you need to install Python one way or another. > If it is, I guess my plan of action > would be to use python embeded in java applets. Just install Python and use it. There's a Java/Python implementation called Jython but don't worry about it for now. > Another question I have: Does any one know any really good, really > easy to understand python books? Try "Dive Into Python", www.diveintopython.org (site is very slow right now, try later). Also the online tutorial, http://docs.python.org/tut/tut.html is pretty good, though not in as much depth. > P.S. I'm 14 and I know HTML, PHP, and I know about many others! If you're good at PHP, then Python shouldn't be much trouble. From chad.hughes at pnl.gov Fri Jun 17 13:22:05 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Fri, 17 Jun 2005 10:22:05 -0700 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6196@pnlmse27.pnl.gov> Are you sure about the lower-case thing. The original post states "Perlhead" and there are many instances at www.Perl.com where O'REILLY spells perl as Perl. Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of Steven D'Aprano Sent: Friday, June 17, 2005 10:02 AM To: python-list at python.org Subject: RE: Overcoming herpetophobia (or what's up w/ Python scopes)? On Fri, 17 Jun 2005 09:36:55 -0700, Hughes, Chad O wrote: > I am very familiar with Python, but I don't know Pearl. The language is *always* spelt without the "a", and usually all in lower-case: perl. Now that I've taught you everything I know about perl, you can be an expert like me -- Steven -- http://mail.python.org/mailman/listinfo/python-list From greg at cosc.canterbury.ac.nz Thu Jun 2 23:14:17 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Fri, 03 Jun 2005 15:14:17 +1200 Subject: [python-gtk] problem with multiple inheritance In-Reply-To: References: Message-ID: <3ga08nFb9gavU1@individual.net> Taki Jeden wrote: > class view_tree_model(gtk.GenericTreeModel,gtk.TreeSortable): > > raises a "TypeError: multiple bases have instance lay-out conflict" > Is this a bug in gtk, or python-gtk, or something? It's not a bug, it's a limitation of the way Python handles inheritance from built-in types. You can only inherit from more than one built-in type if they have compatible C structures, and it appears that the two you're trying to inherit from aren't compatible. You'll have to think of some way of doing whatever you're trying to do without inheriting from multiple gtk types. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From kai.festersen at zdftheaterkanal.de Wed Jun 22 06:23:04 2005 From: kai.festersen at zdftheaterkanal.de (kai festersen) Date: Wed, 22 Jun 2005 12:23:04 +0200 Subject: Installing MySQL-Python In-Reply-To: <1119402324.019970.42590@g43g2000cwa.googlegroups.com> References: <1119402324.019970.42590@g43g2000cwa.googlegroups.com> Message-ID: Cathy Hui wrote: > Do u know why do i get the following message error: command 'gcc' failed with exit status 1 yes: error: command 'gcc' failed with exit status 1 means: there's no compiler gcc ... kai when trying to build the > MySql-Python (1.2.0) on my Solaris 8 system? (with mysql 4.0.21 and > python 2.4). thanks! > > error mesg: > ld: fatal: relocations remain against allocatable but non-writable > sections > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > > > see below for the log > ===================================================== > > > # python setup.py build > > unknown> 0x5c8 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0x840 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0x84c > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0x9b4 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0x9bc > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0x9f8 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0xa04 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0xa98 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0xaac > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0xad0 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0xae0 > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > 0xb0c > /usr/local/mysql/lib/mysql/libmysqlclient_r.a(default.o) > . > . > . > > ld: fatal: relocations remain against allocatable but non-writable > sections > collect2: ld returned 1 exit status > error: command 'gcc' failed with exit status 1 > From bjtexas at hotmail.com Tue Jun 28 14:31:03 2005 From: bjtexas at hotmail.com (BJ in Texas) Date: Tue, 28 Jun 2005 18:31:03 GMT Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: muldoon wrote: || Americans consider having a "British accent" a sign of || sophistication and high intelligence. Many companies hire || salespersons from Britain to represent their products,etc. || Question: When the British hear an "American accent," does it || sound unsophisticated and dumb? || || Be blunt. We Americans need to know. Should we try to change || the way we speak? Are there certain words that sound || particularly goofy? Please help us with your advice on this || awkward matter. Which of the British accents? BJ From fingermark at gmail.com Tue Jun 7 06:02:19 2005 From: fingermark at gmail.com (fingermark at gmail.com) Date: 7 Jun 2005 03:02:19 -0700 Subject: Trouble Encoding Message-ID: <1118135690.961381.207490@o13g2000cwo.googlegroups.com> I'm using feedparser to parse the following:
Adv: Termite Inspections! Jenny Moyer welcomes you to her HomeFinderResource.com TM A "MUST See &hellip;
I'm receiveing the following error when i try to print the feedparser parsing of the above text: UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in position 86: ordinal not in range(256) Why is this happening and where does the problem lie? thanks From dave.opstad at monotypeimaging.com Wed Jun 22 16:24:56 2005 From: dave.opstad at monotypeimaging.com (Dave Opstad) Date: Wed, 22 Jun 2005 13:24:56 -0700 Subject: Odd slicing behavior? References: <3htv6gFips59U1@uni-berlin.de> Message-ID: In article <3htv6gFips59U1 at uni-berlin.de>, "Diez B. Roggisch" wrote: > So - the rationale seems to be: "When using slice-assignment, a form > like l[a:b:c] imposes possibly a non-continous section in l, for which > the semantics are unclear - so we forbid it" But it isn't forbidden: >>> v = range(10) >>> v [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> v[0:10:3] = ['a', 'b', 'c', 'd'] >>> v ['a', 1, 2, 'b', 4, 5, 'c', 7, 8, 'd'] The only time it's actively forbidden is when the length of the slice and the length of the list being assigned to it don't match. I agree with you that it might be nice for [a:b:1] and [a:b] to be treated synonymously. Dave From lambacck at gmail.com Sun Jun 5 21:12:57 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Sun, 5 Jun 2005 21:12:57 -0400 Subject: Destructive Windows Script In-Reply-To: References: Message-ID: The reason they are slow and tedious is that they need to write to every byte on the disk. Depending on the size of the disk, there may be a lot of data that needs to be written, and if they are older computers, write speed may not be particularly fast. -Chris On 6/5/05, rbt wrote: > Roose wrote: > > My guess would be: extremely, extremely easy. Since you're only writing 30 > > bytes for each file, the vast majority of the data will still be present on > > disk, just temporarily inaccessible because of the del command. And more > > than likely it will be possible to recover 100% if they are using a > > journaling file system like NTFS, which Windows XP does. > > > > If you are honestly trying to destroy your own data, go out and download a > > free program that will do it right. If you're trying to write some kind of > > trojan, well you've got a lot of learning to do. :) > > Thanks for the opinion... I don't do malware. Just interested in > speeding up file wiping (if possible) for old computers that will be > auctioned. The boot programs that you allude to (killdisk, autoclave) > work well, but are slow and tedious. If this can be done *properly* in > Python, I'd like to have a go at it. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From twic at urchin.earth.li Thu Jun 16 09:29:49 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 16 Jun 2005 14:29:49 +0100 Subject: What is different with Python ? (OT I guess) In-Reply-To: References: <42AED7B3.8060009@carmen.se> Message-ID: On Wed, 15 Jun 2005, Terry Hancock wrote: > On Tuesday 14 June 2005 08:12 am, Magnus Lycka wrote: > >> Oh well, I guess it's a bit late to try to rename the Computer >> Science discipline now. > > Computer programming is a trade skill, not a science. It's like > being a machinist or a carpenter --- a practical art. A lot of universities teach 'software engineering'. I draw a distinction between this and real computer science - computer science is the abstract, mathematical stuff, where you learn to prove your programs correct, whereas software engineering is more practical, where you just learn to write programs that work. Of course, CS does have quite a practical element, and SE has plenty of theory behind it, but they differ in emphasis. SE departments tend to grow out of electronics engineering departments; CS departments tend to bud off from maths departments. > Unfortunately, our society has a very denigrative view of craftsmen, and > does not pay them well enough, so computer programmers have been > motivated to attempt to elevate the profession by using the appellative > of "science". > > How different would the world be if we (more accurately) called it > "Computer Arts"? At one point, a friend and i founded a university to give our recreational random hackery a bit more credibility (well, we called ourself a university, anyway; it was mostly a joke). We called the programming department 'Executable Poetry'. tom -- Punk's not sexual, it's just aggression. From tjreedy at udel.edu Thu Jun 2 18:31:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Jun 2005 18:31:29 -0400 Subject: optparse.py: FutureWarning error References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> Message-ID: "kosuke" wrote in message news:1117722584.910599.242900 at g47g2000cwa.googlegroups.com... >I keep getting the following error/warning message when using the > python based program getmail4: > > /usr/lib/python2.3/optparse.py:668: FutureWarning: %u/%o/%x/%X of > negative int will return a signed string in Python 2.4 and up > return ("<%s at 0x%x: %r>" > > I'm using python2.3.5 on a debian sid box. > > The getmail4 website/FAQ maintains that this is a bug in the optparse > module. > > Any idea on how to resolve this? a) Learn to live with it ;-) b) Upgrade to 2.4 (if getmail4 will run with it) c) Check to see if Python has a startup option for suppressing warnings As to c) python -h gives a list indicating what I thought, that -W controls warnings, but gives insufficient info for me to use it, and I didn't find any more in the docs. I hope someone else chimes in. Terry J. Reedy Terry J. Reedy From agriff at tin.it Mon Jun 13 02:32:10 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 13 Jun 2005 06:32:10 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: <669qa1pco0ktsplldikhf6ugire9nielc6@4ax.com> On Sun, 12 Jun 2005 21:52:12 -0400, Peter Hansen wrote: >I'm curious how you learned to program. An HP RPN calculator, later TI-57. Later Apple ][. With Apple ][ after about one afternoon spent typing in a basic program from a magazine I gave up with basic and started with 6502 assembler ("call -151" was always how I started my computer sessions). >What path worked for you, and do you think it was >a wrong approach, or the right one? I was a fourteen with no instructor, when home computers in my city could be counted on the fingers of one hand. Having an instructor I suppose would have made me going incredibly faster. Knowing better the english language at that time would have made my life also a lot easier. I think that anyway it was the right approach in terms of "path", not the (minimal energy) approach in terms of method. Surely a lower energy one in the long run comparing to those that started with basic and never looked at lower levels. >In my case, I started with BASIC. Good old BASIC, with no memory >management to worry about, no pointers, no "concrete" details, just FOR >loops and variables and lots of PRINT statements. That's good as an appetizer. >A while (some months) later I stumbled across some assembly language and >-- typing it into the computer like a monkey, with no idea what I was >dealing with -- began learning about some of the more concrete aspects >of computers. That is IMO a very good starting point. Basically it was the same I used. >This worked very well in my case, and I strongly doubt I would have >stayed interested in an approach that started with talk of memory >addressing, bits and bytes, registers and opcodes and such. I think that getting interested in *programming* is important... it's like building with LEGOs, but at a logical level. However that is just to get interest... and a few months with basic is IMO probably too much. But after you've a target (making computers do what you want) then you've to start placing solid bricks, and that is IMO assembler. Note that I think that any simple assembler is OK... even if you'll end up using a different processor when working in C it will be roughly ok. But I see a difference between those that never (really) saw assembler and those that did. >I won't say that I'm certain about any of this, but I have a very strong >suspicion that the *best* first step in learning programming is a >program very much like the following, which I'm pretty sure was mine: > >10 FOR A=1 TO 10: PRINT"Peter is great!": END Just as a motivation. After that *FORGETTING* that (for and the "next" you missed) is IMO perfectly ok. >More importantly by far, *I made the computer do something*. Yes, I agree. But starting from basic and never looking lower is quit a different idea. Andrea From jepler at unpythonic.net Thu Jun 2 13:51:51 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 2 Jun 2005 12:51:51 -0500 Subject: Unicode string in exec In-Reply-To: <1117687496.341548.117760@g14g2000cwa.googlegroups.com> References: <1117687496.341548.117760@g14g2000cwa.googlegroups.com> Message-ID: <20050602175148.GC19350@unpythonic.net> First off, I just have to correct your terminology. "exec" is a statement, and doesn't require parentheses, so talking about "exec()" invites confusion. I'll answer your question in terms of eval(), which takes a string representing a Python expression, interprets it, and returns the result. In Python 2.3, the following works right: >>> eval(u"u'\u0190'") u'\u0190' Here, the string passed to eval() contains the literal LATIN CAPITAL LETTER OPEN E, and the expected unicode string is returned The following behaves "surprisingly": >>> eval(u"'\u0190'") '\xc6\x90' ... you seem to get the UTF-8 encoding of the unicode. This is related to PEP 263 (http://www.python.org/peps/pep-0263.html) but the behavior of compile(), eval() and exec don't seem to be spelled out. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From newsgroups at jhrothjr.com Mon Jun 13 23:01:59 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 13 Jun 2005 21:01:59 -0600 Subject: "also" to balance "else" ? References: Message-ID: <11asi5cps42vfe5@news.supernews.com> "Ron Adam" wrote in message news:H6pre.131217$IO.122689 at tornado.tampabay.rr.com... > Currently the else block in a for loop gets executed if the loop is > completed, which seems backwards to me. I would expect the else to > complete if the loop was broken out of. That seems more constant with > if's else block executing when if's condition is false. Actually, it makes sense if you look at it correctly. In an unadorned loop, exits via break and via the loop condition becoming false go to the same place. To distinguish requires some kind of a switch. In a loop with an else, exits via break skip the else clause, while an exit via the loop condition takes the else clause. You don't need a special exit on break since you can put any amount of logic after the if and in front of the break. Where you need it is on exit via the loop condition. The difficulty you're having with this is that else is a very bad keyword for this particular construct. I'd prefer something like "on normal exit" as a keyword. John Roth From rkern at ucsd.edu Fri Jun 10 15:26:16 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 10 Jun 2005 12:26:16 -0700 Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <42A9DAC3.2010306@anvilcom.com> Message-ID: Andrew Dalke wrote: > Robert Kern wrote: > >>There is no moderator. We are all moderators. > > I am Spartacus! > > We are all Kosh. Well, if we're starting on the Vorlon quotes, this one seems germane: "The avalanche has already begun. It is too late for the pebbles to vote." -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fredrik at pythonware.com Sat Jun 18 06:36:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 18 Jun 2005 12:36:54 +0200 Subject: utf8 and ftplib References: <11b3ftrea0k2e29@news.supernews.com> <1119001242.31248.236579821@webmail.messagingengine.com> Message-ID: Richard Lewis wrote: > OK, I've fiddled around a bit more but I still haven't managed to get it > to work. I get the fact that its not the FTP operation thats causing the > problem so it must be either the xml.minidom.parse() function (and > whatever sort of file I give that) or the way that I write my results to > output files after I've done my DOM processing. I'll post some more > detailed code: > > def open_file(file_name): > ftp = ftplib.FTP(self.host) > ftp.login(self.login, self.passwd) > > content_file = file(file_name, 'w+b') > ftp.retrbinary("RETR " + self.path, content_file.write) > ftp.quit() > content_file.close() > > ## Case 1: > #self.document = parse(file_name) > > ## Case 2: > #self.document = parse(codecs.open(file_name, 'r+b', "utf-8")) > > # Case 3: > content_file = codecs.open(file_name, 'r', "utf-8") > self.document = parse(codecs.EncodedFile(content_file, "utf-8", > "utf-8")) > content_file.close() > > In Case1 I get the incorrectly encoded characters. case 1 is the only one where you use the XML parser as it is designed to be used (on the stream level, XML is defined in terms of encoded text, not Unicode characters. the parser will decode things for you) given that he XML tree returned by the parser contains *decoded* Uni- code characters (in Unicode string objects), what makes you so sure that you're getting "incorrectly encoded characters" from the parser? (I wonder why this is so hard for so many people? hardly any programmer has any problem telling the difference between, say, a 32-bit binary floating point value on disk, a floating point object, and the string representation of a float. but replace the float with a Unicode character, and anglocentric programmers immediately resort to poking-with-a-stick-in-the-dark programming. I'll figure it out, some day...) From gsakkis at rutgers.edu Mon Jun 13 02:05:24 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jun 2005 23:05:24 -0700 Subject: count string replace occurances References: <1118620538.711624.237680@z14g2000cwz.googlegroups.com> Message-ID: <1118642724.101379.269450@f14g2000cwb.googlegroups.com> "Jeff Epler" wrote: > On Sun, Jun 12, 2005 at 04:55:38PM -0700, Xah Lee wrote: > > if i have > > mytext.replace(a,b) > > how to find out many many occurances has been replaced? > > The count isn't returned by the replace method. You'll have to count > and then replace. > > def count_replace(a, b, c): > count = a.count(b) > return count, s.replace(b, c) > > >>> count_replace("a car and a carriage", "car", "bat") > (2, 'a bat and a batriage') I thought naively that scanning a long string twice would be almost twice as slow compared to when counting was done along with replacing. Although it can done with a single scan, it is almost 9-10 times slower, mainly because of the function call overhead; the code is also longer: import re def count_replace_slow(aString, old, new): count = [0] def counter(match): count[0] += 1 return new replaced = re.sub(old,counter,aString) return count[0], replaced A good example of trying to be smart and failing :) George From wesleyhenwood at hotmail.com Thu Jun 30 10:52:04 2005 From: wesleyhenwood at hotmail.com (Wesley Henwood) Date: 30 Jun 2005 07:52:04 -0700 Subject: python commmand line params from c++ Message-ID: <1120143124.925422.290980@g44g2000cwa.googlegroups.com> What is the proper way to pass command line parameters to a python script called from C++? I'm tryng this: path = "c:\\someDir\\someScript.py param1 param2 param3"; PyRun_SimpleFile(PyFile_AsFile( PyFile_FromString( path, "r")), "someScript.py"); I'm getting a "format error someScript.py, line 1" when the code is executed. Note: The strange appearannce of the 3 python function calls nested is not a bug, but required to prevent a run-time error. From bronger at physik.rwth-aachen.de Fri Jun 24 15:50:29 2005 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 24 Jun 2005 21:50:29 +0200 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: <87k6kjy1oa.fsf@wilson.rwth-aachen.de> Hall?chen! Jeffrey Maitland writes: > [...] > > { > for(int i = 0; i < 100; i++){ > //do stuff > } > } > > wrapping the for loop in { } makes the i a local variable It's local anyway. > and then you can use it again in the code if not you will get a > variable already defined error. Only in compilers created by this infamous company. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus From fuzzyman at gmail.com Wed Jun 29 17:46:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jun 2005 14:46:31 -0700 Subject: Inheriting from object In-Reply-To: <42c30ea5$0$31301$636a15ce@news.free.fr> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> Message-ID: <1120081591.319266.10200@z14g2000cwz.googlegroups.com> So theres no actual advantage that you know of ;-) Surely when they are removed : class foo: pass won't become invalid syntax, it will just automatically inherit from object ? That's what I assumed, anyway.... Regards, Fuzz http://www.voidspace.org.uk/python From benji at benjiyork.com Tue Jun 21 09:28:13 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 21 Jun 2005 09:28:13 -0400 Subject: Python can do it for me? In-Reply-To: <1119357359.145942.139840@g43g2000cwa.googlegroups.com> References: <1119357359.145942.139840@g43g2000cwa.googlegroups.com> Message-ID: <42B815ED.7090402@benjiyork.com> silasju at gmail.com wrote: > MySQL or Potsgree SQL ***remote connection***(it's the most important). > GUI interface. > Report generator. > Barcode printing. I've done all of these very successfully in Python. > Maybe PyGTK can do it for me? What do you think? I've never used PyGTK, but it looks nice. I've generally stuck with wxPython. -- Benji York From danb_83 at yahoo.com Wed Jun 8 14:11:50 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 8 Jun 2005 11:11:50 -0700 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118251198.426673.108180@g49g2000cwa.googlegroups.com> Message-ID: <1118254310.375903.299930@g43g2000cwa.googlegroups.com> Mahesh wrote: > No, why should Python assume that if you use != without supplying a > __ne__ that this is what you want? Because every single time I've used __ne__, that *is* what I want. > Without direction it will compare > the two objects which is the default behavior. It's also the default behavior that x == y and x != y are mutally exclusive. From peter at engcorp.com Tue Jun 14 08:21:11 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 08:21:11 -0400 Subject: Where is Word? In-Reply-To: References: Message-ID: Guy Lateur wrote: > I need a way to get the path where MS Word/Office has been installed. I need > to start Word from a script (see earlier post), (Asking us to refer to some earlier post that may or may not even be available on our news servers isn't the best way to get us the info. A sentence or two summarizing would work best, I think.) Can you describe what the user is going to do after Word pops open with this file in it? Maybe there are simpler ways to do what you are trying to accomplish, aside from the specific issue of how to open Word itself. For example, maybe the work you plan to have the user accomplish can be done automatically by controlling Word with COM. -Peter From cpw28 at cam.ac.uk Thu Jun 2 10:53:00 2005 From: cpw28 at cam.ac.uk (Christopher Wood) Date: Thu, 02 Jun 2005 15:53:00 +0100 Subject: PYTHONSTARTUP and the -i command line option Message-ID: Greetings all, A quick query: as all sorts of stuff can be defined in a .pythonrc.py file or similar and called at python startup using the PYTHONSTARTUP environment variable, it's very useful and can enhance the interpreter experience greatly. However, executing a script using the -i command line option to put the Python interpreter into 'interactive mode' after script termination is also very useful. But these two things won't play together, as (by design, it seems) $PYTHONSTARTUP isn't read when the -i option is used, leaving me with an unenhanced Python interpreter environment after after script execution. Is the any way round this, other than editing all my scripts or manually loading the .pythonrc.py script in the interpreter? Thanks in advance for any hints! Chris Wood From no.spam at thanks.com Thu Jun 30 10:49:47 2005 From: no.spam at thanks.com (Mike P.) Date: Fri, 1 Jul 2005 00:49:47 +1000 Subject: map vs. list-comprehension References: <42c27238$0$26269$626a14ce@news.free.fr> <87irzxtqsp.fsf@lucien.dreaming> Message-ID: <42c4068c$0$21964$afc38c87@news.optusnet.com.au> "Bj?rn Lindstr?m" wrote in message news:87irzxtqsp.fsf at lucien.dreaming... > "F. Petitjean" writes: > > > res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] > > > > Hoping that zip will not be deprecated. > > Nobody has suggested that. The ones that are planned to be removed are > lambda, reduce, filter and map. Here's GvR's blog posting that explains > the reasons: > > http://www.artima.com/weblogs/viewpost.jsp?thread=98196 > That really sucks, I wasn't aware of these plans. Ok, I don't use reduce much, but I use lambda, map and filter all the time. These are some of the features of Python that I love the best. I can get some pretty compact and easy to read code with them. And no, I'm not a Lisp programmer (never programmed in Lisp). My background being largely C++, I discovered lambda, apply, map and filter in Python, although I had seen similar stuff in other functional languages like Miranda and Haskell. Also, I don't necessarily think list comprehensions are necessarily easier to read. I don't use them all that much to be honest. IMHO I'm not particularly happy with the way Python is going language wise. I mean, I don't think I'll ever use decorators, for example. Personally, in terms of language features and capabilities I think the language is fine. Not much (if anything needs to be added). I think at this stage the Python community and Python programmers would be better served by building a better, more standardised, cross platform, more robust, better documented, and more extensive standard library. I would be happy to contribute in this regard, rather than having debates about the addition and removal of language features which don't improve my productivity. I would love it if modules like PyOpenGL, PyOSG (Open Scene Graph), PyQt, a graph library etc, were all part of the standard python library, and that worked out of the box on all major platforms -Windows, Unix, Linux, Mac. All these modules which are C/C++ based are all at different versions and at different stages, requiring different versions of Python working on different operating systems. It's not as transparent as it should be. For example, why aren't PIL, Numeric and a host of other fairly mainstream Python modules not part of the standard library? Compare that with the huge SDK that comes with Java. Then there is always issues of performance, better standard development tools, better documentation. There are lots of things to do, to make the Python programmers life better without touching the actual features of the language. Sorry, I've probably gone way off topic, and probably stirred up political issues which I'm not aware of, but, man when I hear stuff like the proposed removal of reduce, lambda, filter and map, all I see ahead of me is a waste of time as a programmer. I don't program in Python for it's own sake. I program in Python because it lets me get my job done quicker and it saves me time. The proposed removals are going to waste my time. Why? Because my team and myself are going to have to go through all our code and change stuff like maps to ugly looking list comprehensions or whatever when Python 3000 comes out. Sure some of you will say you don't have to update, just stick with Python 2.3/2.4 or whatever. That is fine in theory, but in practice I'm going to have to use some third party module which will require Python 3000 (this happened to me recently with a module which had a serious bug with the Python 2.3 version, but worked with the Python 2.4 version - I had to upgrade every single third party module I was using - I was lucky the ones I was using had 2.4 versions, but there are still a lot of modules out there that don't). Sorry for the OT long rant. Mike From ChuckDubya at gmail.com Tue Jun 28 03:23:30 2005 From: ChuckDubya at gmail.com (ChuckDubya at gmail.com) Date: 28 Jun 2005 00:23:30 -0700 Subject: Newbie: Help Figger Out My Problem Message-ID: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> ##Coin Flip: randomly flips 100 "coins" and prints results ##Original draft: june 27, 2005 ##Chuck import random heads = 0 tails = 0 flips = 0 while flips < 99: coin = random.randrange(0, 2) if coin == 0: heads = heads + 1 else: tails = tails + 1 flips = flips + 1 if flips >= 99: print "Heads: " + heads print "Tails: " + tails print "Total: " + flips + "flips" raw_input("Press the enter key to exit.") When I save and run this "program", I get a DOS window that flashes at me and disappears. What's wrong with it? From philippe at philippecmartin.com Mon Jun 20 15:40:45 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 19:40:45 GMT Subject: Python choice of database References: <1119293008.907670.251570@g44g2000cwa.googlegroups.com> Message-ID: <1ZEte.198$5w3.124@newssvr11.news.prodigy.com> Yes, I agree, but as most of the customer base I target uses the O/S that cannot be named ;-) , file names could become a problem just as 'ln -s' is out of the question. Yet, this might be the best trade-off. Regards, Philippe Oren Tirosh wrote: > Philippe C. Martin wrote: >> Hi, >> >> I am looking for a stand-alone (not client/server) database solution for >> Python. >> >> 1) speed is not an issue >> 2) I wish to store less than 5000 records >> 3) each record should not be larger than 16K > > How about using the filesystem as a database? For the number of records > you describe it may work surprisingly well. A bonus is that the > database is easy to manage manually. One tricky point is updating: you > probably want to create a temporary file and then use os.rename to > replace a record in one atomic operation. > > For very short keys and record (e.g. email addresses) you can use > symbolic links instead of files. The advantage is that you have a > single system call (readlink) to retrieve the contents of a link. No > need to open, read and close. > > This works only on posix systems, of course. The actual performance > depends on your filesystem but on linux and BSDs I find that > performance easily rivals that of berkeleydb and initialization time is > much faster. This "database" also supports reliable concurrent access > by multiple threads or processes. > > See http://www.tothink.com/python/linkdb > > Oren From CousinStanley at HotMail.Com Thu Jun 23 17:32:09 2005 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Thu, 23 Jun 2005 14:32:09 -0700 Subject: Looking For Geodetic Python Software In-Reply-To: References: <447po2-iqt.ln1@eskimo.tundraware.com> Message-ID: <42bb2b4d$1_2@spool9-west.superfeed.net> | .... | 1) Given the latitude/longitude of two locations, compute the distance | between them. | | "Distance" in this case would be either the straight-line | flying distance, or the actual over-ground distance that accounts | for the earth's curvature. # --------------------------------------------------------------- NewsGroup .... alt.comp.freeware Date ......... 2003-12-28 Posted_By .... GRL Reply_By ..... Sascha Wostmann the formula is as follows: D = ACos((Sin(LA1)*Sin(LA2)) + (Cos(LA1)*Cos(LA2)*Cos(LO1-LO2))) * r with: LA1 / LA2 = latitude position 1 / 2 LO1 / LO2 = longitude 1 / 2 r = radius of earth (~ 6371 km = ~3958,75 miles) D = distance between locations (in km or miles depending on r) Source: somewhere below http://geoclassphp.sourceforge.net # ---------------------------------------------------------------- About 18 months ago I put together a couple of small Python programs to compute great circle distances from the above formula .... http://fastq.com/~sckitching/Python/gcircle.py [ 2.6 kb ] http://fastq.com/~sckitching/Python/gcircle_dms.py [ 3.4 kb ] The first prompts the user for Lat/Long in fixed point degrees. The second prompts the user of Lat/Long in degrees minutes seconds. I only checked a few distances known distances at the time, but they seemed to be OK .... -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From Scott.Daniels at Acm.Org Thu Jun 23 16:28:02 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 23 Jun 2005 13:28:02 -0700 Subject: key - key pairs In-Reply-To: References: Message-ID: <42bb13e3$1@nntp0.pdx.net> Florian Lindner wrote: > Hello, > is there in python a kind of dictionary that supports key - key pairs? > I need a dictionary in which I can access a certain element using two > different keys, both unique. > > For example: > > I've a dictionary with strings and times. Sometimes I have the string and I > want to have the time, other time I've the time and I want the string. It > is important that one of the keys supports the min/max builtin function. > > Thanks, > > Florian As Claudio suggests, you probably want to make a class with (at least) a pair of dictionaries. Are the strings one-to-one with the times? I am unsure of what you mean by "supports the min/max builtin function." If all you mean is, "can I get the min and/or max of the keys (strings or times), then a pair of dictionaries does it. If you mean "finds faster than linear," you need to say what operations are to be fastest, and whether you mean worst case or amortized. It is possible to make the fast operations most combinations of: "find least", "find greatest", "remove least", "remove greatest", "find arbitrary", "remove arbitrary", "add entry" Depending on your choice on costs, the data structure changes. --Scott David Daniels Scott.Daniels at Acm.Org From mrsani at mesa.com Sat Jun 18 15:15:22 2005 From: mrsani at mesa.com (Mrsani) Date: Sat, 18 Jun 2005 20:15:22 +0100 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> Message-ID: <1119121987.131b80ae9685ccc81cd29fe3170de805@teranews> > So true. Am I the only one who wonders this: If Python at runtime runs > very much like Java and has generally about the same > speed (or faster) rofl From newsuser at stacom-software.de Tue Jun 21 06:27:53 2005 From: newsuser at stacom-software.de (Alexander Eisenhuth) Date: Tue, 21 Jun 2005 12:27:53 +0200 Subject: Howto access a enumeration in a COM TypeLib Message-ID: Hello alltogether, I hope somebody can help me in that case. I bet I have overseen s.th.. I have a VC++ IDispatch Com-Server (ATL) and include for error handling issues a enumeration in the IDL-File. [...] enum PROG_ERROR { P_OK = 0, P_ERR_01 = 1, P_ERR_02 = 2, ... } typedef enum PROG_ERROR PROG_ERROR_T; [...] I can acess the COM object using : obj = win32com.client.Dispatch("...") and can Load the TypeLib: lib = pythonwin.LoadTypeLib("...") and see the enumeration in the OLE-Browser of Windows, but don't know how to access the enum in Python. Any help and hints are very welcome. Regards Alexander PS.: I use the actual version of ActivePython 2.4. From philippe at philippecmartin.com Tue Jun 28 12:11:24 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 16:11:24 GMT Subject: ANN: PyDev 0.9.5 released References: <42A720BD.5050701@esss.com.br> Message-ID: Thanks Fabio, I take this opportunity to ask what I could be doing wrong with pylint: my PYTHONPATH is good (I think), my code compiles and passes pylint when I run it by hand. Yet pylint in pydev does not seem to think the modules I include and usually derive from exist. Any clue ? Regards, Philippe Fabio Zadrozny wrote: > Hi All, > > PyDev - Python IDE (Python Development Enviroment for Eclipse) version > 0.9.5 has just been released. > > Check the homepage (http://pydev.sourceforge.net/) for more details. > > Release Highlights: > > - File encodings now follow the python convention > - Overview ruler now works > - Editor is synchronized when working in multiple windows with the same > file - Code folding improved > - Syntax highlighting is not confused by escaped quote + triple quote > anymore > - Insertion of parentheses now replaces selected text > - Some more bugs... > > Regards, > From future_retro at yahoo.co.uk Thu Jun 23 10:22:41 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 23 Jun 2005 07:22:41 -0700 Subject: python create WMI instances In-Reply-To: References: Message-ID: <1119536561.777787.59510@g47g2000cwa.googlegroups.com> Right I got it working. I had to put a printer port in aswell. I'll now look at a script to create printer ports. My goal is being able to query the printers on print server x and then recreate the printers (shares and ports) on print server y. Thanks, for all your help Tim, much appreciated. MW import win32com.client WBEM = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" + "." + r"\root\cimv2") printer = WBEM.Get("Win32_Printer").SpawnInstance_() printer.Properties_('DeviceID').Value = 'myprinter' printer.Properties_('DriverName').Value = 'HP 2000C' printer.Properties_('Location').Value = 'myoffice' printer.Properties_('Network').Value = 'True' printer.Properties_('Shared').Value = 'True' printer.Properties_('ShareName').Value = 'myprintershare' printer.Properties_('PortName').Value = 'IP_169.254.110.14' printer.Put_() From der.rudi at planet-dot-nl.no-spam.invalid Thu Jun 30 04:32:49 2005 From: der.rudi at planet-dot-nl.no-spam.invalid (DeRRudi) Date: Thu, 30 Jun 2005 08:32:49 +0000 (UTC) Subject: Open running processes References: Message-ID: > Tim Goldenwrote: > > Rudi. I, at least, am reading this via the mailing list, not > via Usenet nor via Google. This means that if you don't put > any kind of context in what you post, I have to guess at what > you're responding to. (All I see is the exact text you typed, > nothing else). > > Assuming that you're answering my question: why use mmap and > not just two events? I understand what your overall plan is, > and it looks like you have a way to solve it. It just seemed > that you might be able to achieve the same thing with two > events: one for maximize and one for minimize. Why would > this be better? Well, only because it seems to me slightly simpler > than one event and a separate mmap mechanism. But I've never > done what you're doing, so I may well be completely wrong. > > TJG > Hi Tim, I'm sorry did not realize it! U are right! (i believe) at first i put in the minimize for testing. I'm only using the maximize. But it seemed handy to do it this way and beeing abled to send over data from an other programm. That's what i want to use the mmap for. Or am i missing something. because i'm not really seeing what your point is. Because it is a complete different process what is calling the maximize (or minimize) i can't just create an event and call it (or can i?) Greetz From ggg at zzz.it Sun Jun 12 07:59:27 2005 From: ggg at zzz.it (deelan) Date: Sun, 12 Jun 2005 13:59:27 +0200 Subject: How to get/set class attributes in Python In-Reply-To: References: Message-ID: Kalle Anke wrote: > I'm coming to Python from other programming languages. I like to > hide all attributes of a class and to only provide access to them > via methods. (...) > Is this the "Pythonic" way of doing it or should I do it in a different > way or do I have to use setX/getX (shudder) the pythonic way is to use "property" (as others have already explained) only when is *stricly necessary*. this may clarify things up: "Python Is Not Java" HTH. -- deelan From d at e.f Mon Jun 13 23:19:19 2005 From: d at e.f (D H) Date: Mon, 13 Jun 2005 22:19:19 -0500 Subject: What is different with Python ? In-Reply-To: <6fasa1d9l1m4ifkn3nmo34j3eu6t1cmabe@4ax.com> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <42ade58b$0$25394$636a15ce@news.free.fr> <6fasa1d9l1m4ifkn3nmo34j3eu6t1cmabe@4ax.com> Message-ID: <8cOdnXxJn6Ah0TPfRVn-pg@comcast.com> Andrea Griffini wrote: > On Mon, 13 Jun 2005 22:23:39 +0200, Bruno Desthuilliers > wrote: > > >>Being familiar with >>fondamental *programming* concepts like vars, branching, looping and >>functions proved to be helpful when learning C, since I only had then to >>focus on pointers and memory management. > > > If you're a good programmer (no idea, I don't know > you and you avoided the issue) then I think you > wasted a lot of energy and neurons learning that way. > Even high-level scripting languages are quite far > from a perfect virtualization, and either the code > you wrote in them was terrible *OR* you were able > to memorize an impressive quantity of black magic > details (or you were just incredibly lucky ;-) ). The best race driver doesn't necessarily know the most about their car's engine. The best baseball pitcher isn't the one who should be teaching a class in physics and aerodynamics. Yes, both can improve their abilities by learning about the fundamentals of engines, aerodynamics, etc., but they aren't "bad" at what they do if they do not know the underlying principles operating. If you want to understand what engineers like programmers, and scientists approach their work, look up the structure-behavior-function framework. Engineers work from function (the effect something has on its environment, in this case the desired effect), to structure - how to consistently constrain behavior to achieve that desired function. Scientists, on the other hand, primarily work from structure and behavior to function. Here is an unknown plant - why does it have this particular structure or behavior? What is its function, or what in its environment contributed to its evolution? See descriptions of SBF by Cindy Hmelo and others. From claird at lairds.us Thu Jun 16 11:08:17 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 16 Jun 2005 15:08:17 GMT Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> <1118468625.619330.12540@f14g2000cwb.googlegroups.com> Message-ID: <4se8o2-ksq.ln1@lairds.us> In article <1118468625.619330.12540 at f14g2000cwb.googlegroups.com>, Kay Schluehr wrote: . . . >less expensive. Arguing that a Python project definitely needs less >programmers than the Java counterpart ( which is very cost effective >because you need less management and administration to lead them - >remember that a programmer is always cheap compared to a manager ). A . . . Kay, please parse this for me. Are you making the point that Java managers are intrinsically more available and/or cheaper than Python managers? From martin.witte at gmail.com Mon Jun 27 15:30:04 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 27 Jun 2005 12:30:04 -0700 Subject: Boss wants me to program In-Reply-To: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: <1119900604.826501.187860@o13g2000cwo.googlegroups.com> I guess you need a database plus GUI layer for your apps, you might look in to MS Access (or Open Office 2.0 Base, but this is still beta, so I don't think your boss will like that) for that From peter at engcorp.com Mon Jun 20 09:13:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Jun 2005 09:13:43 -0400 Subject: functions with unlimeted variable arguments... In-Reply-To: <1119218400.989803.230410@g47g2000cwa.googlegroups.com> References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> <7xr7f0yv0c.fsf@ruckus.brouhaha.com> <1119218400.989803.230410@g47g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > oops... it is in the tutorial... sorry. If you're sorry, have you now *finally* gone and worked through the rest of tutorial, making a serious attempt to learn it? > This is not a rhetorical question, but where would one start to look > for it in the python ref? > > a language is used by programers. Subroutine definition with > variable/default parameters is a basic issue a programer wants to know, > and different languages differs very much in how they handle this. This > is what i mean that the language doc should be programing oriented, as > opposed to computer-sciency or implementation oriented... You seem to be under the impression that most programmers learn a new language by looking up key phrases such as "variable argument list" in the index of their new language's manual as they encounter the need for a feature. In actual fact, most programmers learn by finding a tutorial or convenient beginner's lesson (hint hint), and then by browsing through other material such as a FAQ (hint hint), and then perhaps by skimming quickly through the reference material to learn what is there. This way they avoid making themselves look like complete and utter fools by appearing to learn only by looking up things in the index. -Peter From mandus at gmail.com Wed Jun 29 05:37:28 2005 From: mandus at gmail.com (Mandus) Date: Wed, 29 Jun 2005 09:37:28 +0000 (UTC) Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Sun, 26 Jun 2005 08:35:58 +0200 skrev Peter Otten: > Steven D'Aprano wrote: > >> On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote: >> >>> Mandus wrote: >>> >>>> By using the builtin reduce, I >>>> move the for-loop into the c-code which performs better. >>> >>> No. There is no hope of ever writing fast code when you do not actually >>> measure its performance. >> >> Good grief! You've been spying on Mandus! How else could you possibly know >> that he doesn't measure performance? Are you running a key-logger on his >> machine? *wink* > > His mentioning reduce() as a performance panacea was a strong indication > even without looking over his shoulders. He filled in some conditions in a > later post, but "[U]sing reduce ... performs better [than a for-loop]" is > just wrong. Ok - so sometimes reduce() for convenience (nha, that's just me...), sometimes for performance. In some cases clever use of map/reduce/etc. have given a good speedup - say 4 times that of for-loops. But going to C can give 10 to 100 times speed up over that again... So it depends how important the performance is. Going to C/Fortran is always a bit more hassel, while reduce is something you can stick in your interactive session to finish the work rather before than after lunch :) [snip] > >> Isn't it reasonable to just say, "I use join because it is faster than >> adding strings" without being abused for invalid optimization? > > OK, I am making a guess: "".join(strings) is more often faster than > naive string addition than reduce() wins over a for-loop. you're probably right. > I don't think my pointed comment qualifies as "abuse", by the way. neither think I. -- Mandus - the only mandus around. From l.serwatka at gazeta-dot-pl.no-spam.invalid Thu Jun 9 04:33:58 2005 From: l.serwatka at gazeta-dot-pl.no-spam.invalid (ls) Date: Thu, 9 Jun 2005 08:33:58 +0000 (UTC) Subject: how to export data from ZODB to text files References: Message-ID: Hi Josef, Thank you so much. I will ask our Plone administrator to test your script and I will write about result here. I thought also about Python script like //connect to database >>> from ZODB import FileStorage, DB >>> storage = FileStorage.FileStorage('Data.fs') >>> db = DB(storage) >>> conn = db.open() >>> dbroot = conn.root() //here should be interation for DB which saves attributes output in to file I'm not able to write the second part, but I think that this shouldn`t be a problem for experienced Python developer. How complex will be script like above? @Max > If you have access to the zope instance you want to export from, you only need to write an external method in Zope to export the data you want. Its pretty easy that way. Could you contribute code which do export data? -- Lukasz From simon.brunning at gmail.com Tue Jun 28 06:18:44 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 28 Jun 2005 11:18:44 +0100 Subject: Thoughts on Guido's ITC audio interview In-Reply-To: <11bs1bc5jotvg9c@news.supernews.com> References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: <8c7f10c6050628031818379b05@mail.gmail.com> On 6/26/05, John Roth wrote: > What's being ignored is that type information is useful for other things > than compile type checking. The major case in point is the way IDEs > such as IntelliJ and Eclipse use type information to do refactoring, code > completion and eventually numerous other things. A Java programmer > using IntelliJ or Eclipse can eliminate the advantage that Python > used to have, and possibly even pull ahead. I'm a Java programmer as my day job, most of the time, and I use Eclipse. I'm fairly proficient with it, but nevertheless I'm more productive with Python and SciTE than I am with Java and Eclipse. Eclipse helps a lot, true - I certainly wouldn't want to code Java without it or something like it - but it's not enought to pull ahead of Python's inherent superiority. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at REMOVETHIScyber.com.au Fri Jun 17 13:02:13 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Jun 2005 03:02:13 +1000 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? References: Message-ID: On Fri, 17 Jun 2005 09:36:55 -0700, Hughes, Chad O wrote: > I am very familiar with Python, but I don't know Pearl. The language is *always* spelt without the "a", and usually all in lower-case: perl. Now that I've taught you everything I know about perl, you can be an expert like me -- Steven From http Wed Jun 29 15:11:14 2005 From: http (Paul Rubin) Date: 29 Jun 2005 12:11:14 -0700 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: <7x3br1ger1.fsf@ruckus.brouhaha.com> Rocco Moretti writes: > Except that (please correct me if I'm wrong) there is somewhat of a > policy for not including interface code for third party programs which > are not part of the operating system. (I.e. the modules in the > standard libary should all be usable for anyone with a default OS + > Python install.) I've never heard of Python having such a policy and I don't understand how such a stupid policy could be considered compatible with a proclaimed "batteries included" philosophy. Why would Python advocates want to make Python deliberately uncompetitive with PHP, Java, and other languages that do include database modules? > A notable exception is the dbm modules, but I seem to recall hearing > that the official position is that it was a mistake. (Now only kept > for backward compatability.) Ahem: Tkinter. There's actually several more, looking in the lib docs. From jepler at unpythonic.net Sun Jun 5 16:32:24 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 5 Jun 2005 15:32:24 -0500 Subject: GUI builders considered harmful (Was: anygui, anydb, any opinions?) In-Reply-To: <86fyvwa91z.fsf_-_@guru.mired.org> References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> <86fyvwa91z.fsf_-_@guru.mired.org> Message-ID: <20050605203224.GA24794@unpythonic.net> On Sun, Jun 05, 2005 at 02:38:16PM -0500, Mike Meyer wrote: [...] > The first, and most obvious, thing that GUI builders do is force the > developer to specify an exact position - if not size - for the > graphical elements of the UI. [...] Certainly some---or even most---builders work like this. But there's no reason that a GUI GUI builder can't work in terms of the more sophisticated layout algorithms that are available in most modern GUI toolkits. I've written a GUI builder for Tcl/Tk (some old versions live at http://unpy.net/~jepler/nf/ but they're very out of date). The core of the application is the part that can write Tcl source code to regenerate the screen as it's currently displayed. The user can either use graphical tools like "insert widget", "show properties", "pack earlier/later", "automatically add accelerator keys", or script the thing by typing in Tcl. Want to use the grid manager? Fine, go ahead. The graphical interface to the grid command may be poor, but the commandline interface works great. When things are as you want them, just "save", and you can trivially "source" the resulting Tcl code from your Tcl/Tk app. I'm not trying to evangelize Tcl/Tk above any other language/toolkit, but I am saying that by pairing an interpreted language with a GUI toolkit, you can get a powerful GUI builder that instantly has top-notch scrptability and also the guarantee that you can use the powerful features of the GUI toolkit. I didn't do a survey of existing software before writing mine, but I don't know of another builder that takes this kind of approach. I wonder why not. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tim.peters at gmail.com Mon Jun 27 11:21:23 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 27 Jun 2005 11:21:23 -0400 Subject: Favorite non-python language trick? In-Reply-To: <200506260529.49224.hancock@anansispaceworks.com> References: <200506260529.49224.hancock@anansispaceworks.com> Message-ID: <1f7befae0506270821419851e5@mail.gmail.com> [Terry Hancock] > Probably the most pointless Python wart, I would think. The =/== > distinction makes sense in C, but since Python doesn't allow assignments > in expressions, I don't think there is any situation in which the distinction > is needed. Python could easily figure out whether you meant assignment > or equality from the context, just like the programmer does. That's what Python originally did, before release 0.9.6 (search Misc/HISTORY for eqfix.py). Even this is ambigous then: a = b Especially at an interactive prompt, it's wholly ambiguous then whether you want to change a's binding, or want to know whether a and b compare equal. Just yesterday, I wrote this in a script: lastinline = ci == ncs - 1 This: lastinline = ci = ncs - 1 means something very different (or means something identical, depending on exactly how it is Python "could easily figure out" what I intended ). Of course strange rules could have resolved this, like, say, "=" means assignment, unless that would give a syntax error, and then "=" means equality. Then lastinline = ci = ncs - 1 would have been chained assignment, and something like lastinline = (ci = ncs - 1) would have been needed to get the intent of the current lastinline = ci == ncs - 1 From grante at visi.com Mon Jun 27 10:27:28 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 27 Jun 2005 14:27:28 -0000 Subject: turn text lines into a list References: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> Message-ID: <11c036grkf1d4d1@corp.supernews.com> On 2005-06-27, Xah Lee wrote: > i have a large number of lines i want to turn into a list. > In perl, i can do > > @corenames=qw( > rb_basic_islamic > sq1_pentagonTile > sq_arc501Tile > sq_arc503Tile > ); > > use Data::Dumper; > print Dumper(\@corenames); > > ---------- > is there some shortcut to turn lines into list in Python? corenames = [ "rb_basic_islamic", "sq1_pentagonTile", "sq_arc501Tile", "sq_arc503Tile"] -- Grant Edwards grante Yow! TAILFINS!!...click... at visi.com From fphsml at gmail.com Fri Jun 24 17:29:37 2005 From: fphsml at gmail.com (James) Date: 24 Jun 2005 14:29:37 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <1119648577.754818.119530@z14g2000cwz.googlegroups.com> Interesting thread ... 1.) Language support for ranges as in Ada/Pascal/Ruby 1..10 rather than range(1, 10) 2.) Contracts 3.) With From skn at skn.com Thu Jun 30 05:20:29 2005 From: skn at skn.com (skn) Date: Thu, 30 Jun 2005 14:50:29 +0530 Subject: JPype - suppressing JVM activity report Message-ID: Hello, Is there any option to suppress the JVM activity report that gets displayed, when you execute Java APIs from within Python using JPype. E.g., JVM activity report : classes loaded : 26 JVM has been shutdown I know I can do it by re-directing the std err to NUL. But is there any other option? From mandus at gmail.com Sat Jun 25 15:23:18 2005 From: mandus at gmail.com (Mandus) Date: Sat, 25 Jun 2005 19:23:18 +0000 (UTC) Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Sat, 25 Jun 2005 16:06:57 GMT skrev Lee Harr: >>> Higher-order functions like map, filter and reduce. As of Python 3000, >>> they're non-python tricks. Sigh - i guess it's time for me to get to know >>> list comprehensions a bit better. >>> > > > Couldnt there just be a "functional" module ?... > > from functional import map, filter, reduce but lambda is grammar, so probably not so easy to import? -- Mandus - the only mandus around. From mithrandir42 at web.de Wed Jun 1 08:58:23 2005 From: mithrandir42 at web.de (N. Volbers) Date: Wed, 01 Jun 2005 14:58:23 +0200 Subject: python 2.4: tarfile tell() and seek() seem to be broeken Message-ID: Hello everyone, I noticed that when you open a zipped tarball using 'tarfile' and if you then get the pseudo-file descriptor fd for a file via 'extractfile', then fd.tell() is broken in the following way: - before reading anything from fd, fd.tell() will return 0 (that's still ok) - after reading a line via fd.readline(), fd.tell() will return a value different from 0 (still ok, I guess) - subsequent calls of fd.readline() and fd.tell() will yield the correct lines but always the same value from fd.tell(). fd.seek() seems to be unaffected from this strange behaviour. Is there a mistake on my side or does this need fixing? Best regards, Niklas Volbers. From ivanlan at pauahtun.org Thu Jun 23 12:08:50 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 23 Jun 2005 10:08:50 -0600 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> <1f7befae05062309012e86599d@mail.gmail.com> Message-ID: <42BADE92.C4768DF8@pauahtun.org> Hi All-- Tim Peters wrote: > Fortran is so > eager to allow optimizations that failure due to numeric differences > in conformance tests rarely withstood challenge. +1 QOTW Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From harold.fellermann at upf.edu Tue Jun 7 09:45:38 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 7 Jun 2005 15:45:38 +0200 Subject: How do I know when a thread quits? In-Reply-To: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> References: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> Message-ID: Hi, > I want a reliable way of knowing when the child > thread finished execution so that I can make the main thread wait till > then. > > Any ideas? use a lock. the subthread allocates the lock and releases it after processing. the main thread must wait until the lock is released. otherwiese, use the higher level Threading module which provides a function Thread.join that allows the main thread to wait for the subthread. I think it uses the same mechanism that I explained above. - harold - -- Outside of a dog, a book is a man's best friend: and inside a dog, it's too dark to read. -- Groucho Marx From mibar02 at student.sdu.dk Wed Jun 22 17:18:10 2005 From: mibar02 at student.sdu.dk (Michael Barkholt) Date: Wed, 22 Jun 2005 23:18:10 +0200 Subject: Python internals and parser Message-ID: <42b9d592$0$31813$ba624c82@nntp06.dk.telia.net> Hi Is there any detailed documentation on the structure of Pythons internals, besides the source code itself? More specifically I am looking for information regarding the C parser, since I am looking into the viability of using it in another project that needs to parse python code (and I would like the code to be written in C). Any inputs? Regards, Michael Barkholt From guy.lateur at b-b.be Thu Jun 9 11:34:41 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 09 Jun 2005 15:34:41 GMT Subject: Start application & continue after app exits Message-ID: Hi all, I was wondering if it would be possible to launch an application, block until the app exits, and do some cleanup afterwards. Maybe an example will be clearer: I would like to make a temperary (text) file, open it with MS Word for the user to edit/layout/print, and then delete the temp file after the user shuts down Word. Is this feasible? Thanks, g From uhorn at csir.co.za Mon Jun 6 11:21:13 2005 From: uhorn at csir.co.za (uli) Date: 6 Jun 2005 08:21:13 -0700 Subject: Computer Cluster Python Software In-Reply-To: References: <1118067774.890927.279130@g49g2000cwa.googlegroups.com> Message-ID: <1118071273.752317.246710@g49g2000cwa.googlegroups.com> Hi Mandus Thanks for your reply. I am looking for an application written in python (preferably a bioinformatics application) which will be able to take advantage of parallel processing on a cluster. I guess what I am asking for is applications which have been written using pyMPI or other python MPI modules. Regards Uli From steven.bethard at gmail.com Wed Jun 29 16:03:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Jun 2005 14:03:53 -0600 Subject: strange __call__ In-Reply-To: <1120062469.370984.130670@f14g2000cwb.googlegroups.com> References: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> <1120062469.370984.130670@f14g2000cwb.googlegroups.com> Message-ID: Rahul wrote: > def wrapper(obj): > g = obj.__call__ > def f(*args,**kwargs): > for arg in args:print arg > return g(*args,**kwargs) > obj.__call__=f > but it seems this will not work for functions :( def wrap(obj): def f(*args, **kwargs): for arg in args: print arg return obj(*args, **kwargs) return f @wrap def func(a, b, c): ... class C(object): ... C = wrap(C) STeVe From fuzzyman at gmail.com Fri Jun 24 08:01:52 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jun 2005 05:01:52 -0700 Subject: howto load and unload a module In-Reply-To: References: Message-ID: <1119614512.950735.13490@g14g2000cwa.googlegroups.com> Answer to 2 - ``hasattr(module, name)`` From simon.brunning at gmail.com Tue Jun 21 05:23:00 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 21 Jun 2005 10:23:00 +0100 Subject: How to get/set class attributes in Python In-Reply-To: References: Message-ID: <8c7f10c6050621022373e14bae@mail.gmail.com> On 6/12/05, Steve Jorgensen wrote: > Oops - I thought I cancelled that post when I relized I was saying nothing, Would that everyone cancelled their posts when they realised that they weren't saying anything. ;-) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at REMOVEMEcyber.com.au Thu Jun 2 23:38:59 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 03 Jun 2005 13:38:59 +1000 Subject: Two questions References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <429FD0D3.7060000@REMOVEMEcyber.com.au> Andrew Dalke wrote: > Steven D'Aprano wrote: > >>I can think of a number of reasons why somebody might want to hide their >>code. In no particular order: > > >>(3) You have create an incredibly valuable piece of code that will be >>worth millions, but only if nobody can see the source code. Yeah right. > > > - id software makes a lot of money licensing their 3D FPS engine The existence of one or two or a thousand profitable software packages out of the millions in existence does not invalidate my skepticism that some random piece of software will directly make money for the developer. Even assuming that the money-making ability would be lost if the source code was available, which is not a given (id software open-sources old versions of their rendering engines, and MySQL is quite profitable and their software is available source code and all). Software rarely makes money for the developers directly. The odds are against any developer, hence my skepticism. > - stock market trading companies make money in part by having > specialized software to help with market trading, forecasts, etc. You are mixing up a number of seperate issues here. If the trading company keeps the software in-house, then the issue of making the source code available is irrelevent since they don't distribute the object code either. If they distribute the software externally, then they almost certainly have more protection from licence agreements and copyright than they get from merely hiding the source. If they even do hide the source code, which is not a given. As for the issue of them making money, I'm not suggesting that software can't make money for a business. I work for a business that makes money from Linux, Apache, perl, Python and other FOSS in the same way that a carpenter makes money from a hammer: they are tools that we use to provide products and services that we sell for profit. In-house use of market forecasting software falls into the "carpenter's hammer" category, not the "make money by selling software" category. As for selling forecasting software, well, you haven't demonstrated that making the source code available would harm the ability to make money from it. Firstly, very often the value of the software is not the algorithms they use (curve fitting software and extrapolation algorithms are hardly secret), but the data used by the algorithm. So long as you keep the financial data proprietary, keeping the source code secret adds nothing. Secondly, even if the software is rubbish, and the forecasts give results no better than chance, doesn't mean the company can't make money selling it. Look at the popularity of "systems" for predicting lottery numbers. >>(8) You are programming a game or puzzle, and you don't want players to >>cheat by reading the source code. Consider pulling out the information >>they need to cheat and putting it in an encrypted data file instead. > > > But code is data ... A pedantic point that doesn't add anything to the discussion :-) Not all the data in a puzzle allows the player to cheat, does it? Case in point: knowing how Solitaire draws the cards on the screen doesn't help you win any games. >>There may be other reasons for wanting to keep the code secret. Some of >>them might even be good reasons, for some value of "good". > > > You are the US government developing software to design/test the > next generation nuclear weapons system and don't want any other > country to use it. (GnuNuke?) Then don't distribute the software, object or source code. > You are a student working on a take-home example and you aren't > allowed to work with/help anyone else Er, I don't see how this is supposed to work. An example of what? How does keeping the source code secret prevent the student from working with others? >>If you really what to hide your code, you might like to think about >>using C-extensions instead. > > > Or go the Amazon/EBay/Google approach and provide only client access > to your code. Yes, good point. That's another way of telling your customers under what circumstances they are allowed to use the software. And who knows, if your software is valuable enough and unique enough, they may even be prepared to work the way you want them to work instead of the way they want to work. -- Steven. From peter at somewhere.com Tue Jun 28 05:08:27 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 28 Jun 2005 11:08:27 +0200 Subject: Boss wants me to program In-Reply-To: References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: Brian schrieb: > Microsoft Visual Basic (.NET) would be your best bet for this type of > software development. It allows you to create GUI apps that can work > with a variety of database options, such as Access or MS SQL Server. Maybe you're right with .net, but I'd go for C# when doing .net. Basic is the ugliest and most mind corrupting language I've come across. And the OP has a C/C++ background. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From hancock at anansispaceworks.com Fri Jun 10 23:09:49 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Jun 2005 22:09:49 -0500 Subject: Dealing with marketing types... In-Reply-To: References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <200506102209.49469.hancock@anansispaceworks.com> On Friday 10 June 2005 12:08 pm, Harald Massa wrote: > > They want a > > "scalable, enterprise solution" (though they don't really know what > > that means) and are going crazy throwing around the Java buzzwords > > (not to mention XML). > > > There is a very cheap solution: Ryan Tomayko debunkes all these myths. > You can google it up, "astronaut architects" Apparently not -- I can't find anything relevant on the first page with the searches: astronaut architects "astronaut architects" "astronaut architects" "ryan tomayko" "astronaut architects" tomayko "astronaut architects" tomko "ryan tomayko" However, after a bit of brainstorming, I tried: "architecture astronauts" "ryan tomayko" and got this: http://naeblis.cx/rtomayko/2005/05/28/ibm-poop-heads which is probably what you meant. I love that file name. ;-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ognjen at mailshack.com Fri Jun 3 04:29:41 2005 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Fri, 03 Jun 2005 09:29:41 +0100 Subject: Formatting Time Message-ID: <42A014F5.40308@mailshack.com> I never thought id need help with such a thing as time formatting (admittadly i never did it before) but ok, i guess there is a first for everything. I have a float variable representing seconds, and i want to format it like this: 0:00:00 (h:mm:ss) Now search as I might i am finding this quite elusive, i had a look at the time module but that seems overly complicated for this. Anyone got any simple solutions to doing this? cheers! From listserver at tdw.net Thu Jun 23 04:51:54 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 23 Jun 2005 09:51:54 +0100 Subject: Optimize a cache References: Message-ID: <010401c577d0$ced22a70$ccbefea9@twilliams> ----- Original Message ----- From: "Florian Lindner" > Hello, > I am building a object cache in python, The cache has a maximum size and the > items have expiration dates. > At the moment I'm doing like that: > What possible you see to optimize this lookup? Or anything else you see to > make it better? Have a look at http://py.vaults.ca/apyllo.py/514463245.769244789.92554878 it already has some of your requirements, and can be used as a building block. From jmdeschamps at cvm.qc.ca Sun Jun 12 15:16:50 2005 From: jmdeschamps at cvm.qc.ca (jean-marc) Date: 12 Jun 2005 12:16:50 -0700 Subject: searching for IDE In-Reply-To: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: <1118603810.369228.74520@g49g2000cwa.googlegroups.com> if you are familiar with eclipse, you could use the PyDev python plugin. jm From me at privacy.net Wed Jun 29 21:25:20 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 29 Jun 2005 21:25:20 -0400 Subject: Programmers Contest: Fit pictures on a page References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> <42c32af7@usenet01.boi.hp.com> Message-ID: On Wed, 29 Jun 2005 19:43:33 -0400, Roy Smith wrote: > Not just plywood panels, but sheets of paper, bolts of cloth, sheet > metal, plate glass, etc. A slight complication is that some materials > have a preferred orientation (i.e. plywood has a grain, textiles have > warp vs. weft, etc) and some don't (or it doesn't matter for the > application). > It gets even more interesting when you're restricted to making cuts > that start at an edge, or go all the way through the sheet to the > other side. I ran into this problem when I worked at a small computer store back in 1979 or 1980. One of our customers owned a plastics plant, and found such a program, and wanted us to install it and maintain it (on an 8080 or a Z-80 running CP/M, no less). The first release only did rectangles, and assumed flawless material, so his first trial was to tell the program about a 4 x 8 foot sheet of plastic, and ask for two 4 x 4 pieces. The program refused, because a saw blade has a non-zero width. But he had mis-specified the problem, because a 4 x 8 sheet of plastic was really a half-inch (or some small amount) bigger in both directions. Anyway, after a couple more years and a few more releases, the program could handle arbitrary polygons, shapes with various types of curved edges, arbitrary flaws in the material (mostly for knots in sheets of plywood), and I'm sure a few more things I don't remember right now. It could also beat his "best guy." Regards, Dan -- Dan Sommers From steve at REMOVETHIScyber.com.au Sat Jun 18 05:45:23 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 18 Jun 2005 19:45:23 +1000 Subject: exceptions considered harmful References: <1119027185.832640.291760@g43g2000cwa.googlegroups.com> Message-ID: On Fri, 17 Jun 2005 20:00:39 -0400, Roy Smith wrote: > "H. S. Lahman" wrote: >> > Never throw an exception. And if someone throws one at you, >> > catch it immediately and don't pass it on. >> >> IMO, this is generally fine advice. Languages provide exception >> handlers so that applications have a chance to respond gracefully when >> the software is in an unstable state. IOW, you should never see an >> exception unless the software is seriously broken. A corollary is that >> if the software is corrupted, then even processing the exception becomes >> high risk. So one should do as little as possible when processing >> exceptions. (Some languages provide a degree of bullet proofing, but >> that just make the exception handling facility too expensive to use for >> routine processing.) > > This sounds like a very C++ view of the world. In Python, for example, > exceptions are much more light weight and perfectly routine. Yes. Furthermore, there is a reason why they are called exceptions and not errors. Exceptions don't necessarily mean "something has gone wrong". They can also mean, "something has gone right, but it is an exceptional case". For example, Guido recommends using exceptions for handling exceptional cases for command-line tools. Eg, something like this: try: for switch in sys.argv[1:]: if switch in ("-h", "--help"): raise HelpException else: do_something() except HelpException: print __doc__ sys.exit(0) # because asking for help is not an error except: print "Program failed!" sys.exit(1) # but an error is an error do_main_calculation() sys.exit(0) Or something like this: try: # long slow calculation do_lots_of_work_here() if condition(): # we can jump out of the slow calculation and take a short cut raise QuickException # and more long slow calculation here partial_result = do_lots_more_work_here() except QuickException: # short and easy calculation partial_result = do_quick_calculation() # in either case, we need to do more work here return do_more_work(partial_result) Or even roll-back of processing: try: process_data() # can raise RecoverableError or FatalError except RecoverableError: roll_back() except FatalError: print "A fatal error occurred." sys.exit(1) Because Python's handling of try...except is lightweight and fast, this is an idiom which is very practical to use in many situations where it wouldn't be practical in other languages. In conclusion: in Python, it is just not true that "you should never see an exception unless the software is seriously broken". It is very bad advice to say that "even processing the exception becomes high risk". If the exception genuinely is an error, then it may be difficult to recover, and the best thing you can do is fail gracefully. But that's no reason to not use exceptions. -- Steven. From mfranklin1 at gatwick.westerngeco.slb.com Fri Jun 24 05:53:50 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 24 Jun 2005 10:53:50 +0100 Subject: don't understand MRO In-Reply-To: References: Message-ID: Uwe Mayer wrote: > Thursday 23 June 2005 19:22 pm Terry Reedy wrote: > > [...] > >>In the absence of other information, I would presume that none of the >>other classes have a move() method. > > > move() is implemented in the class qtcanvas.QCanvasItem > I checked the pyqt sources and it is linked via sip to the C++ object file. > In C++, QCanvasItem.move is delegated to QCanvasItem.moveBy. > > -- snip: C++ sources -- > void QCanvasItem::move( double x, double y ){ > moveBy( x-myx, y-myy ); > } > > void QCanvasItem::moveBy( double dx, double dy ){ > if ( dx || dy ) { > removeFromChunks(); > myx += dx; > myy += dy; > addToChunks(); > } > } I wonder if it is to do with the signature of these methods. they accept two doubles and perhaps the python bindings do not automatically convert from integers, therefore these methods are not called and the rules of mro kick in (thus calling the python move method) > -- snip -- > > >>Are you sure that QCanvasItem has a move method? What results from >> >>>>>print qtcanvas.QCanvasItem.move # ? >> >>If so, I would need to see its code to try to answer. > > >>>>import qtcanvas >>>>qtcanvas.QCanvasItem.move > > > > Here is a working portion which recreates the strange output: > > -- snip -- > from qtcanvas import * > > class Node(object): > def move(self, x,y): > print "Node: move(%d,%d)"%(x,y) > > class Rhomb(QCanvasPolygon, Node): > def __init__(self, parent): > QCanvasPolygon.__init__(self, parent) > Node.__init__(self) > > print Rhomb.mro() > r = Rhomb(None) > r.move(1,2) > -- snip -- > > This prints: > > [, , 'qtcanvas.QCanvasPolygonalItem'>, , 'qt.Qt'>, , , ] > Node: move(1,2) > > Ciao > Uwe > From cam.ac.uk at mh391.invalid Sun Jun 19 04:41:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 19 Jun 2005 09:41:45 +0100 Subject: regarding popen function In-Reply-To: References: Message-ID: Peter Hansen wrote: > Michael, tai64nlocal is a program that converts a special "packed" > timestamp to human-readable form. Thanks Peter. I was asking somewhat rhetorically but I have a love of UNIX arcana and now I know. :) -- Michael Hoffman From look.at.signature at somewhere Wed Jun 1 16:06:35 2005 From: look.at.signature at somewhere (Ruud de Jong) Date: Wed, 01 Jun 2005 22:06:35 +0200 Subject: how to convert string to list or tuple In-Reply-To: References: <1117383768.099922.308760@o13g2000cwo.googlegroups.com> Message-ID: <429e1546$0$1372$5fc3050@dreader2.news.tiscali.nl> Steven Bethard schreef: > But unless the person eval-ing your code *only* writes immaculate code I > can see that you can probably screw them. ;) I wonder why > __subclasses__ isn't a restricted attribute... Is it ever used for > something that isn't evil? ;) > > STeVe Completely off topic, but I just cannot resist showing off. Some time ago I used __subclasses__ in a way that is not evil. I think. The details are described in the following thread: http://groups.google.nl/group/comp.lang.python/browse_thread/thread/5c1ccb986c66cdc1/ A summary: I used __subclasses__ to apply the Chain-of-Responsibility pattern to object creation. The code would appear to instantiate an object of the root of a class hierarchy, but the actual object that was created would be an instance of a subclass. So to get back to your question: yes, there are non-evil uses for __subclasses__. Weird perhaps, but non-evil. Non-standard, sure . Too clever for my own good, very likely. Regards, Ruud -- Ruud de Jong '@'.join('.'.join(s) for s in (['ruud','de','jong'],['tiscali','nl'])) From tim.golden at viacom-outdoor.co.uk Thu Jun 23 02:58:21 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Jun 2005 07:58:21 +0100 Subject: Allowing only one instance of a script? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB926@vogbs009.gb.vo.local> [Ali] | | I have a script which I double-click to run. If i double-click it | again, it will launch another instance of the script. | | Is there a way to allow only one instance of a script, so that if | another instance of the script is launched, it will just | return with an | error. If you're on Windows, have a look at this recent thread: http://groups-beta.google.com/group/comp.lang.python/msg/2a4fadfd3d6e3d4b?hl=en TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tracy at reinventnow.com Mon Jun 6 14:38:09 2005 From: tracy at reinventnow.com (tracyshaun) Date: 6 Jun 2005 11:38:09 -0700 Subject: idiom for constructor? References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> <1118082751.402682.314720@g14g2000cwa.googlegroups.com> Message-ID: <1118083089.614306.260680@g49g2000cwa.googlegroups.com> And you probably should add: ... def __init__(self, *args): assert len(args) == len(self.__slots__) ... --T From s4somesh at gmail.com Fri Jun 3 00:24:45 2005 From: s4somesh at gmail.com (Shrii) Date: 2 Jun 2005 21:24:45 -0700 Subject: Unicode string in exec In-Reply-To: <119ukmgd1nh8ve0@news.supernews.com> References: <1117687496.341548.117760@g14g2000cwa.googlegroups.com> <119ukmgd1nh8ve0@news.supernews.com> Message-ID: <1117772685.418581.25050@g43g2000cwa.googlegroups.com> I came out with proper solution today ! thanx for your response From flamesrock at gmail.com Mon Jun 6 02:52:04 2005 From: flamesrock at gmail.com (flamesrock) Date: 5 Jun 2005 23:52:04 -0700 Subject: easiest way to split a list into evenly divisble smaller lists, and assign them to variables? Message-ID: <1118040724.644534.259460@g44g2000cwa.googlegroups.com> Lets say I have a list containing 12, 13, 23 or however many entries. What I want is the greatest number of lists evenly divisible by a certain number, and for those lists to be assigned to variables. This leads to a few problems.. If I don't know the length of the list beforehand, I can't create the variables and hardcode them. Is it possible in python to generate free variables without stating them explicitly in the code, and if so, how would you get a reference to them? Secondly, is there an easier way to chop a list up into smaller lists? consider this code: # my_list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14, # 15,16,17,18,19,20,21,22,23,24,25] # entry=0 # dictionary_of_lists = {} # while len(original_list) != 0: # new_list=[] # for x in range(4): # if len(original_list) > 0: # new_list.append(files.pop(0)) # dictionary_of_lists[entry] = new_list # entry +=1 would give us {1:[1,2,3,4],2:[5,6,7,8], 3:[9,10,11,12],4:[13,14,15,16], 5:[17,18,19,20],6:[21,22,23,24],7:[25]} Is there a better way? What I'd like to do is create free variables without needing to put them in a dictionary. If not, is it possible in other languages? -thank in advance From erchamion.beren at gmail.com Fri Jun 10 11:21:07 2005 From: erchamion.beren at gmail.com (sinan ,) Date: Fri, 10 Jun 2005 18:21:07 +0300 Subject: about accessing mysql In-Reply-To: References: Message-ID: <59dfa14505061008211c41fe1@mail.gmail.com> hi, my table types are MyISAM both local and server, my code can reach to my locals mysql but cannot reach when running on server. From tjreedy at udel.edu Sat Jun 25 21:18:00 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Jun 2005 21:18:00 -0400 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: "Mandus" wrote in message news:slrndbqe6i.tn3.mandus at kasus.simula.no... > Fri, 24 Jun 2005 16:31:08 +0100 skrev Tom Anderson: >> On Fri, 24 Jun 2005, Joseph Garvin wrote: >> Higher-order functions like map, filter and reduce. As of Python 3000, >> they're non-python tricks. Sigh - i guess it's time for me to get to >> know >> list comprehensions a bit better. >> > > u-huu... I wasn't aware of that. It is really a consensus on this; that > removing map, filter, reduce is a good thing? It will render a whole lot > of my software unusable :( In his State of Python 2005 address, Guido estimated 1/2 +1, 1/4 +/-0, 1/4 -1 on this. So majority of those with opinion, not 'consensus'. Then there is his vote... Terry J. Reedy From cam.ac.uk at mh391.invalid Sat Jun 18 05:01:33 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 18 Jun 2005 10:01:33 +0100 Subject: regarding popen function In-Reply-To: References: Message-ID: praba kar wrote: > The following way of popen function usage is > wrong or not kindly give me answer regarding this > > time = os.popen("echo %s | tai64nlocal" % > line[2]).read() I don't know, I don't know what tai64nlocal is or what's in line[2]. What happened when you tried it? Personally I try to use the subprocess module rather than os.popen. -- Michael Hoffman From jmeile at hotmail.com Wed Jun 8 12:12:08 2005 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 08 Jun 2005 18:12:08 +0200 Subject: circular import Module In-Reply-To: References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Message-ID: <42A718D8.4000801@hotmail.com> >>Circular import does not work on module level, but you can >>import the module in a method: >> >>file1.py: >>import file2 >>.... >> >> >>file2.py: >># import file1 # Does not work! >>def foo(): >> import file1 # Does work > > > Cool idea ! > > It works on local namespaces, wich dont cause trouble to the whole program. > > +1 Yes, I also think is a good solution. Once I needed to do something like that and ended by writting a third module with the shared functions that the two conflicting modules needed. At that time I already knew that one could import modules from functions; however, I didn't come up with that solution :-( Regards, Josef From kraus at hagen-partner.de Thu Jun 30 02:41:37 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 30 Jun 2005 08:41:37 +0200 Subject: need help with MySQLdb In-Reply-To: <1120107408.960230.111180@g44g2000cwa.googlegroups.com> References: <1120107408.960230.111180@g44g2000cwa.googlegroups.com> Message-ID: <42C39421.9040301@hagen-partner.de> nephish at xit.net wrote: > Hey there all, > i have a question about how to point my python install to my sql > database. > > when i enter this: db = MySQLdb.connect(user="user", passwd="pass", > db="myDB") > > i get this: > Traceback (most recent call last): > File "", line 1, in -toplevel- > db = MySQLdb.connect(user="user", passwd="pass", db="MyDB") > File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66, > in Connect > return Connection(*args, **kwargs) > File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line > 134, in __init__ > super(Connection, self).__init__(*args, **kwargs2) > OperationalError: (1049, "Unknown database 'MyDB'") > > i am using the all in one package from lampp (now xampp) and i have > tested a couple of python scripts from the cgi, but.... nothing that > connects to the database. > > any ideas? > > thanks > Try the following from the shell (NOT the python shell): mysql -u user -p [Enter passwd] mysql> show databases; If MyDB isn't in the list either something went wrong with the xampp installation or the database for xampp got a different name. (I am no xampp expert, so I can't help you any further) HTH, Wolfram From dalke at dalkescientific.com Fri Jun 10 05:20:14 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 10 Jun 2005 09:20:14 GMT Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <1118390462.698504.43650@z14g2000cwz.googlegroups.com> Message-ID: wooks wrote: > If I had posted or invited the group to look at my full list of items > rather than just the python book link then I could see where you are > coming from. Take a look at http://www.templetons.com/brad/spamterm.html for some of the first spams and reactions thereof. There's a 30+ year history of posts which one person thinks is relevant or important and others find off-topic, crass, and rude. A rough sort of social norms - called netiquette - have come from that experience. > If my intention was to "spam" this NG then the complaints as they were > phrased would only have served to make me more determined. The intention is to prevent it from happening in the future. If your intention is indeed to spam the group then there are mechanisms to stop you, including such lovely terms as killfiles and cancelbots. Too much of it and you might find your account suspended. Or have you not wondered why few spams make it here? If your intention is to continue posting then it's a warning of sorts that as in every community there are social forms to follow, and often good reasons for those forms. Terry backed up his response explaining not only the convention for what you were doing, but also mentioned (briefly) why he responded in the way he did. I personally found your original posting blunt. I thought it was a virus or spam. You see, I don't do eBay and whenever I see that term in my mail in a URL it's either a spam or a phishing attack. So I ignored it. If you really wanted to sell it then following Terry's advice and holding to social forms would have been better for your auction. There's little incentive for anyone to follow that link without knowing more about it. > Maybe we will all learn something from each other. Hopefully you, but not likely the others involved. As I said, this sort of thing has a long history and for anyone who's been doing this for years (like me) there's little new to learn on the topic. To give an idea of the history, there's even an RFC on netiquette from 10 years ago: http://www.faqs.org/rfcs/rfc1855.html The directly relevant part is - Advertising is welcomed on some lists and Newsgroups, and abhorred on others! This is another example of knowing your audience before you post. Unsolicited advertising which is completely off-topic will most certainly guarantee that you get a lot of hate mail. Most assuredly, what Terry sent you is *not* hate mail. Andrew dalke at dalkescientific.com From njagan at gmail.com Thu Jun 30 14:18:05 2005 From: njagan at gmail.com (Jags) Date: 30 Jun 2005 11:18:05 -0700 Subject: Seeking IDE In-Reply-To: References: Message-ID: <1120155485.235706.204580@f14g2000cwb.googlegroups.com> Hi there, You could use the IDLE that is bundled along with the Python installation. If you don't like that, you could use any of the following editors: EditPlus, TextPad, UltraEdit, WingIDE, Komodo (from ActiveState) or jEdit. All these are Windows based. Cheers! - Jags. From kveretennicov at gmail.com Wed Jun 15 19:21:06 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 16 Jun 2005 01:21:06 +0200 Subject: pyunit: remove a test case on the fly In-Reply-To: <1118869989.840138.16520@g44g2000cwa.googlegroups.com> References: <1118869989.840138.16520@g44g2000cwa.googlegroups.com> Message-ID: <4660fe30050615162115eb1cfd@mail.gmail.com> On 15 Jun 2005 14:13:09 -0700, chris wrote: > We have a number of TestCase classes that have multiple test methods. > We are interested in removing any of the individual test methods on the > fly (dynamically, at runtime, whatever). Here's a simple approach imitating NUnit's CategoryAttribute. I don't know whether it'll work for you, it depends on what exactly isSupported() does. - kv import unittest def category(*test_categories): tc = frozenset(test_categories) def f(g): if tc & frozenset(active_categories): return g # else return None, # effectively removing test from TestCase return f active_categories = ['mac', 'nt'] class T(unittest.TestCase): @category('mac') def test_a(self): print 'mac only' @category('posix') def test_b(self): print 'posix only' @category('posix', 'nt') def test_c(self): print 'posix or nt' def test_d(self): print 'platform-independent' if __name__ == '__main__': unittest.main() From tjreedy at udel.edu Thu Jun 2 13:27:43 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Jun 2005 13:27:43 -0400 Subject: Beginner question: Logs? References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: > import math > math.log10(15625) To find out the names of function in the math module without checking the docs, do >>> dir(math) #same for any other module To get more info, do >>> help(math) # same for any other module with a doc string Terry J. Reedy From ptmcg at austin.rr.com Fri Jun 24 01:14:33 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 23 Jun 2005 22:14:33 -0700 Subject: key - key pairs In-Reply-To: References: <200506231612.42324.hancock@anansispaceworks.com> Message-ID: <1119590073.725041.138270@g44g2000cwa.googlegroups.com> No need to update __getitem__, since the modified __setitem__ drops in the reverse values. But __delitem__ needs overriding, and some special guard needs to be added to __setitem__ to prevent orphaning any old value:key entries. -- Paul Here's one possible solution: class SymmetricDict(dict): def __delitem__(self,x): v = self[x] super(SymmetricDict,self).__delitem__(x) super(SymmetricDict,self).__delitem__(v) def __setitem__(self,k,v): if k in self: del self[k] if v in self: del self[v] super(SymmetricDict,self).__setitem__(k,v) super(SymmetricDict,self).__setitem__(v,k) sd = SymmetricDict() sd["A"] = 1 print sd["A"] print sd[1] sd["A"] = 2 print sd["A"] print sd[2] print sd[1] prints: 1 A 2 A Traceback (most recent call last): File "symmetricDict.py", line 25, in ? print sd[1] KeyError: 1 From donn at drizzle.com Thu Jun 16 01:07:03 2005 From: donn at drizzle.com (Donn Cave) Date: Thu, 16 Jun 2005 05:07:03 -0000 Subject: __str__ vs __repr__ References: <42b021ba$1@griseus.its.uu.se> <11b16e3mld1s9b7@news.supernews.com> Message-ID: <1118898421.887013@yasure> Quoth "John Roth" : ... | str() should be something that's meaningful to a human being when | it's printed or otherwise rendered. I can't believe how many people cite this explanation - meaningful, friendly, pretty to a human being. What on earth does this mean, that couldn't be said more unambiguously? According to my impression of common applications for Python programs, rarely would anyone be looking at the output for esthetic gratification. I mean, imagine your users casting an appraising eye over the contours of a phrase emitted by the program, and praising the rhythmic effect of the punctuation it chose to use, or negative space created by tabs. heh. Whether for human eyes or any destination, properly formed output will carry the information that is required for the application, in a complete and unambiguous way and in the format that is most readily processed, and it will omit extraneous information. Are we saying anything other than this? Donn Cave, donn at drizzle.com From flyingfred0 at gmail.com Thu Jun 9 22:07:00 2005 From: flyingfred0 at gmail.com (flyingfred0) Date: Fri, 10 Jun 2005 02:07:00 GMT Subject: Dealing with marketing types... Message-ID: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> A small software team (developers, leads and even the manager when he's had time) has been using (wx)Python/PostgreSQL for over 2 years and developed a successful 1.0 release of a client/server product. A marketing/product manager has brought in additional management and "architecture" experts to propose moving the entire thing to a Java (application server) platform for the next release. They want a "scalable, enterprise solution" (though they don't really know what that means) and are going crazy throwing around the Java buzzwords (not to mention XML). The developers (including myself) are growing uneasy; the management is continuing to push their requirements and ignore the engineers. I think there's still hope, but I'm at a loss for ideas beyond pointing out the success stories of Python and Zope and language comparisons between Python and Java. What experiences have those in the Python community had in these kinds of situations? From grante at visi.com Thu Jun 23 10:58:45 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Jun 2005 14:58:45 -0000 Subject: Allowing only one instance of a script? References: <1119509361.208748.247400@g49g2000cwa.googlegroups.com> Message-ID: <11bljh588m0r89c@corp.supernews.com> On 2005-06-23, Thomas Guettler wrote: > Create a file which contains the PID (process ID) of > the current process in a directory. If the file > already exists, the file is running. That's how it's usually done. > If your script dies without removing the pid-file, you need to > look during the start if the PID which is in the file is sill > alive. > There is a small race condition between os.path.exists() > and writing the file. That's why it's pointless to call os.path.exists(). > If you want to be 100% sure you need to use file locking. I've never seen it done that way. The standard method is to use open() with flags O_CREAT|O_EXCL. If the open() is sucessful, then you have the lock. If it fails, somebody else already has the lock. Another method is to create a temp file containing the PID and then call link() to rename it. Both open() and link() are atomic operations, so there's no race condition. -- Grant Edwards grante Yow! I don't know WHY I at said that... I think it visi.com came from the FILLINGS inmy read molars... From jwaixs at gmail.com Mon Jun 27 12:29:02 2005 From: jwaixs at gmail.com (jwaixs) Date: 27 Jun 2005 09:29:02 -0700 Subject: execute python code and save the stdout as a string In-Reply-To: References: <1119701023.896260.4770@g47g2000cwa.googlegroups.com> Message-ID: <1119889742.137016.76000@o13g2000cwo.googlegroups.com> Thank you, this really looks cool! From johan at sege.nu Thu Jun 9 07:49:04 2005 From: johan at sege.nu (Johan =?iso-8859-1?Q?Segern=E4s?=) Date: Thu, 9 Jun 2005 13:49:04 +0200 Subject: XML + SOAP + Webservices In-Reply-To: <20050609112130.GA5931@segernas.se> References: <20050609112130.GA5931@segernas.se> Message-ID: <20050609114904.GB5931@segernas.se> On 2005-06-09 13:21 +0200 or thereabouts, Johan Segern?s wrote: > I'm put on building a system in Python and I haven't used either webservices, > SOAP or Python so I'm a bit lost. Addon: I will speak to .NET-stuff in the other end, does this create problems? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From lycka at carmen.se Wed Jun 8 09:40:24 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 08 Jun 2005 15:40:24 +0200 Subject: reg php.ini equivalent file in python In-Reply-To: References: Message-ID: praba kar wrote: > Dear All, > > I have one doubt. Is there python.ini > file like php.ini in Php? There is no such thing in Python. Python is a programming language. It doesn't try to be an operating system or a web server. There are a number of web application toolkits written in Python, but I don't know whether any of them includes these kinds of resource limitations. The limitations on execution time and memory size are handled by the operating system. With Python, you don't have the convenience of setting this in an OS independent way, but it seems from you rext that it doesn't work OS independently in PHP either. I don't know about post content length, but it seems strange to me to set this globally. It's not as if the same maximum length makes sense for all forms on a typical web site. From mblume at socha.net Sun Jun 19 08:44:47 2005 From: mblume at socha.net (Martin Blume) Date: Sun, 19 Jun 2005 14:44:47 +0200 Subject: oddness in super() References: <42B4B22F.1090204@lexicon.net> <42b558b1$0$1153$5402220f@news.sunrise.ch> <87psuish79.fsf@lucien.dreaming> Message-ID: <42b568bf$0$1148$5402220f@news.sunrise.ch> "Bj?rn Lindstr?m" schrieb > > > A great analysis, but what's a "pogo stick" and where can I get one? > > http://search.ebay.com/pogo-stick > Yes, that explains the "bouncing with the pogo stick"; I would have poked around with a stick. ROTFL, thank you. Martin From bj_666 at gmx.net Thu Jun 23 19:36:47 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 24 Jun 2005 01:36:47 +0200 Subject: Package organization References: Message-ID: In , Thomas Lotze wrote: > Assume I have a package called PDF. Should the classes then be called > simply File and Objects, as it is clear what they do as they are > imported from PDF? Or should they be called PDFFile and PDFObjects, as > the names would be too undescriptive otherwise? It depends on the length of the module name in my projects. There's not much difference in importing `PDFFile` from the module or using `PDF.File`. If the name of the module is long, I prefer to explicitly import the names I need from the module. In that case it's nice to have a more descriptive name than `File`. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Tue Jun 21 19:53:01 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 22 Jun 2005 09:53:01 +1000 Subject: *Python* Power Tools In-Reply-To: References: Message-ID: <42b8a85d$1@news.eftel.com> Micah wrote: > Anyone know if there is any organized effort underway to implement the > Python equivalent of "Perl Power Tools" ? > > If not, would starting this be a waste of effort since: +1 WOFTAM-of-the-year > > - it's already being done in Perl? > - cygwin thrives? For windows users, apart from cygwin, there are a couple of sources of binaries for *x command-line utilities (unxutils, gnuwin32). > - UNIX is already pervasive :-) ? > > Or would people really like to claim a pure Python set of UNIX > utilities? Sorry, can't parse that last sentence. From exarkun at divmod.com Thu Jun 30 15:08:11 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 30 Jun 2005 15:08:11 -0400 Subject: Scket connection to server In-Reply-To: Message-ID: <20050630190811.26278.1647308843.divmod.quotient.3273@ohm> On Thu, 30 Jun 2005 18:39:27 +0100, Steve Horsley wrote: >JudgeDread wrote: >> hello python gurus >> >> I would like to establish a socket connection to a server running a service >> on port 29999. the host address is 10.214.109.50. how do i do this using >> python? >> >> many thanks >> >> > >Off the top of my head (so there could be errors): > There are a few: >import socket >s = socket.Socket() s = socket.socket() >s.connect((10.214.109.50, 29999)) s.connect(('10.214.109.50', 29999)) >s.send("Hello, Mum\r\n") s.sendall("Hello, Mum\r\n") > >That should point you in the right direction, anyway. > >There is a higher level socket framework called twisted that >everyone seems to like. It may be worth looking at that too - >haven't got round to it myself yet. Twisted is definitely worth checking out. Jp From prabapython at yahoo.co.in Wed Jun 29 03:15:43 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 29 Jun 2005 08:15:43 +0100 (BST) Subject: How to connect python and Mysql? In-Reply-To: Message-ID: <20050629071543.2558.qmail@web8409.mail.in.yahoo.com> Dear All, I am using python2.4 and Mysql 4.0.20. Now I am want to connect python and mysql. I have problem to install Mysql-python-1.2.0 interface into my machine. When I try to install this interface the following error restrict to install fully. /System/Links/Executables/ld: cannot find -lmysqlclient_r collect2: ld returned 1 exit status error: command 'gcc' failed with exit status 1 So If anybody knows regarding this kindly mail me regards PRabahar __________________________________________________________ Free antispam, antivirus and 1GB to save all your messages Only in Yahoo! Mail: http://in.mail.yahoo.com From sjmachin at lexicon.net Thu Jun 16 17:49:22 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 17 Jun 2005 07:49:22 +1000 Subject: utf8 and ftplib In-Reply-To: References: Message-ID: <42B1F3E2.70200@lexicon.net> Richard Lewis wrote: > Hi there, > > I'm having a problem with unicode files and ftplib (using Python 2.3.5). > > I've got this code: > > xml_source = codecs.open("foo.xml", 'w+b', "utf8") > #xml_source = file("foo.xml", 'w+b') > > ftp.retrbinary("RETR foo.xml", xml_source.write) > #ftp.retrlines("RETR foo.xml", xml_source.write) > > It opens a new local file using utf8 encoding and then reads from a file > on an FTP server (also utf8 encoded) into that local file. It comes up > with an error, however, on calling the xml_source.write callback (I > think) saying that: > > "File "myscript.py", line 75, in get_content > ftp.retrbinary("RETR foo.xml", xml_source.write) > File "/usr/lib/python2.3/ftplib.py", line 384, in retrbinary > callback(data) > File "/usr/lib/python2.3/codecs.py", line 400, in write > return self.writer.write(data) > File "/usr/lib/python2.3/codecs.py", line 178, in write > data, consumed = self.encode(object, self.errors) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 76: > ordinal not in range(128)" > > I've tried using both the commented lines of code in the above example > (i.e. using file() instead of codecs.open() and retlines() instead of > retbinary()). retlines() makes no difference, but if I use file() > instead of codecs.open() I can open the file, but the extended > characters from the source file (e.g. foreign characters, copyright > symbol, etc.) all appear with an extra character in front of them > (because of the two char width in utf8?). Saying "appear with an extra character in front of them" is close to useless for diagnostic purposes -- print repr(sample_string) would be more informative. In any case, the file with the "foreign" [attitude?] characters may well be what you want. > > Is the xml_source.write callback causing the problem here? Or is it > something else? Is there any way that I can correctly retrieve a utf8 > encoded file from an FTP server? To get an exact copy of a file via FTP -- doesn't matter whether it's encoded in utf8 or ESCII or whatever -- use the following combination: xml_source = file("foo.xml", 'w+b') ftp.retrbinary("RETR foo.xml", xml_source.write) If you were using a command-line FTP client, you would use the "binary" command before doing a "get" or "mget". HTH, John From tim.golden at viacom-outdoor.co.uk Fri Jun 3 11:43:30 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 3 Jun 2005 16:43:30 +0100 Subject: tempfile.gettempdir() result on Windows Message-ID: <9A28C052FF32734DACB0A288A3533991EBB88C@vogbs009.gb.vo.local> [Leo Breebaart] | | On MS Windows, I am trying to find out a good default location to | save some temporary files. | | The tempfile module seemed to have exactly what I wanted: | | >>> import tempfile | >>> tempfile.gettempdir() | 'c:\\docume~1\\admini~1\\locals~1\\temp' | >>> | | My problem (entirely cosmetic, but still) is that I also need to | show this location to the users of my program, who I suspect | would be much happier with a 'proper' Windows path than with this | '~1' DOS malarkey. | | Does anybody know how I can obtain a temp directory in 'verbose' | format (or somehow convert the gettempdir() result to that)? Have a look at win32api.GetLongPathName (from the pywin32 extensions, in case it wasn't obvious). So something like this: import tempfile import win32api print tempfile.gettempdir () print win32api.GetLongPathName (tempfile.gettempdir ()) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From twic at urchin.earth.li Thu Jun 16 13:55:51 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 16 Jun 2005 18:55:51 +0100 Subject: Python & firewall control (Win32) In-Reply-To: References: Message-ID: On Thu, 16 Jun 2005, Tim Williams wrote: > Does anyone know of (personal/desktop) firewall that can be controlled > via Python, or a Python Firewall package, or even something like DAXFi > but not dormant ? > > The XP native firewall appears to have an API, but I'm not convinced I > want to go that route unless it is relatively simple. http://wipfw.sourceforge.net/ import os def deny(src, dst, proto="all"): cmd = "ipfw add deny " + proto + " from " + src + " to " + dst os.system(cmd) ipfw for Windows is technically in beta, but ipfw itself is rock solid. tom -- The few survivors on ousfg's side ended up in a monastery of immortal monks who yearned for a life better than street-fighting social groups, learning to grow extra hands and feet on the way to immortality. -- Lyndsey Pickup From csstevens at gmail.com Thu Jun 2 00:04:18 2005 From: csstevens at gmail.com (Svens) Date: 1 Jun 2005 21:04:18 -0700 Subject: Beginner question: Logs? In-Reply-To: References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> Message-ID: <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Hey thanks... Still getting an error message though. Here's what i'm doing: ------ import math log10(15625) ------ -It says that log10 is not defined, but it is since the module is imported, right? From claudio.grondi at freenet.de Wed Jun 15 15:59:12 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 15 Jun 2005 19:59:12 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> <42AFB8FD.1060504@REMOVEMEcyber.com.au> Message-ID: <3hb8jbFgauajU1@individual.net> > Yes, both the sun and the moon have gravitational fields which affect > tides. But the moon's gravitational field is much stronger than the sun's, > so as a first-order approximation, we can ignore the sun. Here we are experiencing further small lie which found its way into a text written by an author probably not aware, that he is creating it. I have picked it out, not because I am so biased towards the very detail, but because it is a good example of how hard it is to discuss without creating small lies one after another. The school books are filled with statements similar to the above causing endless confusion and misunderstandings. "the moon's gravitational field is much stronger than the sun's" ... Sure it is the opposite, i.e. the gravitational field of the sun is much stronger than that of the moon. What was intended to state is probably, that the gravitational force caused by attraction of the masses of earth and the sun applied to earth is lower than the gravitational force caused by attraction of the masses of earth and the moon (applied to earth). I am sure, that if someone will analyse the statement above deep enough he will find some more small lies originated by the temptation to keep any statements short and simple without giving a precise definition of all assumptions required to be known in order to understand it right. What leads to confusion is also the explanation that the water of the oceans is attracted by the moon. It is only half of the true. The another half is, that the moon is attracted by the water of the oceans. It is very interesting, that in the minds of many people the gravitational force acts only on one body. Many think I am stupid, when I try to insist that the gravitational force a human body exerts on earth is the same as that which the earth exerts on a human body. "the human body is so small, so the gravitational force it exerts on earth can be neglected compared to the gravitational force the earth exerts on the human body" is the explanation. The problem of science is, that for communication of its findings it has to use the same language which is used also for many other purposes. The problem of text writers is, that it is so convienient to use shortcuts to what one thinks, but has just forgotten to mention before. It is also common to expresses own thoughts in an inappropriate way because at the moment the right words are just not there. Hope this above has cleared away all what was clear before ;/) What has it all to do with Python? To be not fully off-topic, I suggest here, that it is much easier to discuss programming related matters (especially in case of Python :-) or mathematics than any other subjects related to nature, because programming is _so easy_ compared to what is going on in the "real world". I see the reason for that in the fact, that programming is based on ideas and rules developed by humans themselves, so it is relatively easy to test and proove if statements are right or not. Exception is when the source code is hidden like the rules directing the behaviour of our Universe, what sure shouldn't be interpreted, that people hiding source code behave more like The Creator than others making it public ;/) Claudio "Roy Smith" schrieb im Newsbeitrag news:roy-568484.09073015062005 at reader1.panix.com... > Steven D'Aprano wrote: > > > Roy Smith wrote: > > > Steven D'Aprano wrote: > > > > > > >High and low tides aren't caused by the moon. > > > > > > > > > They're not??? > > > > Nope. They are mostly caused by the continents. If the > > Earth was completely covered by ocean, the difference > > between high and low tide would be about 10-14 inches. > > Yeah, I know about all that stuff. But, let's explore this from a teaching > point of view. > > > The true situation is that tides are caused by the > > interaction of the gravitational fields of the sun, the > > moon and the Earth, the rotation of the Earth, the > > physical properties of water, its salinity, the depth, > > shape and composition of the coast and shoreline, the > > prevailing ocean currents, vibrationary modes of the > > ocean (including up to 300 minor harmonics), ocean > > storms, and even the wind. > > That's a lot of detail to absorb, and is appropriate for a college-level > course taken by oceanography majors. The key to teaching something is to > strip away all the details and try to get down to one nugget of truth with > which you can lay a foundation upon which further learning can happen. > > Yes, both the sun and the moon have gravitational fields which affect > tides. But the moon's gravitational field is much stronger than the sun's, > so as a first-order approximation, we can ignore the sun. > > And, yes, there's a huge amplifying effect caused by coastline shape and > resonant frequencies of the ocean basins, but if you took away the moon > (remember, we're ignoring the sun for now), there would be no tides at all. > If you took away all the continents, there would still be tides, they would > just be a lot less (and nobody would notice them!). > > And, yes, wind affects tide. I live at the western tip of Long Island > Sound. If the wind is blowing hard along the axis of the Sound for a solid > day or two, I can see that it has a drastic effect on the tides. > > This says to me that "The tides are created by the moon, amplified by the > shapes of the land masses, and altered by the wind". > > Sure, "the moon causes the tides" is not the whole picture, and from a > quantitative point of view, may not even be the major player, but from a > basic "How do I explain this physical process to a 6th grade child in a way > that's both easy to understand and fundamentally correct", I think "the > moon causes the tides" is the only reasonable explanation. Once that basic > idea is planted, all the other stuff can get layered on top to improve the > understanding of how tides work. > > So, to try and bring this back to the original point of this thread, which > is that Python is a better first language than C, let's think of the moon > as the "algorithms, data structures, and flow control" fundamentals of > programming, and memory management as the continents and ocean basins. > What you want to teach somebody on day one is the fundamentals. Sure, > there are cases where poor memory management can degrade performance to the > point where it swamps all other effects, but it's still not the fundamental > thing you're trying to teach to a new CS student. From harold.fellermann at upf.edu Thu Jun 23 09:53:06 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 23 Jun 2005 15:53:06 +0200 Subject: Python internals and parser In-Reply-To: <42b9d592$0$31813$ba624c82@nntp06.dk.telia.net> References: <42b9d592$0$31813$ba624c82@nntp06.dk.telia.net> Message-ID: <16f7f243856243140b879df9608e12a7@upf.edu> Hi, On 22.06.2005, at 23:18, Michael Barkholt wrote: > Is there any detailed documentation on the structure of Pythons > internals, > besides the source code itself? > > More specifically I am looking for information regarding the C parser, > since > I am looking into the viability of using it in another project that > needs > to parse python code (and I would like the code to be written in C). maybe this link might help you: http://wiki.cs.uiuc.edu/cs427/PYTHON -- "Wahrheit ist die Erfindung eines L?gners" -- Heinz von Foerster From chad.hughes at pnl.gov Mon Jun 6 18:47:03 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Mon, 06 Jun 2005 15:47:03 -0700 Subject: EnumKey vs EnumValue Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6144@pnlmse27.pnl.gov> EnumKey enumerates subkeys which are equivalent to the folders in regedit. EnumValue enumerates values only. The reason your script is not printing anything must be due to the fact that you are passing in a registry path that contains only subkeys and no values. As I mentioned before, the folders are the subkeys, but the values are the name, type, data tuple in a given key. Some loosely call the values keys, but technically, the keys are the folders and the values are the names. The names can be set to a specific data item. Hence the data column in regedit. The type is obviously the data type of the data that is associated with a given value (name). So, to summarize, keys are the folders that hold values that are set to data of a specific type. Keys are equivalent to the path, values are equivalent to the name in regedit. That value is assigned a date item of a specific type. This can get confusing because people commonly referred to the values as keys when keys are actually the folders. -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of Pykid Sent: Monday, June 06, 2005 1:07 PM To: python-list at python.org Subject: EnumKey vs EnumValue I'm having trouble getting any responses back from the following snippet, where I am just trying to read some data from the Windows Registry. I intend to do a little bit more with this but will work on that later, but I think I can get more data back from EnumValue, I'd like to see the differences between them. I am running Python 2.3 on XP and can get a response from EnumKey, but EnumValue returns nothing at all; the key listing even returns 0 keys when it prints out the status. But EnumKey returns the right number and even prints out the keys I expect, I copied some of this from the Cookbook and can't tell what might be the problem. Thanks for any help. - M ------------------------------------- from _winreg import * findkey = raw_input("What key do you want to look for? ") key = "SOFTWARE\\"+findkey machine = ConnectRegistry(None,HKEY_LOCAL_MACHINE) regpath = OpenKey(machine,key) print "Looking for",key for i in range(25): try: regEndeca = EnumKey(regpath,i) print regEndeca except EnvironmentError: print "There are", i,"keys under",key break print "That was using EnumKey." for j in range(25): try: regstr,value,type = EnumValue(regpath,j) print regstr,value,type except EnvironmentError: print "There are", j,"keys under",key break print "That was using EnumValue." -- http://mail.python.org/mailman/listinfo/python-list From aahz at pythoncraft.com Mon Jun 27 18:14:29 2005 From: aahz at pythoncraft.com (Aahz) Date: 27 Jun 2005 15:14:29 -0700 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: In article , Ivan Van Laningham wrote: >Aahz wrote: >> >> Perhaps. But adding the time to learn those IDEs in addition to the time >> to learn Java is ridiculous. I've been forced to use Java a bit to >> support credit cards for our web application; I've got a friend whose >> Java-vs-Python argument hinges on the use of Eclipse; I was unable to >> make use of Eclipse in the time I had available for the project. > >Were there _good_ reasons not to do the credit card part of the web app >in Java instead of Python? As in, there is no secure module, or you >didn't have time, or Python doesn't support crucial APIs? I'm very >curious. The problem was that we needed to use a vendor-supplied library. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From could.net at gmail.com Thu Jun 30 08:14:43 2005 From: could.net at gmail.com (could ildg) Date: Thu, 30 Jun 2005 20:14:43 +0800 Subject: How to compare two directories? In-Reply-To: References: Message-ID: <311b5ce10506300514469ee1d9@mail.gmail.com> I found dircmp compare only the direct dirs and files, and it will not do anything to the sub-directories. On 6/29/05, Michael Hoffman wrote: > could ildg wrote: > > I want to compare 2 directories, > > and find If all of theire sub-folders and files and sub-files are identical. > > If not the same, I want know which files or folders are not the same. > > I know filecmp moudle has cmpfiles function and a class named dircmp, > > they may help, but I wonder if there is a ready-to-use function in python libs? > > That's a good start. Why doesn't dircmp work for you? > -- > Michael Hoffman > -- > http://mail.python.org/mailman/listinfo/python-list > From guettli at thomas-guettler.de Fri Jun 24 06:49:08 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Fri, 24 Jun 2005 12:49:08 +0200 Subject: Favorite non-python language trick? References: Message-ID: Am Fri, 24 Jun 2005 00:55:38 -0600 schrieb Joseph Garvin: > As someone who learned C first, when I came to Python everytime I read > about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > getattr/setattr, the % operator, all of this was very different from C. > > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > > Here's my current candidate: [cut] > This syntax lets you do a nifty trick, where you can add or subtract a > third dash to change whether or not code runs: I do it this way: if 0: # Just for testing print value ..... You only need to change "if 0" to "if 1" and the code gets executed. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From cam.ac.uk at mh391.invalid Tue Jun 28 16:06:37 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 28 Jun 2005 21:06:37 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. Many companies hire salespersons from Britain to > represent their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? > > Be blunt. We Americans need to know. To be blunt, I have no idea what this has to do with Python. Surely selecting the right forum to use indicates more sophistication and high intelligence than the way one speaks. ;-) -- Michael Hoffman From john106henry at hotmail.com Wed Jun 15 11:50:16 2005 From: john106henry at hotmail.com (John Henry) Date: 15 Jun 2005 08:50:16 -0700 Subject: Opening a drive folder from Python In-Reply-To: References: Message-ID: <1118850616.606416.127550@g14g2000cwa.googlegroups.com> Thanks, Chad. That works. -- John From dalke at dalkescientific.com Fri Jun 3 01:30:42 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 03 Jun 2005 05:30:42 GMT Subject: Two questions References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> <429FD0D3.7060000@REMOVEMEcyber.com.au> Message-ID: Steven D'Aprano wrote: > The existence of one or two or a thousand profitable software packages > out of the millions in existence does not invalidate my skepticism that > some random piece of software will directly make money for the > developer. 'Tis true. I think (but have no numbers to back me up) that most software in the world is developed in-house and is not distributed. Eric Raymond at http://www.catb.org/~esr/writings/magic-cauldron/magic-cauldron-3.html says it's <5% For example, all my income has been from consulting and contract work, and none from product development. > Even assuming that the money-making ability would be lost if the source > code was available, which is not a given (id software open-sources old > versions of their rendering engines, and MySQL is quite profitable and > their software is available source code and all). Regarding id, see section 10.3 of http://www.catb.org/~esr/writings/magic-cauldron/magic-cauldron-10.html They open their software when there isn't much money to be made from it. See also John Carmack's comments at http://slashdot.org/interviews/99/10/15/1012230.shtml > Going open-source from development day one with a game probably doesn't > make much sense. Design by committee doesn't work particularly well, and > for something with as much popular appeal as games, the signal to noise > ratio would probably be very low. ... > I am going to be releasing the majority of the code for Q3 soon, but > there will still be proprietary bits that we reserve all rights to. > We make a fairly good chunk of income from technology licensing, so > it would take some damn good arguments to convince everyone that giving > it all away would be a good idea. MySQL isn't relevant; I know there's companies that make money that way. There's also those that don't, and there are times when obsfucation (compiling, .pyc, etc) changes the economic landscape enough to bring in enough extra money that overrides what is to many the low or non-existent moral obligation to provide the original source in an easily usable and re-distributable form. > Software rarely makes money for the developers directly. The odds are > against any developer, hence my skepticism. Software and restaurant startups have high failure rates. But people like to think they are special and can beat the odds. Some do. >> - stock market trading companies make money in part by having >> specialized software to help with market trading, forecasts, etc. > > You are mixing up a number of seperate issues here. Yes, I am. > If they distribute the software externally, then they almost certainly > have more protection from licence agreements and copyright than they get > from merely hiding the source. If they even do hide the source code, > which is not a given. Ahh, I thought by "hide the source" you meant "not open source". Of course there are many schemes whereby purchasers also get access to the code but don't have redistribution rights. > In-house use of market forecasting software falls into the "carpenter's > hammer" category, not the "make money by selling software" category. I was actually thinking of market trading software that was sold. It's rather absurd to hide software from yourself. One story I heard at the Python conference in Houston ('98, I think) was of a company that developed this sort of package. They redid it and in-house used the newer version but sold the older and less capable version to other companies, including competitors. Nothing to do with open/closed/hidden/etc. but an interesting story. > As for selling forecasting software, well, you haven't demonstrated that > making the source code available would harm the ability to make money > from it. Firstly, very often the value of the software is not the > algorithms they use (curve fitting software and extrapolation algorithms > are hardly secret), but the data used by the algorithm. So long as you > keep the financial data proprietary, keeping the source code secret adds > nothing. At the 2000 Python conference in DC, Eric Raymond was the keynote. He presented his ideas from "The Magic Cauldron" http://www.catb.org/~esr/writings/magic-cauldron/magic-cauldron.html One of the examples he gave of a program that should not be open-sourced was from a company that developed software to optimize lumber cutting from a tree. In that case the value *was* the algorithm used. Note by the way that there were several objections to his presentation. One was to his "Give Away the Recipe, Open A Restaurant" http://www.catb.org/~esr/writings/magic-cauldron/magic-cauldron-9.html#ss9.3 In his talk he mentioned a famous restaurant, and pointed out you could get the recipes for the meals. One guy from the audience said he worked for a sister restaurant to the one cited, that they signed NDAs, and that the published recipes often excluded a few key parts, to make it hard to duplicate. >> You are the US government developing software to design/test the next >> generation nuclear weapons system and don't want any other country to >> use it. (GnuNuke?) > > Then don't distribute the software, object or source code. What about the software in the weapon itself? When used it's certainly delivered. As I joked with Greg Ewing - might as well include the source code with the warhead. >> You are a student working on a take-home example and you aren't >> allowed to work with/help anyone else > > Er, I don't see how this is supposed to work. An example of what? How > does keeping the source code secret prevent the student from working > with others? There's an ethical obligation. I could modify the situation a bit; turn it into an assignment instead of a test, and have the user testing & QA with other classmates be part of the assignment but that sharing code isn't. Distributing a .pyc might be considered sufficient protection if a plagarism charge is investigated. Andrew dalke at dalkescientific.com From michele.simionato at gmail.com Tue Jun 14 03:37:00 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Jun 2005 00:37:00 -0700 Subject: What is different with Python ? In-Reply-To: <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: <1118734620.851366.291360@f14g2000cwb.googlegroups.com> Andrea Griffini wrote: >This is investigating. Programming is more similar to building >instead (with a very few exceptions). CS is not like physics or >chemistry or biology where you're given a result (the world) >and you're looking for the unknown laws. In programming *we* >are building the world. This is a huge fundamental difference! It looks like you do not have a background in Physics research. We *do* build the world! ;) Michele Simionato From sjmachin at lexicon.net Thu Jun 30 08:30:25 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 30 Jun 2005 22:30:25 +1000 Subject: Store multiple dictionaries in a file In-Reply-To: <42c3cccd$0$12707$626a14ce@news.free.fr> References: <42c3cccd$0$12707$626a14ce@news.free.fr> Message-ID: <42C3E5E1.1080208@lexicon.net> bruno modulix wrote: > Philipp H. Mohr wrote: >>My code currently produces a new dictionary every iteration and >>passes it on to another peace of code. > > > May this code rest in piece Perhaps it's the piece of code that passeth all understanding? From piet at cs.uu.nl Tue Jun 14 04:29:53 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 14 Jun 2005 10:29:53 +0200 Subject: Access Database Using Python References: <1118692535.061915.239510@o13g2000cwo.googlegroups.com> Message-ID: >>>>> "Karthish" (K) wrote: >K> I can't figure out how to authenticate and then load a page, since the >K> page requires cookies for authentication. http://www.voidspace.org.uk/python/articles/cookielib.shtml http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From spam.csubich+block at block.subich.spam.com Wed Jun 8 18:12:15 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 18:12:15 -0400 Subject: Fast text display? In-Reply-To: References: Message-ID: Jp Calderone wrote: > If you like, you can check out the code: > > http://sourceforge.net/projects/originalgamer > > As MUD clients go, it's pretty weak, but it solves the text display > problem pretty decently. Oooh! Code! Thanks! After taking an extremely quick look, I think I might be kicking myself soon for not knowing about Twister and writing socket code thus far instead. Interesting to see how someone else solves a the same problem. :) From deets at web.de Thu Jun 9 11:05:07 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 09 Jun 2005 17:05:07 +0200 Subject: XML + SOAP + Webservices In-Reply-To: References: Message-ID: > Basically, don't write the implementation to talk to the SOAP/WDSL-services > in Python, find something else and this 'something else' produces an XML file > which I then parse with Python? For example - or better, instead of passing XML use an RPC mechanism Python is good at - e.g. corba. So you could do some java middleware-thing here, actually done in jython for convenience. Still, not the nicest of architectures - but a goable way. > > win32 isn't an option, we only have *nix-boxes around and we plan to stay > that way. But can't you run some service on the .net-boxes? And what's about mono? There is an .net based python out there - afaik even two: One is written to be running on .net (and thus might be able to be running on mono, interfacing .net-components remotely), one "only" gives access to .net objects - so you could use that to create teh necessary middleware. Diez From exarkun at divmod.com Tue Jun 21 12:55:02 2005 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 21 Jun 2005 12:55:02 -0400 Subject: smtplib and TLS In-Reply-To: <1119368342.884338.266040@g43g2000cwa.googlegroups.com> Message-ID: <20050621165502.5047.1930197373.divmod.quotient.6695@ohm> On 21 Jun 2005 08:39:02 -0700, Matthias Kluwe wrote: >> From: "Paul Rubin" "http://phr.cx"@NOSPAM.invalid > >>> "Matthias Kluwe" writes: >>> After getting a @gmail.com address, I recognized I had to use TLS in my >>> python scripts using smtplib in order to get mail to the smtp.gmail.com >>> server. > >>> [...] > >>> The server accepts and delivers my messages, but the last command >>> raises > >>> socket.sslerror: (8, 'EOF occurred in violation of protocol') > >> [...] > >> Have you verified that its your end that is broken, not gmail's, do other >> servers give the same response ? > >No, I have not -- I should have, as I know now: Connecting, starttls, >login and sending mail works fine without the above mentioned error >using my previous mail provider. > >Does that mean Gmail is in error here? I don't know... Most SSL servers and clients (primarily HTTP, but some SMTP as well) are broken in this regard: they do not properly negotiate TLS connection shutdown. This causes one end or the other to notice an SSL protocol error. Most of the time, the only thing left to do after the TLS connection shutdown is normal TCP connection shutdown, so the error doesn't lead to any problems (which is probably why so much software generates this problem). Of course, there's no way to *tell* if this is the case or not, at least programmatically. If you receive an OK response to your DATA, you probably don't need to worry, since you have gotten what you wanted out of the conversation. It's entirely possible that the fault here lies on gmail's end, but it is also possible that the fault is in your code or the standard library ssl support. Unless you want to dive into Python's OpenSSL bindings or start examining network traces of SSL traffic, you probably won't be able to figure out who's to blame in this particular case. The simplest thing to do is probably just capture and discard that particular error (again, assuming you are getting an OK resposne to your DATA command). Jp From piet at cs.uu.nl Wed Jun 1 17:29:24 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 01 Jun 2005 23:29:24 +0200 Subject: The need to put "self" in every method References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: >>>>> aahz at pythoncraft.com (Aahz) (A) wrote: >A> [posted & e-mailed] >A> In article , >A> Piet van Oostrum wrote: >>> >>> There is. >>> Inside a method there are 3 kinds of identifiers: >>> - local ones e.g. parameters and local variables >>> - global ones (actually module-level) >>> - instance variables and methods >>> >>> Because Python has no declarations there must be a different way to >>> indicate in which category an identifier falls. For globals it is done with >>> the 'global' keyword (which actually is a declaration), for instance >>> variables the dot notation (object.name) is used and the rest is local. >>> Therefore every instance variable or instance method must be used with the >>> dot notation, including the ones that belong to the object `itself'. Python >>> has chosen that you can use any identifier to indicate the instance, and >>> then obviously you must name it somewhere. It could have chosen to use a >>> fixed name, like 'this' in Java or C++. It could even have chosen to use a >>> keyword 'local' to indicate local ones and let instance ones be the >>> default. But if instance variable would be implicit, local ones should have >>> been explicit. >A> Any objection to swiping this for the FAQ? (Probably with some minor >A> edits.) No. The global/local stuff needs a bit more nuance (assignments in the method being the criterium). -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From mwm at mired.org Fri Jun 10 19:13:30 2005 From: mwm at mired.org (Mike Meyer) Date: Fri, 10 Jun 2005 18:13:30 -0500 Subject: Sending mail from 'current user' in Python References: <3gsve7Fe8957U1@individual.net> Message-ID: <863brp6c11.fsf@guru.mired.org> Leo Breebaart writes: > I can get the username info (at least on Unix) via the 'pwd' > module, but that still leaves me with the domainname, or rather > the mailname, and I have not been able to spot a way of finding > that from within Python. (I could try opening /etc/mailname by > hand, but how standard is that filename/location?) Not very. Certainly doesn't exist on FreeBSD, and doesn't appear anywhere in the sources for my UMA. BTW, an alternative for the username is the USER environment variable. I don't know whether or not it exists on Windows. > I've also tried opening a pipe to sendmail, and feeding the > message to that instead. This too works great (and does give an > appropriate default 'From'), but that also turns my problem into > the problem of finding the location of the sendmail program, > which doesn't seem like much of an improvement, portability-wise. Well, you could provide a list of places to look for it. But you're right, this doesn't help much with portability. > Finally, if at all possible I'd also like to get this working on > Windows, so I'd rather stick with the standard smtplib if I can. smtplib needs an SMTP server to connect to. For unix systems, this is typically localhost. What do you use for Windows systems? Or are you connecting to your machine to deliver the mail? The problem with getting this working on Windows is that, IIRC, the information you need is configured in the UMA, and not in some system-wide location, at least on some versions of Windows, and it typically is unrelated to the name of the Windows box you're on. Given those constraints, the simple solution is probably to ask the user for the information you need. Failing that, and assuming os.env['USER'] exists on windows, you could try: 1) Looking up the IP address of the host in question. Not the interface - you need the address the outside world sees. See for example. 2) Do a reverse DNS lookup on that ip address to get a host name. If they've got a dynamic IP address, this will probably be something ugly, if you get anything at all. 3) Start doing MX lookups on that host name, stripping off one domain level at a time from the left until you get an address with an MX record, or you've got nothing left. This assumes that an MX record will exist for the part of the domain name which get mail - which may not be true. This entire procedure also assumes that the user reads mail using their ISP-provided maildrop, which may not be true. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From grante at visi.com Tue Jun 28 16:30:35 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 28 Jun 2005 20:30:35 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c3c3uipbjcg58@corp.supernews.com> <1119990278.946209.303550@g14g2000cwa.googlegroups.com> Message-ID: <11c3crbi1kmsn9f@corp.supernews.com> On 2005-06-28, Devan L wrote: > Thats like posting about Google here because the newsgroup is hosted on > Google. Except the newsgroup isn't "hosted on Google", and it's far less interesting than Monty Python. -- Grant Edwards grante Yow! "THE LITTLE PINK at FLESH SISTERS," I saw them visi.com at th' FLUROESCENT BULB MAKERS CONVENTION... From saint.infidel at gmail.com Wed Jun 1 13:53:58 2005 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2005 10:53:58 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117647935.916469.164160@g47g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> Message-ID: <1117648438.079178.92490@z14g2000cwz.googlegroups.com> > because i need the representations of the other systems types to > themselves be python classes, and so i need a metaclass to make sure > they follow certain rules. This metaclass is for that system what type > is for python I think that's exactly the same thing I just said. More or less. Although depending on exactly what you mean by "follow certain rules", you might only need a common base class rather than a metaclass. > same thing, no? Uh, no, I don't think so. type is, from my trivial understanding, the base type and base metaclass for everything else in python. Saying "type is an object" is only confusing you into thinking it is a subclass of object, which is not the case. object is a class, which I believe has type as it's metaclass (though I could be mistaken - this gets terribly confusing very quickly). From jrastrick at student.usyd.edu.au Wed Jun 1 21:34:49 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 1 Jun 2005 18:34:49 -0700 Subject: any macro-like construct/technique/trick? In-Reply-To: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: <1117676088.978273.272940@g47g2000cwa.googlegroups.com> Is having to read two lines really that much worse than one? And the only thing you find objectionable about the most obvious solution? If so, then what's wrong with: def foo(): # .... do some stuff if debug: emit_dbg_obj(DbgObjFoo(a,b,c)) # .... do more stuff To my mind, this is no less readable and no more clutter than DEBUG_EMIT(DbgObjFoo(a,b,c)) Then again, I don't mind the two line version - personally, I prefer my debug code be more conspicuous rather than less, so that its clearly seperate, visually and hence mentally, from functional part of the code. Preprocessor Macros and their ilk have always seemed like an awful kludge to me, nessecary and useful in a language like C I'll grant, but not very Pythonic at all. If you really feel you can't stand the (presumably marginal) expense of creating the debug objects when unnessecary, and want to get rid of certain lines of code conditionally - using textual replacement, which is essentially, by my limited understanding, all a pre-processor does - then why not just do it yourself? Have emit_dbg_obj(DbgObjFoobar(a,b,c)) all you want in your in development code, and use a simple regex search and replace to comment it out of your source when the code ships. Most critically, though, if you're worried about efficiency issues this fine-grained, trying to scrounge every last byte of memory, I'd suggest Python is probably the wrong language for your problem. Object creation overhead and the like is just part of the regular cost of having a high level, dynamic, interpreted language. If you really, really need preprocessor macros for efficiency reasons, then your probably need C. I'm sorry, my reply hasn't been all that helpful I guess :) It seems a bit of a trend on this mailing list - ask for some feature, or a way to emulate it, and instead get a bunch of arguments as to why that feature doesn't fit the design and philosophy of the language, and some suggestions on how to do things differently. Probably some much more knowledgable Pythonista can cook up a way to achieve your desired behaviour, using exec or eval or some other such unsightly hack... but I can only hope such practices don't become widespread. Mac wrote: > Is there a way to mimic the behaviour of C/C++'s preprocessor for > macros? The problem: a lot of code like this: > > def foo(): > # .... do some stuff > if debug: > emit_dbg_obj(DbgObjFoo(a,b,c)) > > # .... do more stuff > if debug: > emit_dbg_obj(DbgObjBar(d,e)) > > # ... and so on ... > > Notes: > > * the two-lines of debug conditional tend to really break up the flow > of the surrounding code > > * in C you could wrap them with a macro so you could do > DEBUG_EMIT(DbgObjFoo(a,b,c)), etc, with the macro only instantiating > the object and processing it if the debug flag was set. The one-liner > is MUCH less disruptive visually when reading code > > * using > def debug_emit(obj): > if debug: > emit_dbg_obj(obj) > is a poor solution, because it *always* instantiates DbgObj*, even when > not needed; I want to avoid such unnecessary waste From jmdeschamps at cvm.qc.ca Thu Jun 9 13:34:02 2005 From: jmdeschamps at cvm.qc.ca (jean-marc) Date: 9 Jun 2005 10:34:02 -0700 Subject: Python as CGI on IIS and Windows 2003 Server In-Reply-To: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> References: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> Message-ID: <1118338442.024062.24150@o13g2000cwo.googlegroups.com> lothar.sch at gmx.de wrote: > Hi, > > My python scripts are running as cgi scripts on an IIS on Windows XP. > I have to distribute it to IIS on Windows 2003 Server. ... > Is there any difference for python as CGI on IIS between Windows XP > prof. and Windows 2003 Server? ... Yes there is a difference! I had this problem last year (developing on Win XP Pro and delivering on IIS Server), I'll try to lookup the solution, but it might be difficult (it's kind of a thing you do once and forget about later.) Jean-Marc From bogus@does.not.exist.com Thu Jun 30 10:15:02 2005 From: bogus@does.not.exist.com () Date: Thu, 30 Jun 2005 14:15:02 -0000 Subject: No subject Message-ID: #! rnews 2218 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Boss wants me to program X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 39 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: Mime-Version: 1.0 Date: Thu, 30 Jun 2005 13:53:07 GMT Xref: news.xs4all.nl comp.lang.python:384162 Peter Hansen writes: > Harry George wrote: > > "Adriaan Renting" writes: > >>Both VB and Python are easier to learn as the more powerful > >>languages, the price is that they lack features that make it easier to > >>manage large and complex projects. > > What is a large project, and what is Python missing that C++ and Java > > have for such tasks? > > But C++ and Java have features that *management* likes, thus making it > "easier to manage large projects". (That says nothing about whether > or not it makes it easier to produce quality code, successful > projects, happy customers, large profits, or any such silly > things... just that it's "easier to manage". ;-) > > Less facetiously: I have managed a large Python project or three, and > several large C++ projects (and, thankfully, no large Java projects) > and found Python quite up to the task. In fact, if anything the C++ > projects ended up more in danger of succumbing to the sheer weight of > the code than did the Python projects. But I attribute this more to > the fact that we had evolved to using agile approaches with the Python > projects than to any of those special features either present or > lacking in C++. > > Ultimately, manageability of a project is far and away more about the > people involved and the techniques used than it is about any single > technology involved. > > -Peter That's our experience too (and the reason I asked). I wonder if the OP will respond. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From tzot at sil-tec.gr Tue Jun 14 09:02:50 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 14 Jun 2005 16:02:50 +0300 Subject: Hopefully simple regular expression question References: <1118746918.581184.5470@g49g2000cwa.googlegroups.com> Message-ID: On 14 Jun 2005 04:01:58 -0700, rumours say that "peterbe at gmail.com" might have written: >I want to match a word against a string such that 'peter' is found in >"peter bengtsson" or " hey peter," or but in "thepeter bengtsson" or >"hey peterbe," because the word has to stand on its own. The following >code works for a single word: [snip] use \b before and after the word you search, for example: rePeter= re.compile("\bpeter\b", re.I) In the documentation for the re module, Subsection 4.2.1 is Regular Expression Syntax; it'll help a lot if you read it. Cheers. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From sjmachin at lexicon.net Thu Jun 2 19:24:24 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 09:24:24 +1000 Subject: mac address In-Reply-To: <1117753121.178377.24110@g14g2000cwa.googlegroups.com> References: <1117753121.178377.24110@g14g2000cwa.googlegroups.com> Message-ID: <429F9528.7010307@lexicon.net> shama.bell at gmail.com wrote: > Hello, > I am a newbie and i have problems filling an array with the mac address > read from the command line. > > The mac address is FF:FF:FF:FF:FF:FF > > options, args = parser.parse_args() > # options.d contains the address > destAddress = options.d > > data = array('L', '\0' * 24) > The array should contain the data as follows: > data[0] = 0xFF > data[1] = 0xFF > ........ > data[5] = 0xFF > Any help is appreciated > -SB > You will be better off in the long run if you try to solve these minor questions yourself. Break the problem down: First step: *split* the destAddress into 6 strings Second step: convert the strings to *long* integer, remembering to use base 16 arithmetic Third step: use the resulting 6-element list when creating "data". Why do you think you need array.array('L', ....)? What are you going to do with "data" after filling it with the address? From rkern at ucsd.edu Sat Jun 25 18:15:42 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 25 Jun 2005 15:15:42 -0700 Subject: A strange and annoying restriction, possibly a bug. A glance by a more experienced would be nice. In-Reply-To: <42BDD500.4060303@jippii.fi> References: <42BDD500.4060303@jippii.fi> Message-ID: Elmo M?ntynen wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > This is the case: > > >>>>n=(100,) tuple(*n) > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > tuple(*n) > TypeError: iteration over non-sequence n is a sequence. *n correctly expands. The error is that 100 is not a sequence; tuple() requires a sequence or an iterator. tuple(*n) is equivalent to tuple(100). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jepler at unpythonic.net Tue Jun 14 10:43:05 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Tue, 14 Jun 2005 09:43:05 -0500 Subject: [Python-Dev] A bug in pyconfig.h under Linux? In-Reply-To: References: Message-ID: <20050614144301.GE6998@unpythonic.net> [sent to python-list and poster] Did you follow the direction that Python.h be included before any system header? This is mentioned at least in http://docs.python.org/ext/simpleExample.html It's a crummy thing for Python to insist on, but if you can re-organize your headers to do this it should make the warnings go away. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dowskimania at gmail.com Tue Jun 7 12:18:01 2005 From: dowskimania at gmail.com (dowskimania at gmail.com) Date: 7 Jun 2005 09:18:01 -0700 Subject: How do I know when a thread quits? References: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> Message-ID: <1118161081.460925.206840@g14g2000cwa.googlegroups.com> I'm no threads expert, but if you use the higher-level "threading" module, you could try something like this: import threading import time def countToTen(): for i in range(1,11): print i time.sleep(0.5) child = threading.Thread(target=countToTen) class masterThread(threading.Thread): def run(self): print "Master Started" child.start() while child.isAlive(): time.sleep(0.1) print "Master Finished" master = masterThread() master.start() ---------------SCRIPT OUTPUT-------------- Master Started 1 2 3 4 5 6 7 8 9 10 Master Finished Hope this helps. Christian http://www.dowski.com From diesch at spamfence.net Sun Jun 12 14:26:57 2005 From: diesch at spamfence.net (Florian Diesch) Date: Sun, 12 Jun 2005 20:26:57 +0200 Subject: How to overcome automatic cyrillic-to-/hex convert References: Message-ID: <20050612182657.24EC.2.NOFFLE@dieschf.news.arcor.de> wrote: > But when I enter some Bulgarian (actually cyrillic) text as a string, > it > seems that Python automatically converts it to '\x00..\x00 ' and once > converted that way I can't get it back into its original look. The only > way to get it right is using print : > >>>> a = '????' # 'Mam' in Bulgarian >>>> print a > '????' > > but > >>>> a > '\xcc\xe0\xec\xe0' Did you try the locale module? Florian -- begin signature_virus Hi! I'm a signature virus. Please copy me to your signature to help me spread. end From fperez.net at gmail.com Wed Jun 8 11:21:35 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 08 Jun 2005 09:21:35 -0600 Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <1118209749.248567.168700@g49g2000cwa.googlegroups.com> <1118233766.928467.261650@z14g2000cwz.googlegroups.com> Message-ID: Rahul wrote: > > Hi. > The reason is simple enough. I plan to do some academic research > related to computer algebra for which i need some package which i can > call as a library. Since i am not going to use the package > myself..(rather my program will)..it will be helpful to have a python > package since i wanted to write the thing in python. if none is > available then probably i will need to work on an interface to some > package written in some other language or work in that language itself. I've heard of people writing a Python MathLink interface to Mathematica, which essentially turns Mathematica into a Python module. But I don't have any references handy, sorry, and as far as I remember it was done as a private contract. But it's doable. Cheers, f From steve at REMOVETHIScyber.com.au Mon Jun 13 10:34:53 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 14 Jun 2005 00:34:53 +1000 Subject: \r\n or \n notepad editor end line ??? References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Message-ID: On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote: > wrote: > >> It means in windows we should use 'wb' to write and 'rb' to read ? >> Am I right? > > no. > > you should use "wb" to write *binary* files, and "rb" to read *binary* > files. > > if you're working with *text* files (that is, files that contain lines of text > separated by line separators), you should use "w" and "r" instead, and > treat a single "\n" as the line separator. I get nervous when I read instructions like this. It sounds too much like voodoo: "Do this, because it works, never mind how or under what circumstances, just obey or the Things From The Dungeon Dimensions will suck out your brain!!!" Sorry Fredrik :-) When you read a Windows text file using "r" mode, what happens to the \r immediately before the newline? Do you have to handle it yourself? Or will Python cleverly suppress it so you don't have to worry about it? And when you write a text file under Python using "w" mode, will the people who come along afterwards to edit the file in Notepad curse your name? Notepad expects \r\n EOL characters, and gets cranky if the \r is missing. How does this behaviour differ from "universal newlines"? -- Steven From me at privacy.net Mon Jun 13 11:40:18 2005 From: me at privacy.net (Dan Sommers) Date: 13 Jun 2005 11:40:18 -0400 Subject: Tiff Image Reader/writer References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> Message-ID: On 13 Jun 2005 07:55:04 -0700, "PyPK" wrote: > Hi I am looking for a simple tiff Image reader/writer in python.Can > anyone point me to the right one. I don't know what your definition of "simple" is, but check out the Python Imaging Library (PIL) at effbot.org. Regards, Dan -- Dan Sommers From hancock at anansispaceworks.com Sun Jun 12 01:54:29 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 12 Jun 2005 00:54:29 -0500 Subject: case/switch statement? In-Reply-To: References: Message-ID: <200506120054.29698.hancock@anansispaceworks.com> On Saturday 11 June 2005 07:35 pm, Steven D'Aprano wrote: > On Sat, 11 Jun 2005 16:15:42 +0000, Joe Stevenson wrote: > > I skimmed through the docs for Python, and I did not find anything like > > a case or switch statement. I assume there is one and that I just > > missed it. Can someone please point me to the appropriate document, or > > post an example? I don't relish the idea especially long if-else > > statements. > [...] > There is no case statement in Python. If you don't care about > readability, one alternative is to use a dictionary: > > case = {5: do_this, 6: do_that} > case.get(x, do_something_else)() The really nice thing about using dictionaries for this kind of thing in Python is that what was previously hardcoded is now (dynamic) data. That makes alterations like adding a new case extremely trivial (you could load it from a config file for example, or it could be altered by plugin code which simply updates the dictionary to register itself). In my experience with C, this kind of change always comes up with switch statements, so it's nice to neatly sidestep the problem with dictionaries in Python. And perhaps that removal of a false lead is the real reason Python doesn't have a switch/case construct -- it encourages you to use a smarter solution which you'll be glad of later on. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From renting at astron.nl Tue Jun 28 07:27:07 2005 From: renting at astron.nl (Adriaan Renting) Date: Tue, 28 Jun 2005 13:27:07 +0200 Subject: Which kid's beginners programming - Python or Forth? Message-ID: In addition, for and while loops are pretty universally found in all program languages. It is therefore an essential part of material supposed to teach programming. Adriaan Renting | Email: renting at astron.nl ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands | Web: http://www.astron.nl/~renting/ >>> Daniel Dittmar 06/28/05 11:39 AM >>> gatti at dsdata.it wrote: > List comprehensions, however, *are* the basic control flow; loops are > much more verbose and they should be used only when necessary. List comprehensions are probably a bad idea for entry level programmers: - for and while loops are much easier to debug as you can insert print statements everywhere - list comprehensions don't allow you to break complex expressions into several simpler ones by using local variables, everything has to happen in one expression Daniel -- http://mail.python.org/mailman/listinfo/python-list From mwm at mired.org Tue Jun 14 17:40:42 2005 From: mwm at mired.org (Mike Meyer) Date: Tue, 14 Jun 2005 16:40:42 -0500 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> <863brlzmy9.fsf@guru.mired.org> Message-ID: <86ekb4y5ut.fsf@guru.mired.org> Andrea Griffini writes: > On Mon, 13 Jun 2005 21:33:50 -0500, Mike Meyer wrote: > >>But this same logic applies to why you want to teach abstract things >>before concrete things. Since you like concrete examples, let's look >>at a simple one: >> >> a = b + c >> > ... n>>In a very >>few languages (BCPL being one), this means exactly one thing. But >>until you know the underlying architecture, you still can't say how >>many operations it is. > > That's exactly why > > mov eax, a > add eax, b > mov c, eax Um, you didn't do the translation right. > or, even more concrete and like what I learned first > > lda $300 > clc > adc $301 > sta $302 > > is simpler to understand. No, it isn't - because you have to worry about more details. In particular, when programming in an HLL the compiler will take care of allocating storage for the variables. In assembler, the programmer has to deal with it. These extra details make the code more complicated. > Writing programs in assembler takes longer exactly beacuse > the language is *simpler*. Assembler has less implicit > semantic because it's closer to the limited brain of our > stupid silicon friend. You're right, but you have the wrong reasons. There were studies done during the 70s/80s that showed that debugged LOC from programmers is independent of the language being written. Assembler takes longer to write not because it's simpler, but because it takes more LOC to do the same operations. You can avoid that problem - to a degree - if you use an assembler that eschews the standard assembler syntax for something more abstract. For instance, whitesmith had a z80 assembler that let you write: a = b + c and it would generate the proper instructions via direct translation. This didn't reduce the LOC to the level of C, but it makes a significant dent in it. Also, you can only claim that being closer to the chip is "simpler" because you haven't dealt with a sufficiently complicated chip yet. Try writing code where you have to worry about gate settling times or pipeline stalls, and then tell me whether you think it's "simpler" than dealing with an HLL. > Programming in assembler also really teaches (deeply > to your soul) who is the terrible "undefined behaviour" > monster you'll meet when programming in C. > >>Anything beyond the abstract statement "a gets the result >>of adding b to c" is wasted on them. > > But saying for example that > > del v[0] > > just "removes the first element from v" you will end up > with programs that do that in a stupid way, actually you > can easily get unusable programs, and programmers that > go around saying "python is slow" for that reason. That's an implementation detail. It's true in Python, but isn't necessarily true in other languages. Yes, good programmers need to know that information - or, as I said before, they need to know that they need to know that information, and where to get it. >>It's true that in some cases, it's easier to remember the >>implementation details and work out the cost than to >>remember the cost directly. > > I'm saying something different i.e. that unless you > understand (you have a least a rough picture, you > don't really need all the details... but there must > be no "magic" in it) how the standard C++ library is > implemented there is no way at all you have any > chance to remember all the quite important implications > for your program. It's just IMO impossible to memorize > such a big quantity of unrelated quirks. > Things like for example big O, but also undefined > behaviours risks like having iterators invalidated > when you add an element to a vector. That may well be true of the standard C++ library - I don't write it. But it certainly doesn't appear to be true of, for instance, Python internals. I've never seen someone explain why, for instance, string addition is O(n^2) beyond the very abstract "it creates a new string with each addition". No concrete details at all. >>> Are you genuinely saying that abelian groups are >>> easier to understand than relative integers ? >> >>Yup. Then again, my formal training is as a mathematician. I *like* >>working in the problem space - with the abstact. I tend to design >>top-down. > > The problem with designing top down is that when > building (for example applications) there is no top. This is simply false. The top of an application is the application-level object > I found this very simple and very powerful rationalization > about my gut feeling on building complex systems in > Meyer's "Object Oriented Software Construction" and > it's one to which I completely agree. Top down is a > nice way for *explaining* what you already know, or > for *RE*-writing, not for creating or for learning. I also like OOSC - because it makes the abstract type system a part of the language. The approach Meyer takes emphasis the abstract. You haven't stated how you think complex systems should be built, and I think we took different lessons away from Meyer, so you'll have to state it explicitly. I agree - you don't generally build systems top-down. But building is not designing. The common alternative to top-down design - bottom-up design - makes the possibility of a semantic disconnect when you reach the top to likely. > IMO no one can really think that teaching abelian > groups to kids first and only later introducing > them to relative numbers is the correct path. > Human brain simply doesn't work like that. You didn't ask how it should be taught - you asked which I found more natural. Numbers are an abstract concept, and can be taught as such. > You are saying this, but I think here it's more your > love for discussion than really what you think. Actually, I think it's a terminology problem. Or maybe a problem defining the levels. >>The same is true of programmers who started with concrete details on a >>different platform - unless they relearn those details for that >>platform. > > No. This is another very important key point. > Humans are quite smart at finding general rules > from details, you don't have to burn your hand on > every possible fire. Unfortunately sometimes there > is the OPPOSITE problem... we infer general rules > that do not apply from just too few observations. Your opposite problem is avoided by not teaching the details until they are needed, and making sure you teach that those are implementation details, so they student knows not to draw such conclusions from them. >>The critical things a good programmer knows about those >>concrete details is which ones are platform specific and which aren't, >>and how to go about learning those details when they go to a new >>platform. > > I never observed this problem. You really did ? As mentioned, you see it all the time in c.l.python. People come from other languages, and try to write Python as if the rules for that other language apply. >>If you confuse the issue by teaching the concrete details at the same >>time as you're teaching programming, you get people who can't make >>that distinction. Such people regularly show up with horrid Python >>code because they were used to the details for C, or Java, or >>whatever. > > Writing C code with python is indeed a problem that > is present. But I think this is a minor price to pay. > Also it's something that with time and experience > it will be fixed. It can be fixed from the start by teaching the student the difference between abstract programming concepts and implementation details. >>> I suppose that over there who is caught reading >>> TAOCP is slammed in jail ... >> >>Those taught the concrete method would never have been exposed to >>anything so abstract. > > Hmmm; TACOP is The Art Of Computer Programming, what > is the abstract part of it ? The code presented is > only MIX assembler. There are math prerequisites for > a few parts, but I think no one could call it "abstract" > material (no one that actually spent some time reading > it, that is). It tackled abstract problems like "sorting". The students I'm talking about never dealt with anything that abstract. >>Actually, it's a natural place to teach the details of that kind of >>thing. An OS has to deal with allocating a number of different kinds >>of memory, with radically different behaviors and constraints. > > hehehe... and a program like TeX instead doesn't even > need to allocate memory. You're confusing "using a facility" with "building a facility". Yes, TeX needs to allocate memory. You don't need to know anything about the insides of a memory allocator to allocate memory. You can write an application like TeX without having to write a memory allocator. You can't write an OS without having to write *several* memory allocators. Are you going to claim that the right way to learn about memory allocators is by looking at uses of them, or by looking at implementations of them? > Pairing this with that teaching > abelian groups first to kids (why not fiber spaces then ?) > and that TAOCP is too "abstract" tells me that apparently > you're someone that likes to talk just for talking, or > that your religion doesn't allow you to type in smileys. Now you're resorting to straw men and name-calling. That's an indication that you no longer have any real points. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From tjreedy at udel.edu Wed Jun 22 18:02:57 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Jun 2005 18:02:57 -0400 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net><11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net><11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:11bjeckpaq4ir8e at corp.supernews.com... > The bit patterns are defined by the IEEE 754 standard. If > there are Python-hosting platoforms that don't use IEEE 754 as > the floating point representation, then that can be dealt with. > > Python has _tons_ of platform-specific code in it. More, I believe, than the current maintainers would like. Adding more would probably require a commitment to maintain the addition (respond to bug reports) for a few years. > Why all of a sudden is it taboo for Python to impliment > something that's not universally portable and defined in a > standard? ?? Perhaps you wrote this before reading my last post reporting that some NaN/Inf changes have already been made for 2.5. I believe that more would be considered if properly submitted. > Where's the standard defining Python? The Language and Library Reference Manuals at python.org. Terry J. Reedy From usenet.20.evilspam at spamgourmet.com Sun Jun 12 13:55:00 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Sun, 12 Jun 2005 17:55:00 GMT Subject: ElementTree Namespace Prefixes In-Reply-To: References: Message-ID: Andrew Dalke wrote: > On Sun, 12 Jun 2005 15:06:18 +0000, Chris Spencer wrote: > > >>Does anyone know how to make ElementTree preserve namespace prefixes in >>parsed xml files? > > > See the recent c.l.python thread titled "ElemenTree and namespaces" > and started "May 16 2:03pm". One archive is at > > http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/31b2e9f4a8f7338c/363f46513fb8de04?&rnum=3&hl=en Thanks, although that thread didn't seem to resolve the issue. All the first few links talk about is how to hack your own parser to make sense of the Clark notation. The problem at hand is with how Elementtree outputs namespaces and represents the tag name in memory. Given xml with no namespaces, Elementtree works perfectly. However, if you give the root tag an xmlns attribute, Elementtree relabels all child nodes with it's own prefix, completely defeating the purpose of the default namespace. In my opinion, this is unacceptable behavior. If an XML parser reads in and then writes out a document without having altered it, then the new document should be the same as the original. With Elementtree this isn't so. Lundh apparently believes he knows better than you and I on how our namespaces should be represented. It's a shame the default ns behavior in Elementtree is in such a poort staten. I'm surprised no one's forked Elementtree solely to fix this issue. Anyways, Python's native minidom works as expected, so I'll probably use that instead, even if the api is slightly less intuitive. Chris From prabapython at yahoo.co.in Tue Jun 14 01:38:22 2005 From: prabapython at yahoo.co.in (praba kar) Date: Tue, 14 Jun 2005 06:38:22 +0100 (BST) Subject: Reg cgi header In-Reply-To: Message-ID: <20050614053822.27715.qmail@web8407.mail.in.yahoo.com> Dear All, I have doubt regarding headers in cgi programming. If I gives "Content-Type:text/plain" then I try to print html contents. Is right or wrong after giving content-type: text/plain? regards Prabahar __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From cam.ac.uk at mh391.invalid Wed Jun 8 04:37:26 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 08 Jun 2005 09:37:26 +0100 Subject: Writing func_closure? In-Reply-To: References: Message-ID: Fernando Perez wrote: > I am trying to do a run-time modification of a function's closure, > where I want to modify the value of one of the variables in the closure. Out of curiosity, why? > In [21]: def wrap(x): > ....: def f(y): > ....: return x+y > ....: return f > ....: > > In [22]: f1=wrap('hello') > > In [23]: f1.func_closure > Out[23]: (,) > > My question is, how can I create one of these cell objects to stuff into the > closure (I want to do this from pure Python, not C extensions). >>> f1.func_closure[0].__class__() Traceback (most recent call last): File "", line 1, in ? TypeError: cannot create 'cell' instances Hmmm, that didn't work so well. >>> f1.func_closure = f1.func_closure Traceback (most recent call last): File "", line 1, in ? TypeError: readonly attribute Closer inspection of the docs reveals that it is not writable after all. Therefore the only way I can see to do it without writing an extension is to generate some dummy function and copy the func_closure attribute from it. Luckily, you have already produced a factory for such a function: >>> f1(" there")\ 'hello there' >>> _f2 = wrap("howdy") >>> f1 = new.function(f1.func_code, f1.func_globals, f1.func_name, f1.func_defaults, _f2.func_closure) >>> f1(" there") 'howdy there' Mix-and-match functions! What will they think of next? -- Michael Hoffman From brettk at gmail.com Thu Jun 23 19:40:15 2005 From: brettk at gmail.com (brettk at gmail.com) Date: 23 Jun 2005 16:40:15 -0700 Subject: Listening for a Keypress (Console, not GUI) Message-ID: <1119570015.859996.231510@z14g2000cwz.googlegroups.com> Hello All, I've written a small daemon that monitors a pop3 mailbox and downloads any new messages. It's run from the console in windows, and instead of having it print something each time it gets a message or writes a file, i'd like to store those values as internal variables and print them to the screen whenever the user wants to see them. So, my question is, using a regular console, is there a way I can get python to listen for a specific keystroke? I'm using signal handling to deal with ^C, could I also do something like that? TIA From jan.danielsson at gmail.com Wed Jun 1 11:59:27 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Wed, 01 Jun 2005 17:59:27 +0200 Subject: Question about mutexes Message-ID: <429dda0a$1@griseus.its.uu.se> In OS/2 C, I would do this: main() { ... DosCreateMutexSem(NULL, &hmtx, 0UL, FALSE); ... } thread() { ... DosRequestMutexSem(hmtx); Locked! DosReleaseMutexSem(hmtx); ... } How would I go about doing that in Python? I figured this part out: lockobj = mutex() lockobj.lock(foo, "bar") Locked! lockobj.unlock() Now, what (and more importantly: WHY?!) - is foo and "bar" for? I have written a dummyfunction for foo which does nothing when called, but I fail to see the point of its existence. Could someone provide an example when this would be useful? From adsheehan at eircom.net Wed Jun 22 06:16:46 2005 From: adsheehan at eircom.net (adsheehan at eircom.net) Date: 22 Jun 2005 03:16:46 -0700 Subject: Urgent: Embedding Python question please Message-ID: <1119435406.050751.274600@g43g2000cwa.googlegroups.com> Hi, I am embedding Python into a multi-threaded C++ application runnig on Solaris and need urgent clarification on the embedding architecture and its correct usage (as I am experience weird behaviors). Can anyone clarify: - if Python correctly supports multiple sub-interpreters (Py_NewInterpreter) ? - if Python correctly supports multiple thread states per sub-interpreter (PyThreadState_New) ? and the "real" question: - what is the rationale for choosing one of: [a] one sub-interpreter with many thread states [b] many sub-interpreters with one thread state each [c] many sub-interpreters with many threas states each Thanks for helping Alan From theller at python.net Wed Jun 29 05:39:20 2005 From: theller at python.net (Thomas Heller) Date: Wed, 29 Jun 2005 11:39:20 +0200 Subject: COM problem .py versus .exe References: Message-ID: <64vxbiyf.fsf@python.net> "Tim Golden" writes: > [Greg Miller] > | Hello again, I put the executable on the "virgin" PC today. > | I am using > | the wmi(b) that you gave me. The error that I am receiving now is: > | > | File "autoStart.pyc", line 241, in test > | File "wmib.pyc", line 157, in ? > | File "win32com\client\__init__.pyc", line 73, in GetObject > | File "win32com\client\__init__.pyc", line 88, in Moniker > | com_error: (-2147221020, 'Invalid syntax', None, None) > | > | any thoughts on this error? Thanks again for the help. > > Well that's a real pain! Doesn't this look like the WMI service (or how it's called) is not installed? Thomas From correiajREMOVECAPS at hotmail.com Mon Jun 20 13:13:06 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Mon, 20 Jun 2005 17:13:06 GMT Subject: login website that using PHP References: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> Message-ID: "frost" wrote in message news:1119233498.837593.76450 at g47g2000cwa.googlegroups.com... > Hi, > > I am trying to login a website that using PHP and javascript. This is > what happend if you browse that website using IE, after you login, you > can go anywhere without enter your name and password again, as long as > you keep that IE open, but after you close that IE, then later on open > that website in a new window, you need to login again. I guess some > session is created as long as your original login window dose not > close. > > How I can handle this in python? I want get some information from that > website. But the login page is not what I want, how can I simulate > regular IE browser? I mean after I login, I can get to other pages from > it, but I find my programe can't go other place except the login page. > > Hope you could understand my question. Thank you very much! > Check here for some other examples, specifically 'Submitting values and clicking buttons in IE' http://tinyurl.com/7n7xf From gene.tani at gmail.com Mon Jun 6 23:23:58 2005 From: gene.tani at gmail.com (gene tani) Date: 6 Jun 2005 20:23:58 -0700 Subject: Pythonic Gotchas In-Reply-To: <1118019187.206625.96800@g49g2000cwa.googlegroups.com> References: <1118019187.206625.96800@g49g2000cwa.googlegroups.com> Message-ID: <1118114638.511770.245100@g49g2000cwa.googlegroups.com> or Norvig's IAQ: http://www.norvig.com/python-iaq.html From nephish at xit.net Sat Jun 11 10:54:02 2005 From: nephish at xit.net (nephish at xit.net) Date: 11 Jun 2005 07:54:02 -0700 Subject: cgi script runs under Opera, but not firefox In-Reply-To: References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> Message-ID: <1118501642.065924.83560@z14g2000cwz.googlegroups.com> Well, i don't have an app that will automaticlly check a page for errors, unless bluefish will do it, i am not sure. the page it is supposed to print out is a response to a form entry. here is the source from Opera if one of you guys want to look at it. Customer Data

Watkins Crop Consulting

1915 Cherokee
Dalhart, Tx 79022
333-5943

gandalf

Field field one
Crop crop one
GS growing, yep

Weeds many weeds
Water lots o water
Incects lots o insects

Remarks comment block, could be short, could be long, however will we know?


Field another field
Crop another crop
GS another growth stage

Weeds many many weeds
Water lots more water
Incects lots more insects

Remarks ok , short comment this time



this is all generated by the cgi module of python and the script that responds to the form. thanks. From noreply at gcgroup.net Tue Jun 28 17:54:31 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 28 Jun 2005 21:54:31 GMT Subject: tkinter radiobutton In-Reply-To: References: <1ygwe.532$Ox3.193@newssvr12.news.prodigy.com> Message-ID: p.s. I tweaked rbn = tk.Radiobutton(self, text=text, variable=var, value=y) to rbn = tk.Radiobutton(self, text=text, variable=var, value=y+1) and return tuple(row == var.get() for var in self.variables) to return tuple(row+1 == var.get() for var in self.variables) so that the Radiogrid doesn't initialize w/row 1 selected, and accomodates cases where nothing is selected in any column. Bill Peter Otten wrote: > William Gill wrote: > > >>I thought the problem was practical, not philosophical, but what do I >>know I'm the one asking for help. > > > What follows looks more like a spec than a question. > > >> columns can have 0 or 1 selection >> rows can have 0,1,2,3, or 4 selections. > > >>Loop through the 4 intVars 4 times; compare their value to the value for >>the row being processed; if they are the same bitor a value to a >>rowVariable i.e. convert the column information (intVar values) to row >>information. > > > Here's my implementation: > > import Tkinter as tk > > class Radiogrid(tk.Frame): > def __init__(self, master, columns, trace_write=None): > tk.Frame.__init__(self) > self.variables = [] > self.buttons = [] > for x, column in enumerate(columns): > var = tk.IntVar() > if trace_write: > var.trace_variable("w", trace_write) > self.variables.append(var) > self.buttons.append([]) > for y, text in enumerate(column): > rbn = tk.Radiobutton(self, text=text, variable=var, value=y) > rbn.grid(column=x, row=y) > self.buttons[-1].append(rbn) > def get_row_state(self, row): > return tuple(row == var.get() for var in self.variables) > > if __name__ == "__main__": > root = tk.Tk() > def show_state(*args): > for i in range(3): > print "row", i, rg.get_row_state(i) > print > rg = Radiogrid(root, > ["alpha beta gamma".split(), > "one two three".split(), > "guido van rossum".split()], > show_state > ) > rg.pack() > root.mainloop() > > I hope this will move further discussion from the abstract to the > concrete :-) > > Peter > From deepali at ti.com Wed Jun 1 00:43:35 2005 From: deepali at ti.com (Uppal, Deepali) Date: Wed, 1 Jun 2005 10:13:35 +0530 Subject: Beginner question: Python types Message-ID: Hello, I am facing a bit of a problem due to python implicitly attaching a type to an object. I will briefly tell you the problem that I am facing. I am trying to print the docstring of a test case in my pyUnit base test class. I accept the name of the test class as a command line option. So instead of printing the docstring of the test case, it prints the docString of a string object. I would like to give an example here import test_script gettatr( test_script.test_class.test_case, '__doc__') With this simple code, I am able to print the docstring of the test case. However, since I accept the test case information as a command line option. So instead of printing the docstring of the test case it prints the docstring of a string object. => 'str(object) -> string\n\nReturn a nice string representation of the object.\nIf the argument is a string, the return value is the same object.' Is there someway, I can tell the script to change the type of the object from string to an instancetype of a test case? I am quite a newbie in python so I would appreciate any help on this. Regards, Deepali -------------- next part -------------- An HTML attachment was scrubbed... URL: From richardlewis at fastmail.co.uk Thu Jun 2 09:44:37 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Thu, 02 Jun 2005 14:44:37 +0100 Subject: DOM question In-Reply-To: References: Message-ID: <1117719877.12098.235489419@webmail.messagingengine.com> On Thu, 02 Jun 2005 14:34:47 +0200, "Diez B. Roggisch" said: > > However, I got exactly the same problem: each time I use this function I > > just get a DOM Text node with a few white space (tabs and returns) in > > it. I guess this is the indentation in my source document? But why do I > > not get the propert element nodes? > > Welcome to the wonderful world of DOM, Where insignificant whitespace > becomes a first-class citizen! > > Use XPath. Really. It's well worth the effort, as it is suited for > exactly > the tasks you presented us, and allows for a concise formulation of > these. > Yours would be (untested) > > //section[id==$id_param]/node()[!name() == section] > > Yes, in fact: //section[@id=$id_param]//*[name()!='section'] would do the trick. I was trying to avoid using anything not in the standard Python distribution if I could help it; I need to be able to use my code on Linux, OS X and Windows. The xml.path package is from PyXML, yes? I'll just have to battle with installing PyXML on OS X ;-) Cheers, Richard From roccomoretti at hotpop.com Wed Jun 22 13:34:21 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 22 Jun 2005 12:34:21 -0500 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: <42b99d7b$0$21804$626a14ce@news.free.fr> References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: scott wrote: > hi people, > > can someone tell me, how to use a class like that* (or "simulate" more > than 1 constructor) : > #-- > class myPointClass: > def __init__(self, x=0, y=0): > self.x = x > self.y = y > def __init__(self, x=0, y=0, z=0): > self.__init__(self, x, y) > self.z = z > #-- > You might try: #-- class myPointClass: def __init__(self, x=0, y=0, z=None): self.x = x self.y = y if z is not None: self.z = z #-- You could also turn __init__ into a dispatch fuction: #-- class myPointClass: def __init__(self, *args): if len(args) <= 2: self.__init_two(*args) if len(args) == 3: self.__init_three(*args) def __init_two(self, x=0, y=0): self.x = x self.y = y def __init_three(self, x=0, y=0, z=0): self.__init_two(x, y) self.z = z #-- But I would definitely recommend looking at your algorithm to determine if there is a better way to do what you want, that doesn't require an initilizer with two different signatures. From poisondart985 at gmail.com Thu Jun 9 20:48:30 2005 From: poisondart985 at gmail.com (poisondart) Date: 9 Jun 2005 17:48:30 -0700 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> Message-ID: <1118364510.834874.75930@g44g2000cwa.googlegroups.com> 1. You seem to ignore the fact that volunteer teachers exist. 2. I aspire to not repeat history. Esp. history that I don't completely agree with... The description I supplied for the license I had in mind was not ready for your scrutiny, but as somebody else said licensing is less trivial than we would like it to be. In practice, the GPL would probably be the closest to what I'd want, but the problem is that I don't agree with the practice. Why? because it's not tailored to how I want to release my software. This discussion has gone far out of my interest. Thank you all you've made me realize the complexity and breadth of the issue. I'm just going to keep coding and re-think cautiously the future of my software. From kent37 at tds.net Tue Jun 7 20:44:43 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 20:44:43 -0400 Subject: Trouble Encoding In-Reply-To: <11ac4kiih8srf4c@news.supernews.com> References: <1118135690.961381.207490@o13g2000cwo.googlegroups.com> <11ac4kiih8srf4c@news.supernews.com> Message-ID: <42a63f2c$1_1@newspeer2.tds.net> John Roth wrote: > wrote in message > news:1118135690.961381.207490 at o13g2000cwo.googlegroups.com... > >> I'm using feedparser to parse the following: >> >>
Adv: Termite Inspections! Jenny Moyer welcomes >> you to her HomeFinderResource.com TM A "MUST See &hellip;
>> >> I'm receiveing the following error when i try to print the feedparser >> parsing of the above text: >> >> UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in >> position 86: ordinal not in range(256) >> >> Why is this happening and where does the problem lie? > > > Several different things are going on here. First, when you try to > print a unicode string using str() or a similar function, Python is > going to > use the default encoding to render it. The default encoding is usually > ASCII-7. Why it's trying to use Latin-1 in this case is somewhat > of a mystery. Actually I believe it will use sys.stdout.encoding for this, which is presumably latin-1 on fingermark's machine. Kent From bvande at po-box.mcgill.ca Sat Jun 25 02:17:51 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 25 Jun 2005 02:17:51 -0400 Subject: How does one write a function that increments a number? In-Reply-To: <1119678060.774799.244920@g43g2000cwa.googlegroups.com> References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> <1119676986.613202.315140@g47g2000cwa.googlegroups.com> <1119678060.774799.244920@g43g2000cwa.googlegroups.com> Message-ID: <42BCF70F.4090907@po-box.mcgill.ca> anonymousnerd at gmail.com said unto the world upon 25/06/2005 01:41: > Wait... so this means it is impossible to write a function that > increments an integer without turning the integer into a list? > Well, one of these options will probably suit: >>> def increment_counter(data): ... data += 1 ... return data ... >>> counter = 0 >>> counter = increment_counter(counter) >>> counter 1 Or, if you only care about one counter, don't like the return/assignment form, and don't mind all the cool kids frowning on the use of global: >>> counter = 0 >>> def increment_counter(): ... global counter ... counter += 1 ... >>> counter 0 >>> increment_counter() >>> counter 1 >>> Nicest might be using a class, where you keep a clean namespace, and don't have the return/assignment form: >>> class My_class(object): ... def __init__(self): ... self.counter = 0 ... def increment_counter(self): ... self.counter += 1 ... >>> my_object = My_class() >>> my_object.counter 0 >>> my_object.increment_counter() >>> my_object.counter 1 >>> This also lets you have multiple independent counters: >>> my_other_object = My_class() >>> my_other_object.counter 0 >>> my_other_object.increment_counter() >>> my_other_object.increment_counter() >>> my_other_object.counter 2 >>> my_object.counter 1 >>> Best, Brian vdB From noreply at gcgroup.net Thu Jun 16 10:25:20 2005 From: noreply at gcgroup.net (William Gill) Date: Thu, 16 Jun 2005 14:25:20 GMT Subject: access properties of parent widget in Tkinter In-Reply-To: <42b17114$1_2@newspeer2.tds.net> References: <42b17114$1_2@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > William Gill wrote: > >> I am trying to get & set the properties of a widget's parent widget. >> What I have works, but seems like a long way around the block. First >> I get the widget name using w.winfo_parent(), then i convert the name >> to a reference using nametowidget(). >> >> self.nametowidget(event.widget.winfo_parent()).hasChanged= True > > > Personally I think it is bad design for a widget to assume anything > about its enclosing environment. What about passing a StringVar or > IntVar to the child widget and letting it work with that? > > Kent Maybe I should clarify what I am doing and why, so that I can get a better understanding of your replies. The overall app is a gui editor for a database made up of several related tables; one for basic info, one for their various phone numbers (publish, contact, fax,cell, etc), one for various addresses (publish ,ship to, mail to, etc.), one for the services they subscribe to, etc. The editor brings records from each of the various tables together in one ?record? for editing. Each table has an associated python/tkinter class (widget) that displays the fields in a parent widget, and each field is a child of the table widget. So ?city? is a child of address, is a child of client. If I change or add a phone number that db table will need updating when I?m done, but the address table may not. I have designed each table class with a hasChanged attribute, initialized to False, if a child Entry widget changes I set has changed to True. When I?m done the exit routine runs each table objects save routine, which checks hasChanged to see if an update query needs to be run on that table. Client - basicData object (data from client table) - company - contact person - notes - phones object (data from phonenumber table) - type (cell, fax, publish, etc) - areaCode - exchange - base If I change the area code in one record only the phonenumber table needs to be updated, but since areaCode is a child of phones, phones.hasChanged needs to be set to True by the areaCode entry widget. > Personally I think it is bad design for a widget to assume anything > about its enclosing environment. What about passing a StringVar or > IntVar to the child widget and letting it work with that? This is not a criticism, but how is passing a known intVar or stringVar any different than designing with the knowledge that an areaCode widget can not exist except as a child of phonenumber? Besides, I need to pass the state of areaCode (has it changed or not), not its value? Bill From peter at engcorp.com Wed Jun 22 13:05:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Jun 2005 13:05:10 -0400 Subject: PEP ? os.listdir enhancement In-Reply-To: References: Message-ID: Riccardo Galli wrote: > I noticed that when I use os.listdir I need to work with absolute paths > 90% of times. > While I can use a for cycle, I'd prefere to use a list comprehension, > but it becomes too long. > > ### e.g. 1 part 1 - getting a list of directories ### > dirs=[] > for i in os.listdir(path): > tmp_path=os.path.join(path,i) > if os.path.isdir(tmp_path): > dirs.append(tmp_path) > > ### e.g. 1 part 2 ### > dirs=[join(path,x) for x in listdir(path) if isdir(join(path,x))] Using Jason Orendorff's "path" module, all this code basically collapses down to this beauty (with your variable "path" renamed to myPath to avoid a name collision): from path import path dirs = path(myPath).abspath().dirs() -Peter From curtin at computer.org Wed Jun 1 20:27:07 2005 From: curtin at computer.org (curtin) Date: 1 Jun 2005 17:27:07 -0700 Subject: prob with ActiveState and FireFox on Win32 (XP and W2K) Message-ID: <1117672027.924838.245780@g47g2000cwa.googlegroups.com> hi, i just downloaded the latest version of ActiveState's IDE (pywin 2.4.X) and have noticed that i can't have firefox/ActiveState open at the same time. if i try to create a 'new' script, the AS IDE blocks till i tear down firefox. this is on an XP and W2K box. i did some digging on ActiveState's site, and googled but no luck. anyone see this before? thanks, craig From joel at rosdahl.net Thu Jun 23 03:30:16 2005 From: joel at rosdahl.net (Joel Rosdahl) Date: Thu, 23 Jun 2005 09:30:16 +0200 Subject: Database recommendations for Windows app In-Reply-To: (Dave Cook's message of "Wed, 22 Jun 2005 15:50:03 GMT") References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: <877jgl7con.fsf@fluff.rosdahl.net> Dave Cook writes: > On 2005-06-22, Will McGugan wrote: > > [...] >> Can anyone recommend a database that runs on Windows, is fast / >> efficient and can be shipped without restrictions or extra >> downloads? > > http://pysqlite.org Or APSW . -- Joel Rosdahl Key BB845E97; fingerprint 9F4B D780 6EF4 5700 778D 8B22 0064 F9FF BB84 5E97 From nospam at nospam.nospam Thu Jun 30 04:30:11 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Thu, 30 Jun 2005 01:30:11 -0700 Subject: Acceptance test spike example References: Message-ID: <44b7c11mbrrk3nllr5psb8cl9bqfj6ni02@4ax.com> On Sun, 26 Jun 2005 16:10:05 -0700, Steve Jorgensen wrote: >I'm posting this message for 2 reasons. > >First, I'm still pretty new and shakey to the whole Acceptance Testing thing, >and I'm hoping for some feedback on whether I'm on the right track. Second, >although all the Agile literature talks about the importance of doing >Acceptance Testing, there's very little in any of the books or out on the Web >that helps with how to do it. If I am on the right track, this will be one >more helpful item folks can find on a Google search. > >The code below is basically a spike I wrote in a few hours last night to prove >to myself and my team that it would be feasible to quickly create a simple, >useful Acceptance Testing harness for our learning project. ... Here's an updated script and code to process the script. I made the script syntax more friendly. New example script... ========== Check recipeListCount is 0 Do new Check name is "New Recipe" Keyin "PB&J" to name Ch eck name is "PB&J" Do save Do close Check recipeListCount is 1 Do goToListItem 1 Do openListItem Check name is "PB&J" ========== New Python code for test runner including skeleton of application model that can be tested, but can't pass the tests... ========== import string class RecipeOrgModel: recipeListCount = 0 name = "New Recipe" def new(self): pass def save(self): pass def close(self): pass def goToListItem(self,itemNum): pass def openListItem(self): pass class Action: failMessage = "" def __init__(self, actionArgs): pass def tryAction(self, model): return True class NoAction (Action): pass class ActionDo (Action): item = "" args = "" def __init__(self, actionArgs): delimPos = string.find(actionArgs, " ") self.args = "" if delimPos==-1: self.item = actionArgs else: self.item = actionArgs[0:delimPos] self.args = string.strip(actionArgs[delimPos+1:]) def tryAction(self, model): methodCall = "model." + self.item +"(" + self.args + ")" exec(methodCall) return True class ActionKeyin (Action): item = "" value = "" def __init__(self, actionArgs): delimPos = string.find(actionArgs, " to ") self.args = "" if delimPos==-1: self.item = actionArgs else: self.value = eval( actionArgs[0:delimPos] ) self.item = string.strip(actionArgs[delimPos+len(" to "):]) def tryAction(self, model): setattr(model, self.item, self.value) return True class ActionCheck (Action): item = "" expectValue = "" def __init__(self, actionArgs): delimPos = string.find(actionArgs, " is ") self.args = "" if delimPos==-1: self.item = actionArgs else: self.item = actionArgs[0:delimPos] self.expectValue = eval( string.strip(actionArgs[delimPos+len(" is "):]) ) def tryAction(self, model): valueIs = getattr(model, self.item) if self.expectValue == valueIs: return True else: self.failMessage = ( "Expected " + str(self.expectValue) + " but got " + str(valueIs) ) return False class ActionUnknown (Action): actionArgs = "" def __init__(self, actionArgs): self.actionArgs = actionArgs def tryAction(self, model): self.failMessage = "Test statement not understood: " + self.actionArgs return False def MakeTestAction(lineText): delimPos = string.find(lineText, " ") commandArgs = "" if delimPos==-1: commandType = lineText else: commandType = lineText[0:delimPos] commandArgs = string.strip(lineText[delimPos+1:]) if commandType == "Do": return ActionDo(commandArgs) elif commandType == "Keyin": return ActionKeyin(commandArgs) elif commandType == "Check": return ActionCheck(commandArgs) elif commandType == "": return NoAction(commandArgs) else: return ActionUnknown(commandType + " " + commandArgs) class TestSession: fileName="" lines = None model = RecipeOrgModel() def __init__(self,fileName): self.fileName = fileName def run(self): self.loadLines(self.fileName) for line in self.lines: print(line) action = MakeTestAction(line) actionOk = action.tryAction(self.model) if not actionOk: print(" !!! " + action.failMessage) break def loadLines(self, fileName): file = open(fileName) lines = file.readlines() file.close lines = map(string.strip,lines) self.lines = lines session = TestSession("test1.txt") session.run() ========== Ouptut of test runner using example script... ========== Check recipeListCount is 0 Do new Check name is "New Recipe" Keyin "PB&J" to name Check name is "PB&J" Do save Do close Check recipeListCount is 1 !!! Expected 1 but got 0 ========== From bretthoerner at gmail.com Mon Jun 27 23:33:35 2005 From: bretthoerner at gmail.com (Brett Hoerner) Date: 27 Jun 2005 20:33:35 -0700 Subject: Better console for Windows? In-Reply-To: References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: <1119929615.053863.261260@f14g2000cwb.googlegroups.com> Benji York wrote: > To make the console full screen hit Alt-Enter. The same thing makes it > windowed again. To accommodate very long lines click the "C:\" icon in > the upper left corner of the window, choose "Properties" and then change > the "Screen Buffer Size" Width and Height to something more to your liking. > > While you're there I'd recommend turning on "QuickEdit Mode" on the > "Options" tab. Then you can drag with your left mouse button to select > an area of text, right click to copy, then right click again to paste. Thanks very much, not sure why I always missed those. I guess I was just frustrated in general. This will make python a lot more enjoyable. Brett From d at e.f Fri Jun 24 16:51:05 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 15:51:05 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <8-2dnaeqFsai7yHfRVn-iA@comcast.com> Terry Reedy wrote: > "D H" wrote in message > > >>Roy Smith wrote: > > >>>Tom Anderson wrote: >>> >>>>The one thing i really do miss is method overloading by parameter >>>>type. I used this all the time in java > > >>>You do things like that in type-bondage languages like Java and C++ >>>because you have to. Can you give an example of where you miss it in >>>Python? >> >>Well it's coming to a future Python version, > > > The 'it' under discussion is 'method overloading by parameter type'. While > a few people have requested it, I have seen no indication that 'it' is > coming. Did you not see the very next sentence I wrote which exactly clarified my point that I was referring to type checking and not method overloading? Way to quote me out of context. Type checking IS coming to python in all likelihood -> >>I don't know if you'll have method overloading, but there will be type >>checking. >>"Type checking is going to slow down your code." -GVR 2005 keynote, >>http://www.sauria.com/%7Etwl/conferences/pycon2005/20050324/The%20State%20of%20Python.html > > > You left out " NOTE: Nothing's settled yet!!!!!!!!!!!!!!!!" and " > Reminder and Disclaimer > Nothing's settled yet!!!!! I also left out the dozens of angry rants that people wrote after Guido first proposed static typing, leading him to change the proposal to runtime type checking, which by definition will slow down the code. Static typing is almost certainly not going to come to Python, but the typing annotations ("def method(x : int) -> bool") can be used by other tools perhaps to do optimizations at compile time. From hancock at anansispaceworks.com Thu Jun 30 21:05:28 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 30 Jun 2005 20:05:28 -0500 Subject: map vs. list-comprehension In-Reply-To: <42c4068c$0$21964$afc38c87@news.optusnet.com.au> References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: <200506302005.28067.hancock@anansispaceworks.com> On Thursday 30 June 2005 09:49 am, Mike P. wrote: > That really sucks, I wasn't aware of these plans. Ok, I don't use reduce > much, but I use lambda, map and filter all the time. > [...] > Also, I don't necessarily think list comprehensions are necessarily easier > to read. I don't use them all that much to be honest. Actually, I prefer list comprehension syntax, after having a chance to experience both, both as a writer and a reader of other people's code. So I disagree with this particular issue. > IMHO I'm not particularly happy with the way Python is going language wise. > I mean, I don't think I'll ever use decorators, for example. Personally, in > terms of language features and capabilities I think the language is fine. > Not much (if anything needs to be added). This though, I mostly agree with. I'm not sure if I'll ever find use for decorators, but the "@" signs bother me, I must admit. I liked the fact that there was a way to do this without fiddling with the language syntax. > I think at this stage the Python community and Python programmers would be > better served by building a better, more standardised, cross platform, more > robust, better documented, and more extensive standard library. I would be > happy to contribute in this regard, rather than having debates about the > addition and removal of language features which don't improve my > productivity. Now this, I agree with wholeheartedly! The library is where the real work ought to be happening. Either that, or previous suggestions about making access to external packages should be improved and the "batteries included" focus should be sidelined. One of the strengths of Python has been that the language itself is small (which it shares with C and (if I understand correctly, not being a lisp programmer?) Lisp), but with all the syntax enhancements going on, Python is getting pretty complicated. I have to wonder if new users won't begin to find it just as intimidating as Perl or other big languages. I know something like that happened with HTML. When I learned it, HTML was very simple (version 1? I think or maybe 2?). Later extensions in 3.2 and 4.0 didn't bother me, because they were incremental increases over what I already knew. But new users are finding HTML much more daunting, which encourages them to reach for WYSIWYG tools and the like, rather than just coding it. So my former experience of HTML as "dead simple" seems to have been undermined by the later developments. It still seems "dead simple" to me, but new users don't seem to have the reaction that I did. I strongly doubt this is because "new users are wimpier than we were". Likewise, part of the thing that attracted me to Python and which I still consider a "selling point" is that it is not only easy for me to use, but easy for potential collaborators to learn. Since the projects I am most interested in are free-software projects primarily interesting to non-programmers or semi-skilled programmers, the need to make the code as easy for them to understand as possible is important to me. I want to actually encourage users to *become* programmers to work on my projects, not just interest existing programmers. Before I encountered Python, that didn't seem possible. But I was really impressed with how easy Python was to learn (that is, Python 1.5.9). Even 2.1 was pretty easy, and I acknowledge the benefits of list comps and the like, even though I also see that they can be abused. Now, though, I'm starting to wonder if that newfound advantage is disappearing. Frankly, I feel like slamming on the brakes. Simplicity is really, really good, and we shouldn't forget that in our zeal to make Python "a better systems programming language". ISTM that it's already pretty good at those tasks, and if it's a little harder to do a few things, maybe that's the cost of keeping most things easy. In any case, the Python object model is very flexible, and most things you want to do can be done using it. So it seems to me like compartmentalizing changes by keeping them in modules would be really good. I guess I've become a python conservative. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From noreply at gcgroup.net Sat Jun 25 15:34:50 2005 From: noreply at gcgroup.net (William Gill) Date: Sat, 25 Jun 2005 19:34:50 GMT Subject: tkinter radiobutton Message-ID: I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep references to them in a 2 dimensional list ( rBtns[r][c] ). It works fine, and I can even make it so only one button per column can be selected, by assigning each column to an intVar. In many languages a radiobutton has a property that can be directly read to see if it is selected on unselected. Tkinter radiobuttons don't seem to have any such property. Is there any way to look (via the script not the screen) to determine if it is selected?, or can this only be achieved via control variables? Bill From steve at holdenweb.com Thu Jun 16 15:16:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Jun 2005 15:16:46 -0400 Subject: dir() with string as argument In-Reply-To: <47d5f088340cd.42b193c4@Princeton.EDU> References: <47d5f088340cd.42b193c4@Princeton.EDU> Message-ID: Shankar Iyer (siyer at Princeton.EDU) wrote: > Hi, > > Suppose I have a string, sModuleName, that contains the name of a module. I now want to see what functions are in that module, but if I call dir(sModuleName), I instead get the list of operations that can be done on a string. Is there any way to convert the string into a format that I could feed to dir to cause the desired effect? I think I could modify the string a bit and then use the exec command, but I was advised against that on this board last week. > > Shankar > The __import__() builtin function takes a module name and returns the imported module as a value. >>> m = __import__("bsddb") >>> m >>> dir(m) ['UserDict', '_DBWithCursor', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '__version__', '_bsddb', '_checkflag', '_db', '_iter_mixin', '_openDBEnv', 'btopen', 'db', 'error', 'hashopen', 'os', 'ref', 'rnopen', 'sys'] >>> regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From jmeile at hotmail.com Sat Jun 25 07:07:59 2005 From: jmeile at hotmail.com (Josef Meile) Date: Sat, 25 Jun 2005 13:07:59 +0200 Subject: Office COM automatisation - calling python from VBA In-Reply-To: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <42BD3B0F.9030802@hotmail.com> Hi guy, > I'll be using COM, and I could probably make an application that > controls Outlook (externally). But I'd also like to have this > functionality exposed in OL itself. So I guess I'll need to use VBA, > but I don't really like VBA - relax, please, it's just an opinion.. ;) > > So, ideally, I'd like to program as much as possible in python (I'm > pretty new to that, too, btw), and only use VBA if needed - say, to > call python objects/methods (+ wxGUI, please). You could try to do an addin/addon for Word, Excel, and Outlook. You don't need to code with VBA. Here you just need a language from where you can access the microsoft interop assemblies (ie: C++ or C#; IronPython maybe?) I'm now working in an addon for Visio, but I'm not using python. I'm using C#. The main idea is that we have an exe application, which creates a COM object, with the first running instance of visio (if some is found). Then, I use a class (event handler) to catch some events comming from visio (this is in part documented at the msdn). I even embebbed a windows form in Visio (it was an example in the sdk). So, I think in theory, you could do the same with python. I have heard you can somehow create COM objects there. You could also try the new version of python for net: IronPython. I guess you can from there access all the assemblies to interact with office: Microsoft.Office.Interop.Excel, Microsoft.Office.Interop.Word, and Microsoft.Office.Interop.Outlook A good start is to see the SDK documentation of each office product you need at each developer center in www.msdn.microsoft.com Good luck, Josef From tom at dtsam.com Mon Jun 6 11:23:19 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Mon, 6 Jun 2005 10:23:19 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: "bruno modulix" wrote in message news:42a3fc70$0$30762$626a14ce at news.free.fr... > You mean the "wimp gui builder + db -> ui pipeline" model ? If yes, C > doesn't have it, C++ doesn't have it (in fact most languages doesn't > have it) - and .... > .... the fact is that C and C++ are usually considered as much > more "serious and professionnal" than VB and the likes. Yes but there is another fact that must be considered. Systems like VB (and the likes) are much more *productive* . The secret of that particular success has nothing to do with the language and everything to do with the integrated GUI / IDE available to that particular (VB) language. Anything that reduces the overhead involved in producing a consistent/attractive/idiot proof user interface makes a far more productive environment. Thomas Bartkus From scrimp212 at yahoo.com Thu Jun 2 17:40:43 2005 From: scrimp212 at yahoo.com (scrimp) Date: 2 Jun 2005 14:40:43 -0700 Subject: saving .zip or .txt email attachments instead of deleting them In-Reply-To: <119utnt1mvdue50@news.supernews.com> References: <1117746435.769666.186810@z14g2000cwz.googlegroups.com> <119utnt1mvdue50@news.supernews.com> Message-ID: <1117748443.644449.30170@g43g2000cwa.googlegroups.com> Im using the winpython IDE to run that script for the unpacking the email. The usage says unpackmail [options] msgfile. I type unpackmail -d filename and it gives me a syntax error. What modifications did u do to that module to make it work? From david.bear at asu.edu Mon Jun 20 17:20:21 2005 From: david.bear at asu.edu (David Bear) Date: Mon, 20 Jun 2005 14:20:21 -0700 Subject: reading a list from a file Message-ID: <223874235.UzX6FoQtyG@teancum> I have a file that contains lists -- python lists. sadly, these are not pickled. These are lists that were made using a simple print list statement. Is there an easy way to read this file into a list again? I'm thinking I would have to read until char = '[' read until char = " ' " Well, reading character by char until I have the list and then parse it all myself. I was hoping there was a pythonic way of doing this.. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From Scott.Daniels at Acm.Org Tue Jun 28 21:07:16 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 28 Jun 2005 18:07:16 -0700 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <86y88um4y3.fsf@bhuda.mired.org> Message-ID: <42c1ecaf$1@nntp0.pdx.net> Ron Adam wrote: > Mike Meyer wrote: > >> Riccardo Galli writes: >>> result = [value2,value1][cond] Or: result = [(lambda: expr0), lambda: expr1][cond]() Which is harder to understand than the if-based assignment even with 5-character expressions. --Scott David Daniels Scott.Daniels at Acm.Org From dalke at dalkescientific.com Wed Jun 15 23:59:05 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 16 Jun 2005 03:59:05 GMT Subject: What is different with Python ? References: Message-ID: Terry Hancock wrote: > Of course, since children are vastly better at learning > than adults, perhaps adults are stupid to do this. ;-) Take learning a language. I'm learning Swedish. I'll never have a native accent and 6 year olds know more of the language than I do. But I make much more complicated sentences than 6 year olds. (Doesn't mean they are grammatically correct, but I can get my point across given a lot of time.) > Quantum mechanics notwithstanding, I'm not sure there > is a "bottom" "most-reduced" level of understanding. It's > certainly not clear that it is relevant to programming. I agree. That's why I make this thread branch. I think learning is often best taught from extending what you know and not from some sort of top/bottom approach. I'm also one who bristles at hierarchies. Maybe that's why I like Python and duck typing. :) Some learning works by throwing yourself in the deep end. Languages are sometimes learned that way. The Suzuki method extends that to music, though that's meant for kids. > Python is actually remarkably good at solving things in a > nearly optimal way. Have you read Richard Gabriel's "Worse is Better" essay? http://www.dreamsongs.com/WIB.html Section "2.2.4 Totally Inappropriate Data Structures" relates how knowing the data structure for Lisp affects the performance and seems relevant to your point. Andrew dalke at dalkescientific.com From snobis at gmx.de Sat Jun 11 10:42:02 2005 From: snobis at gmx.de (Stefan Nobis) Date: Sat, 11 Jun 2005 16:42:02 +0200 Subject: Best Web dev language References: <11al0nhr4opfgaa@corp.supernews.com> Message-ID: <877jh1ez0l.fsf@snobis.de> "Jon Slaughter" writes: > Does anyone know of any detailed and objective comparisons > between the major languages(perl, php, java, javascript, etc...) > that might help me get a clearer picture? I don't know of any (really good) comparisions, but anyway here are my opinion: Don't look only at something someone calls "major language". The not-so-well-known one may offer you quite some nice extras. If you have to deal with medium to complex application give continuation based approches (Seaside (Smalltalk), PLT/Scheme, Cocoon (Java), UncommonWeb (Common Lisp) and others; to get an idea look at http://lisp.tech.coop/Web/Continuation ). What language do i seem interesting to look at for web development? Hmmm... let's see (listing in random order): - Common Lisp (my personal favorite) - Scheme (PLT/Scheme, Bigloo,...) - Scala (http://scala.epfl.ch/) - Nice (http://nice.sourceforge.net/) - Squeak (http://www.squeak.org/index.html) - Python Scala and Nice compiles to Java-Bytecode and you have access to the complete Java-World (AFAIK there are such JVM-Compilers for Common Lisp and some Scheme, too and there is JPython). I don't like Perl syntax much, so it's not on the list, and PHP is a rather chaotic language with (personal view!) at least a couple of new security issues eacht month, so it's the worst choice one can make (i think). Hope that helps a little bit. -- Stefan. From desertgarden at netscape.com Mon Jun 27 16:28:24 2005 From: desertgarden at netscape.com (Brian) Date: Mon, 27 Jun 2005 20:28:24 GMT Subject: Boss wants me to program In-Reply-To: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: Hi Xeys, Even though I absolutely love Python... Microsoft Visual Basic (.NET) would be your best bet for this type of software development. It allows you to create GUI apps that can work with a variety of database options, such as Access or MS SQL Server. My personal opinion is this: ---------------------------- 1) Python shines the best on the server realm. 2) VB.net shines the best on the client-computer realm. Brian --- xeys_00 at yahoo.com wrote: > I'm a manager where I work(one of the cogs in a food service company). > The boss needed one of us to become the "tech guy", and part of that is > writing small windows programs for the office. He wants the development > work done in house, and he knows I am in school for a CS minor. I know > basic C++(Part 2 of that is in the fall), and I will be taking Java 1 > in the fall also. What is the easiest way for me to make windows > programs that will do basic things like(Inventory, Menu Management, > etc...)? I have heard visual basic is where it's at. I want to keep an > open mind though, so I am wondering if python could be an option. The > programs have > no speed requirement. But they must be pretty, and not confuse my > boss. Plus he wants well documented help for each function. I asked the > windows programming group, but I thought I would ask here also. Thanks. > > Xeys > From tim.golden at viacom-outdoor.co.uk Tue Jun 14 09:54:11 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 14 Jun 2005 14:54:11 +0100 Subject: Single Application Instance Example Message-ID: <9A28C052FF32734DACB0A288A3533991EBB8D3@vogbs009.gb.vo.local> [Chris Lambacher] | Does anyone know of an example of how to make a Python program only | run a single instance. I am specifically looking for examples for | win32. | | I think I should be able to do this with win32all but the method is | not obvious. Preferably I would like to be able to get a handle to | the already running instance so that I can push it to the foreground | as well. You could Google around through the archives of this group and find some previous discussions, for greater detail, but the standard approach (within the Python world and without) seems to be to use the Mutexes exposed by the win32event module. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kent37 at tds.net Fri Jun 17 14:42:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 14:42:51 -0400 Subject: Shortcut to initialize variables In-Reply-To: <1119032651.912256.319140@o13g2000cwo.googlegroups.com> References: <1119032651.912256.319140@o13g2000cwo.googlegroups.com> Message-ID: <42b31929$1_2@newspeer2.tds.net> Andrew wrote: > Newb here... For one of my programs I want to initialize a variable for > each letter of the alphabet. For example, a,b,c = 0,0,0. I don't think > this works, but I'm wondering if I can do something similar to this: > > from string import ascii_lowercase > > class Blah: > def __init__(self): > for letter in ascii_lowercase: > setattr(self,letter,0) > > Is there a way I can do something like this without using classes? This is a very common request on this list. The usual advice is to use a dictionary rather than defining variables, e.g. letters = {} for letter in ascii_lowercase: letters[letter] = 0 But I'm becoming curious about why this is so commonly requested. What is your background that you (and others) would think of this as a solution? Is there a language where it is easy to do this sort of thing, and where the resulting variables are easily used? Thanks, Kent From usenet.20.evilspam at spamgourmet.com Mon Jun 13 01:14:11 2005 From: usenet.20.evilspam at spamgourmet.com (Chris Spencer) Date: Mon, 13 Jun 2005 05:14:11 GMT Subject: searching for IDE In-Reply-To: <1118603810.369228.74520@g49g2000cwa.googlegroups.com> References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> <1118603810.369228.74520@g49g2000cwa.googlegroups.com> Message-ID: jean-marc wrote: > if you are familiar with eclipse, you could use the PyDev python > plugin. > > jm Thanks for that reference. I had been using SPE for my Python editing, but it's gone unmaintained as of late, so I've been looking for an alternative. Aside from an autocomplete bug (which I've reported) Pydev's been working great for me. Chris From bvande at po-box.mcgill.ca Sun Jun 26 05:00:09 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun, 26 Jun 2005 05:00:09 -0400 Subject: [offtopic] Re: Set of Dictionary In-Reply-To: References: <4660fe3005061608023c4f96ab@mail.gmail.com> <20050616160959.34219.qmail@web53910.mail.yahoo.com> Message-ID: <42BE6E99.60302@po-box.mcgill.ca> James Dennett said unto the world upon 26/06/2005 03:51: > Steven D'Aprano wrote: > > >>On Thu, 16 Jun 2005 21:21:50 +0300, Konstantin Veretennicov wrote: >> >> >> >>>On 6/16/05, Vibha Tripathi wrote: >>> >>> >>>>I need sets as sets in mathematics: >>> >>>That's tough. First of all, mathematical sets can be infinite. It's >>>just too much memory :) >>>Software implementations can't fully match mathematical abstractions. >> >> >>:-) >> >>But lists can be as long as you like, if you have enough memory. > > > But you never have enough memory to store, for example, > a list of all the prime integers (not using a regular list, > anyway). An even better example is the set of reals in the interval (0, 1). Even an idealized Turing machine with (countably) infinite memory will choke on that :-) >>Standard Set Theory disallows various constructions, otherwise you get >>paradoxes. >> >>For example, Russell's Paradox: the set S of all sets that are not an >>element of themselves. Then S should be a set. If S is an element of >>itself, then it belongs in set S. But if it is in set S, then it is an >>element of itself and it is not an element of S. Contradiction. >> >>The price mathematicians pay to avoid paradoxes like that is that some >>sets do not exist. For instance, there exists no universal set (the set >>of all sets), no set of all cardinal numbers, etc. >> >>So even in mathematics, it is not true that sets can contain anything. > > > See "Set Theory With a Universal Set" by T. Forster, which covers > some set theories in which there *is* a set of all things, and > in which Russell's paradox is avoided in other ways (such as by > restricting the comprehension axioms). > > (Sorry for drifting offtopic, I happen to find non-standard > set theories interesting and thought that some others here > might too.) > > -- James So do I :-) Do you know of non-well-founded set theory (non-standard set theory which allows sets A, such that A is in A)? Not really on point for any of the above, but being on topic is in the rear view mirror, anyway :-) Best, Brian vdB From peter at engcorp.com Tue Jun 28 14:43:03 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Jun 2005 14:43:03 -0400 Subject: benchmarking with threading module In-Reply-To: <1119966502.076081.242340@g44g2000cwa.googlegroups.com> References: <1119966502.076081.242340@g44g2000cwa.googlegroups.com> Message-ID: <342dnULzuo7bB1zfRVn-pg@powergate.ca> Matteo Memelli wrote: > Hi, I'd like to know if it is possible to use the threading module to > benchmark a web server. > Do you think that using the Threading module would be a good idea? > Any other suggestion? This sounds like a good time to use Twisted instead of "threading". -Peter From tgflynn at stny.rr.com Wed Jun 1 22:58:31 2005 From: tgflynn at stny.rr.com (Tim Flynn) Date: Thu, 02 Jun 2005 02:58:31 GMT Subject: viewing generated images Message-ID: Hi, I'm trying to write a simple image viewer using Tkinter and ImageTk from the PIL toolkit. The images are stored in memory and I don't want to create temporary files for them. My code looks like this : from Tkinter import * import Image import ImageTk class Viewer(Frame): def __init__( self, master=None ): Frame.__init__( self, master ) self.grid() self.createWidgets() def createWidgets(self): self.image_size = (50,50) self.pilim = Image.new( "1", self.image_size ) # Generate a blank image f = lambda(x): 0 Image.eval( self.pilim, f ) self.bmi = ImageTk.BitmapImage( image = self.pilim, foreground = 'black' ) self.canvas = Canvas( width=100, height = 100, bg = 'white' ) self.quitButton = Button( self, text="Quit", command=self.quit ) self.quitButton.grid() self.canvas.grid() im_id = self.canvas.create_bitmap( 0, 0, anchor = 'nw', bitmap = self.bmi ) viewer = Viewer() viewer.master.title("Test viewer") viewer.mainloop() The create_bitmap call fails with the following error : _tkinter.TclError: bitmap "pyimage2" not defined I've seen a couple of mentions of this problem but with no solution given other than to write the image to a temporary file, which I don't want to do. I'd appreciate it if anyone could point me to a different approach for this that works (and doesn't involve creating temporary files). I'd be open to trying a different GUI/imaging package if anyone has suggestions for one that would be better suited to this sort of application. Otherwise I'm also interested if anyone has any ideas about the root cause of this problem because if I don't find some work around I intend to try to fix it in Tkinter. Thanks, Tim From Scott.Daniels at Acm.Org Tue Jun 28 12:35:07 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 28 Jun 2005 09:35:07 -0700 Subject: Newbie: Help Figger Out My Problem In-Reply-To: References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> Message-ID: <42c174ab$1@nntp0.pdx.net> db wrote: > On Tue, 28 Jun 2005 00:23:30 -0700, ChuckDubya wrote: >>... if flips >= 99: >> print "Heads: " + heads >> print "Tails: " + tails >> print "Total: " + flips + "flips" >>raw_input("Press the enter key to exit.")... > > Your programm gives an error. You are trying to concatenate strings with integers. > Might I suggest you were looking for this: ... print "Heads: ", heads print "Tails: ", tails print "Total: ", flips, "flips" ... --Scott David Daniels Scott.Daniels at Acm.Org From bs343 at you-know-where.ac.uk Tue Jun 7 19:42:01 2005 From: bs343 at you-know-where.ac.uk (bens) Date: Wed, 08 Jun 2005 00:42:01 +0100 Subject: Help! File objects and scoping Message-ID: I'm trying to return an 'mmap' object from a function. The return works, but some of the object's methods crash. Here are two examples doesntwork.py --------------------------- import mmap import os name="/any/real/file/on/my/hard/drive" def getfile(name): somefile=file(name, 'r+b') mmapped = mmap.mmap(fileno=somefile.fileno(), \ length=os.path.getsize(name)) return mmapped mmapped=getfile(name) mmapped.seek(1) #this works, so mmapped is a working mmap object print mmapped.size() #this dies with an error mmapped.close() -------------------------- doesntwork.py dies with the error: EnvironmentError: [Errno 9] Bad file descriptor On the other hand, doeswork.py --------------------------- import mmap import os name="/the/exact/same/file" somefile=file(name, 'r+b') mmapped = mmap.mmap(fileno=somefile.fileno(), \ length=os.path.getsize(name)) mmapped.seek(1) #works fine print mmapped.size() #works fine, prints out the right number mmapped.close() -------------------------- The only difference between doeswork and doesntwork is whether 'mmapped' is created in the global scope or created in a local scope and returned. Why does that make a difference? The strangest thing about this, I think, is that the error printed out above, EnvironmentError, is listed in the docs under "only used as base classes for other exceptions". In other words, it's never supposed to be thrown. I'll take any advice you can give me. Thanks, Ben Schwartz www.mit.edu/~bens/ From harlinseritt at yahoo.com Sat Jun 18 01:01:01 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 17 Jun 2005 22:01:01 -0700 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> Message-ID: <1119068711.730364.215290@g47g2000cwa.googlegroups.com> On 2005-06-18, cpunerd4 wrote: >> I've guessed that python is purely an interpreted language unless its >> compiled into another language (ie. it needs python installed in order >> to run programs). Is this correct? >It's just like Java. It's compiled into bytecode and then the >bytecode is executed on a virtual machine. So true. Am I the only one who wonders this: If Python at runtime runs very much like Java and has generally about the same speed (or faster), then why in the world isn't Java becoming more archaic and being steadily replaced by Python? I ask this not as a rhetorical question, but --really-- how come developers are still stuck on Java when Python seems to be a far better language? In context, Python is not a low level compiled language like C/C++ is but an interpreted one just like Java. Bruce Eckel even marvels at the concise syntax of Python: "In Python, I can process each line in a file by saying: for line in file("FileName.txt"): # Process line I didn't have to look that up, or to even think about it, because it's so natural. I always have to look up the way to open files and read lines in Java." If anyone cares to give an intelligence answer to my question, I'll be happy to take it in without ridicule but I just don't see it. Sorry for the rant (and somewhat off-topic but I hear you guys are tolerant of that in this group ;-)), but this is something that has been weighing on my mind for the last 6 months. Harlin Seritt From rex.eastbourne at gmail.com Wed Jun 29 11:25:52 2005 From: rex.eastbourne at gmail.com (Rex Eastbourne) Date: 29 Jun 2005 08:25:52 -0700 Subject: Debugger Confusion In-Reply-To: References: Message-ID: <1120058752.835849.78610@g14g2000cwa.googlegroups.com> Thanks! From ptmcg at austin.rr.com Wed Jun 22 23:46:34 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 22 Jun 2005 20:46:34 -0700 Subject: Avoiding deadlocks in concurrent programming References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: <1119498394.311663.305180@g14g2000cwa.googlegroups.com> Using an RDBMS is no cure-all for deadlocks - I can just as easily deadlock with an RDBMS as with my own threads and locks, probably easier. I try to pick up crumbs of knowledge from my co-workers, and one of the smarter ones gave me this rubric for testing for deadlocks. You need 3 things to create deadlock: 1. multiple locks 2. multiple threads of execution 3. mixed access order to the locks (process 1 has lock A and wants lock B, while concurrently process 2 has lock B and wants A) So to avoid deadlock, invert the rubric and get rid of any one of these elements. One proposed solution was to use a single global lock - this would cancel out criteria number 1. An alternative might be to get rid of multiple threads. Your current design uses a background thread, but if this could be merged in some round-robin fashion with the other needed processing (a generator pool perhaps?), then you could try door #2. If you don't like either of these options, then look at ways to ensure locks are always acquired in the same order - perhaps alphabetically by resource name, or top-down if organized hierarchically - to ensure that locks are never acquired in mixed order. In the case of processes 1 and 2, if all locks were to be acquired alphabetically, then process 2, holding B and wanting A, would have to first release B, then request A and then re-request B. This would break the deadlock with process 1. I don't know if I've really offered anything new, but at least you have some structure with which to approach your question. -- Paul From mvanaswegen at gmail.com Mon Jun 6 02:58:18 2005 From: mvanaswegen at gmail.com (marinus van aswegen) Date: Mon, 6 Jun 2005 08:58:18 +0200 Subject: Socket Speed In-Reply-To: <20050605135944.GA18270@unpythonic.net> References: <1117979261.996245.143810@g14g2000cwa.googlegroups.com> <20050605135944.GA18270@unpythonic.net> Message-ID: Would you care to do that between two machines on a 100mb link ? On 6/5/05, Jeff Epler wrote: > 300KB/s sounds dreadfully low. > > I simply ran "python /usr/lib/python2.3/SimpleHTTPServer.py &", then > "wget -O /dev/null http://0.0.0.0:8000/70megfile". On the best of 4 > runs (when the file was cached) wget measured 225.20MB/s. > > The hardware is a Pentium-M laptop with 768MB RAM runnng at 1.5GHz. The > OS is Fedora Core 2, kernel 2.6.12-rc5, Python 2.3. > > Jeff > > > From flupke at nonexistingdomain.com Fri Jun 24 08:35:40 2005 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 24 Jun 2005 12:35:40 GMT Subject: webserver application (via Twisted?) Message-ID: I need to program and setup serveral webservices. If i were still using jsp, i would use Tomcat to make the several applications available on a given port. How can i accomplish this in Python? I was thinking about Twisted but it's not clear to me what parts i need to make a webserver listen on a certain port and having it serve different application based on the url that i received. Any advice on this? Thanks, Benedict From avera at coes.org.pe Thu Jun 30 18:44:39 2005 From: avera at coes.org.pe (Alberto Vera) Date: Thu, 30 Jun 2005 17:44:39 -0500 Subject: pdf in full-color Message-ID: <000a01c57dc5$4cc38b00$1603a8c0@pc22> Hello. I got a pdf file from a microsoft word document using Linbox-converter. The problem is that I got a pdf file in white&black color. Do you know another library to convert this to a full-color? Is it possible to do that using Linbox-converter? Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From philippe at philippecmartin.com Mon Jun 20 11:53:48 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 15:53:48 GMT Subject: Python choice of database References: <9yBte.372$W74.334@newssvr30.news.prodigy.com> Message-ID: You mean pickling a dictionnary of 5000/16K objects ? Erik Max Francis wrote: > Philippe C. Martin wrote: > >> Well that would be shelve I guess ... with the restrictions I mentioned. > > I was talking about pickle, not shelve. > From jrastrick at student.usyd.edu.au Sat Jun 18 03:32:43 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 18 Jun 2005 00:32:43 -0700 Subject: OO approach to decision sequence? In-Reply-To: References: Message-ID: <1119079963.742936.56500@g49g2000cwa.googlegroups.com> I've coded some simple recursive tree data structures using OO before (unfortunately not in Python though). It's not nessecarily an ill-suited approach to the task, although it depends on the specific details of what you're doing. What's the the piece of code from which your if...elif fragment is taken actually supposed to do? Without knowing more about your problem, I think the most obvious OO approach would be to write a seperate (simple) class for each of node_type_1, node_type_2, etc. Make sure each one provides the same interface, i.e. defines the same set of methods. Then put the different decision branches as implementations of a certain method in each class. class Node_Type_1(object): def recurse(self): # do stuff here class Node_Type_2(object): def recurse(self): # do other stuff here only make sure you use more informative names than "Node_Type_1" and "recurse" :) Your if elif code then collapses to: node.recurse() where the node variables refers to an instance of any one of your Node_Type classes. OO isn't magic. You still in the end have to write the code that implements the decision choices. In this example, its likely the OO code is actually more verbose, since you have all the class and method definitions to write as well. But there are advantages. Adding new cases (new node_types) is simpler and less error prone - you just write a new node_type class. The code for the new class, unlike a new elif brach, is kept cleanly and safely seperate from your existing, correctly working code. If you forget to provide the new class with the recurse method, you get a runtime error. But if you forget to add the case to your if..elif statement, you just end up silently going with your sentinel "else" branch, which may not be what you really want to do with that node_type. (in fact I'd usually raise an exception on reaching the else branch in any such extended if..elif structure, because it's almost always the result of an error in your program logic) Essentially, although you may end up writing more code, its also better organised, since as you wish it avoids your 'conventional lengthy if struture'. Its a partciularily useful approach if you have several different functions that need to branch on node-type in this fashion (e.g. pretty print the tree, post-order traverse it, run a search over it, etc). For each such function, you just provide a method on every node_type class. Again, if you forget to provide the code for a certain node_type, the error is very easy to detect. If your problem is simple, the OO approach may be overkill - your current if..elif code may be the most straightfoward solution. But if the problem is complicated, or has the potential to grow more complicated, the advantages of the OO approach may be a worthwhile trade off. Fortuantely Python is a multi-paradigm language, so the choice to use or not use OO according to what best suits the design and the problem is left up to you, the programmer, and is not thrust upon you by the language. And you certainly don't want metaclasses or anything else that complex and deep for something like this. Chinook wrote: > OO approach to decision sequence? > --------------------------------- > > In a recent thread (Cause for using objects?), Chris Smith replied with (in > part): > > > If your table of photo data has several types of photos, and you find > > yourself saying > > > > if is_mugshot: > > #something > > elif is_freehand: > > #something > > else: > > #something > > > > then OOP will help organize your code. > > This struck a chord because I'm trying to refactor a top-down approach to an > OO approach. The reason I am doing such is to try and get my mind wrapped > around OO design, not because the particular module will benefit from an OO > approach (it's a simple top-down recursive tree utility). In fact it's > probably ill suited for OO and that is why I chose it. > > I've used an OO approach where I built up record (instance) content in a > variable record file, but here I'm trying to come at it from the opposite > direction as variable record mapping (deconstructing) would be to such. > > Anyway, a tree node can be any of seven types where: > > if node_type_1: > # recurse > elif node_type_2: > # terminus - do something > elif node_type_3: > # terminus - do something else > ... > else: > # terminus - catch all, do yet something else > return #to parent > > So, where is the magic :~) Seriously, how might OO help me organize this > type of problem (alleviate the conventional lengthy if structure)? I've > looked at the cookbook, class interface techniques, factory functions and > metaclasses till my head is swimming. Am I missing a bolt in the machinery > somewhere, or simply trying to find magic that doesn't exist for a > straightforward decision sequence? > > Thank you, > Lee C From unclebob at objectmentor.com Wed Jun 1 11:46:06 2005 From: unclebob at objectmentor.com (Robert C. Martin) Date: Wed, 01 Jun 2005 10:46:06 -0500 Subject: Intellisense and the psychology of typing References: <1117125072.825389.74190@g47g2000cwa.googlegroups.com> Message-ID: <7plr9190lrppcqc8i8fmi1cs13hgq3v88i@4ax.com> On 26 May 2005 09:31:12 -0700, andrew.queisser at hp.com wrote: >Yesterday I typed in some C++ code that called a function with two >ints. Intellisense (auto-complete) helpfully told me that the first >formal parameter was called "frontLight" and the second "ringLight". It >occurred to me that I'm getting some semantic help here on top of the >obvious type safety. It seems to me that the existance of this kind of >support is tied to the static typing nature of C++. > >I've always been interested in the psychology behind those heated >"static" vs. "dynamic" (quotes to avoid another lengthy discussion >about manifest, latent, explicit, ...) typing debates. So I googled >"Intellisense static dynamic typing" and tried to get a view of the >collective mental landscape of this subject. It appears that the >threads that talk about Intellisense soon run dry. I'm wondering if >this is because: > >1) Intellisense is really just another crutch that does more harm than >good? There were a few hardcore defenders of this position but not >many. > >2) Intellisense is really useful but hard to implement well in IDEs for >dynamic languages? Can anyone comment on the status of >Intellisense-like tools for dynamic-language IDEs? > >3) Users of dynamic languages are always developing/debugging running >programs where the current type of a variable is known and hence >Intellisense is possible again? My own limited experience with dynamic >languages (Ruby) is limited to edit-run cycles. > >Any opinions? Static typing is a strong enabler of certain intelisense functions; but not all, nor even most. A good IDE for a dynamically typed language can make quite a few inferences to decide how to suggest intellisense. That said, statically typed languages will always have better intellisense than dynamically typed languages. Indeed, one of the reasons that I have not switched to Ruby as my standard language is the wonderful tools available with "IntelliJ" for Java and "ReSharper" for C#. ----- Robert C. Martin (Uncle Bob) | email: unclebob at objectmentor.com Object Mentor Inc. | blog: www.butunclebob.com The Agile Transition Experts | web: www.objectmentor.com 800-338-6716 "The aim of science is not to open the door to infinite wisdom, but to set a limit to infinite error." -- Bertolt Brecht, Life of Galileo From fredrik at pythonware.com Wed Jun 22 04:06:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Jun 2005 10:06:02 +0200 Subject: Using code objects? References: <0001HW.BEDD05A1000D6CC7F00FF3B0@smtp.tds.net> Message-ID: Chinook wrote: > When I create the code objects though, it seems a couple different ways > work and I'm wondering which is better and why (or is there a more correct > technique in this situation)? from where are you getting the source code for those code objects? from the example below, it sure looks like using callable objects and argument binding is a "better way" to do it. for the simplest cases, you can use a plain lambda to delay evaluation: > > The two different ways are illustrated below: > > Python 2.4.1 (#2, Mar 31 2005, 00:05:10) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] > Type "help", "copyright", "credits" or "license" for more information. > >>> def foo(st): > ... print st > ... >>> obj1 = lambda: foo("#expression1#") >>> obj1() #expression1# >>> obj2 = lambda: foo("#expression2#") >>> obj2() #expression2# From lycka at carmen.se Fri Jun 10 08:10:05 2005 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 10 Jun 2005 14:10:05 +0200 Subject: programmnig advise needed In-Reply-To: <1118171685.749946.240100@g47g2000cwa.googlegroups.com> References: <1118171685.749946.240100@g47g2000cwa.googlegroups.com> Message-ID: mitsura at skynet.be wrote: > Hi, > > I am writing a Python program that needs to read XML files and contruct > a tree object from the XML file (using wxTree). > The XML however is not an hiearchical XML file. It contains > and tags. The tags link the elements > together. Are you sure that you get a tree? As I understand your description, the XML format could well be used to describe arbitrary directed graphs, even cyclic ones. This might not be a problem unless someone tries to expand the entire tree...but you should probably have some kind of cycle check, or disallow "expand all" in the GUI and make sure you don't create the nodes before they are expanded. If you really just permit trees, it's fairly simple, because a node should just appear as a in an association once. You can put those in a set, and check that they aren't already in the set before you accept the content in a new association. Something like the following semi-pseudo-code: nodes = set() for name, parent in associations: if name in nodes: raise KeyError, ("%s is already in the tree. " "Can't put it under %s." % (name, parent) nodes.add(name) whatever... If you want to allow arbitrary directed acyclic graphs (DAGs), you have to work a little more. E.g. if you want to allow things like: A .B ..C ...D ...E .F ..C ...D ...E (I know that you said a tree, but I've certainly met clever and well educated people before who called DAGs trees...) For DAGs, you might traverse the tree to make sure there are no cycles, but there are probably better solutions as well. As I said, if it's really trees you want, this is not a problem. Actually, another risk is that your document describes several disjunct structures... Oh well, that's another issue, and you can always argue how defensive your code needs to be. It obviously depends on how well you trust your input and the implications of problems. Anyway, assuming cycle checks, it's easy to find roots: They are the keys in the dictionary that don't occur as values. If there's just one, you just have one tree. To summarize: If you want to describe a tree structure in XML, it's probably a good idea to use the natural hierarchy of XML tags to do this. That way the file can't convey a non-tree structure. If you need to use a construct like you describe in your XML, this suggests that you need to convey non-tree structures, and then you probably need to handle those as well. From gandalf at geochemsource.com Wed Jun 1 15:29:01 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 01 Jun 2005 21:29:01 +0200 Subject: idiom for constructor? In-Reply-To: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> Message-ID: <429E0C7D.2040202@geochemsource.com> Mac wrote: >Is there a nice Python idiom for constructors which would expedite the >following? > >class Foo: > def __init__(self, a,b,c,d,...): > self.a = a > self.b = b > self.c = c > self.d = d > ... > >I would like to keep the __init__ parameter list explicit, as is, >rather than passing in a dictionary, as I want the code to be explicit >about what arguments it expects... in effect enforcing the right number >of arguments. > > I could list the parameter names programatically: class A(object): def __init__(self,a,b,c,d,e,f,): varnames = self.__init__.im_func.func_code.co_varnames for varname in varnames[1:7]: print varname a = A(1,2,3,4,5,6) But I could not get their values. From deets at web.de Thu Jun 30 17:16:04 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 30 Jun 2005 23:16:04 +0200 Subject: how to shrink a numarray array? In-Reply-To: References: Message-ID: <3ij5omFlokn0U1@uni-berlin.de> Qiangning Hong wrote: > To draw a large array of data on a small panel, I need to shrink it to a > given size. e.g: > > To draw numarray.arange(10000) on a panel of width of 100, I only need > to draw the points of (0, 100, 200, 300, ...) instead of (0, 1, 2, ...). > So I need a method to shrink it to an 100-item array. > > x[::len(x)/panel_width] will not work. If the panel's width is 60, that > expression will return an array of 61 elements. > > I believe there is an existing function in numarray to do this, however > English is not my mother tongue and math is not my speciality, I can't > find it in the document full of math terms... > You can do that with bresenham's algortithm. But that's been sooo long since I did that the last time... The basic idea is that you us the larger of the values (your columncount) as a threshold. The you do msomething like this: columncount = 600 image_width = 60 v = 0 cols_to_pick = [0] for i in xrange(columncount): if v >= columncount: v -= columncount cols_to_pick.append(i) v += image_width Maybe a better idea is to try and find image scaling algorithms -they might even do filtering for you. Diez From gvanrossum at gmail.com Thu Jun 2 23:09:02 2005 From: gvanrossum at gmail.com (Guido van Rossum) Date: Thu, 2 Jun 2005 20:09:02 -0700 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements Message-ID: After many rounds of discussion on python-dev, I'm inviting public comments for PEP 343. Rather than posting the entire PEP text here, I'm inviting everyone to read it on line (http://www.python.org/peps/pep-0343.html) and then post comments on a Wiki page I've created for this purpose (http://wiki.python.org/moin/WithStatement). I think this is a good one; I hope people agree. Its acceptance will obsolete about 4 other PEPs! (A sign that it fulfills a need and that the proposed solution is powerful.) -- --Guido van Rossum (home page: http://www.python.org/~guido/) From pdemb at gazeta.pl Sun Jun 12 11:47:29 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 12 Jun 2005 17:47:29 +0200 Subject: python bytecode grammar References: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> Message-ID: <874qc3inla.fsf@hector.domek> "Terry Reedy" writes: > "M1st0" wrote in message > news:1118406741.403982.319720 at g44g2000cwa.googlegroups.com... >> where I can find the grammar of python bytecode ? ( better if is in >> BCF > > I believe the top-level production is something like > BYTECODE := (OPCODE ARGS)* ROTFL :) From leo at lspace.org Tue Jun 14 05:04:01 2005 From: leo at lspace.org (Leo Breebaart) Date: 14 Jun 2005 09:04:01 GMT Subject: Sending mail from 'current user' in Python References: <3gsve7Fe8957U1@individual.net> <863brp6c11.fsf@guru.mired.org> <42AC1B7D.8090502@abo.fi> Message-ID: <3h7ks1Ffnko1U1@individual.net> Marcus Alanen writes: > >>I've also tried opening a pipe to sendmail, and feeding the > >>message to that instead. This too works great [but] doesn't > >>seem like much of an improvement, portability-wise. > > No, but at least it can be expected to do the right thing > w.r.t. sending the mail. Good point. > >>Finally, if at all possible I'd also like to get this working on > >>Windows, so I'd rather stick with the standard smtplib if I can. > > smtplib needs an SMTP server to connect to. For unix systems, this is > > typically localhost. What do you use for Windows systems? Or are you > > connecting to your machine to deliver the mail? > > I'd be very surprised if the typical SMTP server is localhost > on unix-like computers. [...] Let the sendmail program take > care of those details. > > The Unix Programming Frequently Asked Questions "Q5.2 What's the best > way to send mail from a program?" is worth reading. Thanks to you and everyone else who contributed to this thread. I've now decided to accept the inherent non-portabilitiness of the whole concept of 'sending mail from within a program', and will be going with a Unix-only see-if-you-can-find-sendmail approach. -- Leo Breebaart From tdelaney at avaya.com Mon Jun 13 23:20:33 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 14 Jun 2005 13:20:33 +1000 Subject: Controlling a generator the pythonic way Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025205A7@au3010avexu1.global.avaya.com> FWIW, PEP 342 is now titled "Coroutines via Enhanced Iterators" :) Tim Delaney From philippe at philippecmartin.com Mon Jun 20 11:47:17 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 20 Jun 2005 15:47:17 GMT Subject: Python choice of database References: Message-ID: <9yBte.372$W74.334@newssvr30.news.prodigy.com> Well that would be shelve I guess ... with the restrictions I mentioned. Regards, Philippe Erik Max Francis wrote: > Philippe C. Martin wrote: > >> I am looking for a stand-alone (not client/server) database solution for >> Python. >> >> 1) speed is not an issue >> 2) I wish to store less than 5000 records >> 3) each record should not be larger than 16K >> >> >> As I start with Python objects, I thought of using shelve, but looking at >> the restrictions (record size + potential collisions) I feel I should >> study my options a bit further before I get started. > > Why not just use native Python data structures and pickle them? > From riccardo_cut1 at cut2_sideralis.net Thu Jun 23 06:48:47 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Thu, 23 Jun 2005 12:48:47 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: On Thu, 23 Jun 2005 12:56:08 +0300, Konstantin Veretennicov wrote: > On 6/22/05, Riccardo Galli wrote: > >> I propose to add an 'abs' keyword which would make os.listdir return the >> absolute path of files instead of a relative path. > > What about os.listdir(dir='relative/path', abs=True)? Should listdir call > abspath on results? Should we add another keyword rel? Would it complicate > listdir unnecessarily? > > - kv keyword dir not exists (don't know if you added as example or not) and abs set to true would return abspath on result. What else could it do ? -- Riccardo Galli Sideralis Programs http://www.sideralis.net From jeffelkins at earthlink.net Thu Jun 2 09:13:51 2005 From: jeffelkins at earthlink.net (Jeff Elkins) Date: Thu, 2 Jun 2005 09:13:51 -0400 Subject: xml processing In-Reply-To: References: Message-ID: <200506020913.52071.jeffelkins@earthlink.net> On Wednesday 01 June 2005 11:01 am, Steven Bethard wrote: > If you're not committed to pyxml, you might consider using ElementTree: > > http://effbot.org/zone/element-index.htm > > I find it *way* easier to work with. Thanks. I've installed it and am experimenting. From gilles.lenfant at nospam.com Thu Jun 16 12:36:52 2005 From: gilles.lenfant at nospam.com (Gilles Lenfant) Date: Thu, 16 Jun 2005 18:36:52 +0200 Subject: Subprocess and time-out Message-ID: <42b1ace9$0$4979$636a15ce@news.free.fr> Hi, Grabbing the various docs of Python, I didn't find how to do this : I Use popen2 to run wvware that transforms lots of M$ word docs to plain text. Sometimes wvware runs in a deadlock and I can't control this from Python app. I need to stop wvware processing after 30 seconds (considered deadlocked) and to process the next file. Unfortunately, I didn't find any pythonic stuff to control the time spent runnning subprocesses (and kill'em if needed) launched with popen. An hint is welcome. Many thanks by advance. -- Gilles Lenfant From http Fri Jun 17 15:34:58 2005 From: http (Paul Rubin) Date: 17 Jun 2005 12:34:58 -0700 Subject: smtplib and TLS References: <1119034830.168876.26290@f14g2000cwb.googlegroups.com> Message-ID: <7xmzposrod.fsf@ruckus.brouhaha.com> "Matthias Kluwe" writes: > The server accepts and delivers my messages, but the last command > raises > > socket.sslerror: (8, 'EOF occurred in violation of protocol') > > Did I miss something? Any hint is welcome. Looks like the module didn't send an TLS Close Notify message before closing the socket. I don't see anything in the docs about how to send one from smtplib or socket, though. From skn at skn.com Tue Jun 28 03:05:33 2005 From: skn at skn.com (skn) Date: Tue, 28 Jun 2005 12:35:33 +0530 Subject: JEP and JPype in a single process References: Message-ID: Thanks for your prompt reply, Steve. Just one suggestion, may be the startJVM method's implementation can itself be changed to check for already existing JVM. Of course this will also mean a change in shutdownJVM() semantics. If JVM has been started earlier(not using startJVM()), shutdownJVM() should be a do-nothing function. Another question I had was, is there any option to suppress the JVM activity report that gets displayed. For e.g., JVM activity report : classes loaded : 26 JVM has been shutdown I know I can do it by re-directing the std err to NUL. But is there any other option? With best regards, skn "Steve Menard" wrote in message news:MXFte.45766$Fn.345638 at weber.videotron.net... > skn wrote: > > Hello, > > > > I have written a very simple java class file, which invokes a Python script > > using JEP. > > > > Code snippet:- > > ------------------- > > Jep jep = new Jep(false); > > jep.runScript("C:\\temp\\testscript.py"); > > jep.close(); > > > > Now inside this Python script I want to make Java calls using JPype. > > If I use startjvm() inside this Python script, a Runtime Error (exception) > > is thrown. > > Also tried attachThreadToJVM(), but doesn't work, again Runtime Error. > > > > Any clues as to how I could achieve my goal?? > > The interaction shown below should happen in a single process. > > > > JAVA ==> jep ==> PYTHON ==> jpype ==> JAVA > > > > Regards, > > skn > > > > > > You're trying to do something I hope to make possible somewhere down the > road ... > > As of today, I do not think it is possible. JPype does not provide a way > to initialize the JVM-bridge system except for startJvm .. which seems > to be prohibited when a JVM is already running. > > AttachThreadToJVM will only work once the JVM-bridge system has been > initialize. > > I will look into providing a sister method to startJVM to attach to the > currently running JVM instead of starting a new one. IF it does not > require major changes I will release it as 0.5.1. If you'd like you can > submit an enhancement request on the JPype sourceforge page, so this > doesn't get lost. > > > > -- > Steve Menard > -------------------- > Maintainer of http://jpype.sourceforge.net From ptmcg at austin.rr.com Mon Jun 27 01:13:52 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Jun 2005 22:13:52 -0700 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> Message-ID: <1119849232.609949.272220@g43g2000cwa.googlegroups.com> ('abc') is not a tuple - this is an unfortunate result of using ()'s as expression grouping *and* as tuple delimiters. To make ('abc') a tuple, you must add an extra comma, as ('abc',). >>> list( ('abc',) ) ['abc'] -- Paul From jabel at plus.net Fri Jun 10 09:57:21 2005 From: jabel at plus.net (John Abel) Date: Fri, 10 Jun 2005 14:57:21 +0100 Subject: Perl s/ To Python? Message-ID: <42A99C41.6050207@plus.net> Does anyone know of a quick way of performing this: $testVar =~ s#/mail/.*$##g The only way I can think of doing it, is: mailPos = testVar.find( "mail" ) remainder = testVar[ :mailPos ] Any ideas would be appreciated. I'm iterating over a lot of entries, and running these lines for each entry. J From bvande at po-box.mcgill.ca Tue Jun 21 14:33:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 21 Jun 2005 14:33:42 -0400 Subject: Create our own python source repository In-Reply-To: <1119355109.640882.74380@g47g2000cwa.googlegroups.com> References: <1118145563.972344.325260@g43g2000cwa.googlegroups.com> <1118156654.634103.186390@o13g2000cwo.googlegroups.com> <1118170303.568984.242610@z14g2000cwz.googlegroups.com> <1119355109.640882.74380@g47g2000cwa.googlegroups.com> Message-ID: <42B85D86.80204@po-box.mcgill.ca> Michele Simionato said unto the world upon 21/06/2005 07:58: > qwwee: > >>for a certain argument I'd prefer an application fully >>explained (also if not covering all the features) to a more general >>tutorial with only brief and unrelated code snippets. >>Unfortunately, that's not the way things are normally done, because it >>is much harder to build a useful application and fully comment it > > > A part the Cookbook, I know of at least two Python books taking the > approach you describe: > > 1. Dive into Python (Pilgrim) > 2. Programming Python (Lutz) > > Dive into Python is free (and even translated in Italian on > www.python.it, IIRC) > > Michele Simionato > Not free, but: Practical Python, published by the same press as the Pilgrim, steps through incremental approaches to large (by book standards) applications. From the author's site: "Hetland devotes the second half of the book to project development, taking great care to choose a series of ten increasingly complex applications that are of timely and wide-ranging interest to burgeoning and expert developers alike. Project focus includes automated document conversion, newsgroup administration, graphical PDF document generation, remote document maintenance, the creation of a peer-to-peer system with XML-RPC, database integration, and GUI and game development. " http://hetland.org/writing/practical-python/ best, Brian vdB From ptmcg at austin.rr.com Tue Jun 28 10:22:59 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 28 Jun 2005 07:22:59 -0700 Subject: OO refactoring trial ?? References: Message-ID: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> Lee, Interesting idea, but I think the technique of "inherit from MF to automatically add class to the test chain" is a gimmick that wont scale. Here are some things to consider: - I'm not keen on the coupling of forcing your A,B,etc. classes to inherit from MF. Especially in a duck-typing language like Python, it adds no value, the subclasses receive no default behavior from their superclass, and I'm not keen on using the inheritance hierarchy to register test classes. What is the order of classes returned from __subclasses__()? Will you always want this order? Will you always want all subclasses? If this is part of a library that others will use, you may not be able to anticipate what subclasses someone else may stick on to your MF class. - The list of items should be dynamic in the calling code, not built statically by your class structure. There's no way to anticipate what various sequences you will want to evaluate. - Let's call the MF class "MultiEvaluator". There are several ways to evaluate among several alternatives: . short-circuit, take first match . best-fit, evaluate all and take best score (assuming the testit routines return a double or int, as opposed to a bool) For short-circuiting, say you have a case that will match A, you want to avoid any processing related to B,C,etc. as possible at test/do runtime. You *might* be able to do extra work at list construction time. Consider these two alternative designs: class MultiEvaluator(object): def __init__(self, *classes): self.testClasses = classes[:] def findit(self, *args): for C in self.testClasses: testobj = C() if testobj.testit(args[0]): testobj.doit() MultiEvaluator(A,B).findit("relates to A") vs. class MultiEvaluator(object): def __init__(self, *classes): self.testClasses = [ C() for C in classes ] def findit(self, *args): for testobj in self.testClasses: if testobj.testit(args[0]): testobj.doit() MultiEvaluator(A,B).findit("relates to B") In the first case, no B class is ever constructed, so if test object construction is expensive, you might go this route. In the second, A() and B() are built ahead of time, so the run-time processing is the fastest - you might choose this if the construction time can be done up front. The second option may cause problems for multi-threadedness or re-entrancy with a shared MultiEvaluator, though. This style of constructing the MultiEvaluator also makes more explicit (which I hear is better than implicit) what classes you are testing when creating your MultiEvaluator. - To make your testit() and doit() code more flexible and more powerful, I'd pass (*args) to each, as in: class MultiEvaluator(object): def __init__(self, *classes): self.testClasses = classes[:] def findit(self, *args): for C in self.testClasses: testobj = C() if testobj.testit(args): testobj.doit(args) - In the interests of flogging OO-ness, you could make MultiEvaluator into a function object, by changing "findit" to "__call__". Then your invocation of it would change from: getObj = MultiEvaluator(A,B) getObj.findit("relates to B") to: getObj = MultiEvaluator(A,B) getObj("relates to B") Although some might claim this is *less* explicit. The purpose of this is that you could then pass getObj to functional routines like map (although you could also pass getObj.findit). Those are my comments off the top of my head. Let us know what you come up with. -- Paul From harold.fellermann at upf.edu Tue Jun 7 10:55:51 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 7 Jun 2005 16:55:51 +0200 Subject: redirecting messgaef from sys.stdout In-Reply-To: <20050607144330.13561.qmail@web52203.mail.yahoo.com> References: <20050607144330.13561.qmail@web52203.mail.yahoo.com> Message-ID: On 07.06.2005, at 16:43, Ahmad Hosseinzadeh wrote: > Hello, > > I?m trying to run an external program in my > application. Both are coded in python. I need to write > an independent module that is used in the main > application. Its responsibility is to run the external > program and redirect its stdout and stderr to the main > application. > The application?s stdout and stderr are set to an > object and they are not command prompt anymore. > The output is selected by a flag; if true the stdout > and stderr will be redirected to application?s stdout > and stderr. If false, the stdout and stderr will be > redirected o command prompt. I don?t know how to > redirect the output. > Can anyone help please? have a look at: http://www.python.org/doc/current/lib/module-popen2.html -- Je me suis enferm? dans mon amour -- je r?ve. -- Paul Eluard From trentm at ActiveState.com Wed Jun 1 20:35:05 2005 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 1 Jun 2005 17:35:05 -0700 Subject: prob with ActiveState and FireFox on Win32 (XP and W2K) In-Reply-To: <1117672027.924838.245780@g47g2000cwa.googlegroups.com> References: <1117672027.924838.245780@g47g2000cwa.googlegroups.com> Message-ID: <20050602003505.GB25220@ActiveState.com> [curtin wrote] > hi, > i just downloaded the latest version of ActiveState's IDE (pywin 2.4.X) > and have noticed that i can't have firefox/ActiveState open at the same > time. if i try to create a 'new' script, the AS IDE blocks till i > tear down firefox. this is on an XP and W2K box. I suspect that you mean the *Pythonwin IDE* that is part of the *PyWin32 extensions* that comes as a standard part of *ActivePython* (a distro of Python). I can't reproduce this problem on my machine. I'm not sure how there could be crosstalk between Pythonwin and Firefox. Trent -- Trent Mick TrentM at ActiveState.com From peterbe at gmail.com Tue Jun 14 08:01:07 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 14 Jun 2005 05:01:07 -0700 Subject: Resume after exception References: Message-ID: <1118750467.115256.225630@g14g2000cwa.googlegroups.com> Why does the first function return True? Shouldn't it return the file content? That's at least what the function name implies. You call the second function open_command() which returns a boolean. Feels wrong. Where you have written "How?" I suggest that you replace that by: return open_file("foo.bar", 1) and change open_file() to look something like this: def open_file(file_name, ignore_lock=False): f = file(file_name, 'r') {read first line for file lock info} if first_line == "FILE LOCKED" and not ignore_lock: raise FileLockedException(lock_user, lock_timestamp) {read remainder of file} return True From claird at lairds.us Thu Jun 16 11:08:20 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 16 Jun 2005 15:08:20 GMT Subject: What language to manipulate text files References: <1118551021.345157.300200@g14g2000cwa.googlegroups.com> <1118569126.540000.217730@o13g2000cwo.googlegroups.com> <1118576811.816071.65590@z14g2000cwz.googlegroups.com> Message-ID: In article <1118576811.816071.65590 at z14g2000cwz.googlegroups.com>, wrote: >ross wrote: >> Roose wrote: >> > Why do people keep asking what language to use for certain things in the >> > Python newsgroup? Obviously the answer is going to biased. >> > >> > Not that it's a bad thing because I love Python, but it doesn't make sense >> > if you honestly want an objective opinion. >> > >> > R >> >> What usenet group is it best to ask in then? >> Is there one where people have good knowledge of many scripting >> languages? > >"What programming language is best for x" questions can be asked in >comp.programming and/or comp.lang.misc , and possibly in a >domain-specific newsgroup if it exists, for example >sci.math.num-analysis if x = scientific computing. The resulting >debates contain both heat and light :). > comp.lang.python is actually a fine place to ask such questions, I submit, for reasons the original poster could not have known: clp includes quite a few deeply-experienced commentators, and the ethos of clp favors accuracy over invective far more than some other newsgroups nominally better focused on general questions. From doodle4 at gmail.com Wed Jun 8 13:40:43 2005 From: doodle4 at gmail.com (ashtonn@gmail.com) Date: 8 Jun 2005 10:40:43 -0700 Subject: array problems.. OverflowError Message-ID: <1118252443.856435.8170@g44g2000cwa.googlegroups.com> How do i fill 1 byte and 4 bytes in a single array? This array contains packet information. Python code... from array import * size = 526 pData = array("B", '\0'* 526) # Destination MAC address destAddress = FFFFFFFFFFFF for i in range(0, len(destAddress), 2): pData[i/2] = int(destAddress[i:i+2], 16) pattern = 0xAAAAAAAA for i in range( 512): pData[i+6] = long(pattern, 16) print pData OverflowError: long int too large to covert to int def test(pData.buffer_info()[0]) .... .... Any help appreciated. -Ashton From theller at python.net Thu Jun 9 08:56:54 2005 From: theller at python.net (Thomas Heller) Date: Thu, 09 Jun 2005 14:56:54 +0200 Subject: identifying 64-bit Windows from 2.3.5? References: Message-ID: Steven Knight writes: > Hi Ivan-- > >>> If I have installed 2.3.5 from the python.org Windows installer, can >>> any one point me to a run-time way to identify whether I'm running on >>> a 32-bit vs. 64-bit version of Windows XP, given that Python itself was >>> built on/for a 32-bit system? >> >> I really don't think it matters too much which one you have, I have >> 64 bit and it works fine. > > Yes, the same Python executable and code works just fine on both systems, > but I need to do different things (in this case, invoke a different > compiler with a different set of compiler options) based on whether or > not I'm building on a 32-bit or 64-bit system. Use ctypes (sic!), or write a binary extension, and call IsWow64Process. http://msdn.microsoft.com/library/en-us/win64/win64/running_32_bit_applications.asp Thomas From adsheehan at eircom.net Thu Jun 9 09:05:45 2005 From: adsheehan at eircom.net (adsheehan at eircom.net) Date: 9 Jun 2005 06:05:45 -0700 Subject: How to determine your pthread in Python? Message-ID: <1118322345.961053.232460@g47g2000cwa.googlegroups.com> Does anyone know how to determine the pthread or native thread identifier while in Python ? FYI I have a multi-threaded C++ app on Solaris that embeds the Python interpreter. While in the interpreter I need to determine its actual running thread id. FYI2 The python interpreter is not firing off extra threads via the python threading classes etc. Thanks Alan From zathras at thwackety.com Sat Jun 4 13:03:50 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 04 Jun 2005 18:03:50 +0100 Subject: ANN: Axon 1.1.0 has been released! Message-ID: <42a1dedc$0$21771$ed2619ec@ptn-nntp-reader01.plus.net> Axon 1.1.0 has been released! What is it? =========== Axon is a collection of pure python modules from the Kamaelia project which allow you to build concurrent systems in a compositional manner using communicating python generators. Components are python generators are augmented by inbox and outbox queues (lists) for communication in a CSP like fashion. Version 1.1.0 also adds in the facility for writing components using threads as well as using generators. Put another way this allows you to build complex systems easily out of small concurrent components in a fashion similar to unix pipelines, except rather than being limited to just stdin/stdout you can have whatever inputs/outputs you desire. (The defaults are inbox/outbox, control/signal) Axon works under Linux, Mac OS X, Windows and a subset has been ported to Series 60 mobiles. Documentation is largely generated directly from the test suite output. Also, a presentation on Kamaelia (which may help put Axon in context) was give at ACCU/Python UK conference in April this year. The slides are available here: ???*?http://kamaelia.sourceforge.net/Kamaelia-ACCU-20050422.pdf This is due to be released as a BBC R&D White Paper shortly. What's Kamaelia? (for context :-) ================ Kamaelia is a project that aims to allow the BBC and others to create and test open protocols for large scale streaming. Substantial subsystems include a core concurrency subsystem and the beginnings of an RTSP/RTP streaming server. Existing functionality in Kamaelia that uses Axon includes a generic TCP & Multicast client and server framework that allows protocols to be trivially created, a number of example protocols, and an Ogg Vorbis decoding subsystem for client site testing (libvorbissimple). What's new in Axon 1.1.0? ========================= This release features support for components to be threads as well as python generators has been added, allowing the integration of arbitrary code blocking or non-blocking. Other changes include microprocesses (and hence components) can now be run without a scheduler in standalone mode and the debug subsystem has been reactivated system wide. Threaded components: ???*?Inherit?from?threadedcomponent?rather?than?Component ???*?Rather?than?have?a?generator?method?called?"main"?you?have?a?main ?????thread?method?called?"run".?(This?will?change?to?"main"?at?some?later ?????point?in?time) ???*?May?be?blocking.?(This?was?the?primary?reason?for?creating?them?-?Nokia ?????Series?60?sockets?cannot?be?used?in?a?nonblocking?manner,?requiring?the ?????use?of?threads?to?avoid?blocking) Platforms ========= Axon has been used successfully under both Linux, Windows and Mac OS X. A separate release branch exists for Series 60 Nokia mobiles. Where can I get it? =================== Axon is a sub-project of the BBC R&D Kamaelia project, which means Axon is downloadable from http://sourceforge.net/projects/kamaelia/ Web pages are here: ???http://kamaelia.sourceforge.net/Docs/Axon.html ???http://kamaelia.sourceforge.net/?(includes?info?on?mailing?lists) ViewCVS access is available here: ???http://cvs.sourceforge.net/viewcvs.py/kamaelia/ Licensing ========= Kamaelia (and hence Axon) is released under the Mozilla tri-license scheme (MPL/GPL/LGPL). Specifically you may choose to accept either the Mozilla Public License 1.1, the GNU General Public License 2.0 or the Lesser General Public License 2.1. Proprietary terms and conditions available upon request. Best Regards, Michael. -- Michael.Sparks at rd.bbc.co.uk, http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically state From claudio.grondi at freenet.de Sun Jun 12 20:31:59 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 13 Jun 2005 00:31:59 -0000 Subject: Following the white rabbit (was "The Python Way") References: Message-ID: <3h3rerFf41vdU1@individual.net> > Just follow the white rabbit. This triggers in me the temptation to start a thread asking: What (in your opinion) can a good programmer learn from watching all of the Matrix movies? Which part, one, two or three deals most with the philosophy of programming? Claudio "Jarek Zgoda" schrieb im Newsbeitrag news:d8iaen$1q3$1 at nemesis.news.tpi.pl... > Kalle Anke napisa?(a): > > > So, I'm looking for advice/information on: > > > > + How to write "proper" python code instead of > > Java/Perl/C/C++/Pascal/Modula-2/etc inspired code > > Just follow the white rabbit. > > Rewrite your code in Python, then optimize. > > -- > Jarek Zgoda > http://jpa.berlios.de/ | http://www.zgodowie.org/ From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 27 08:25:02 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 27 Jun 2005 14:25:02 +0200 Subject: noob question In-Reply-To: References: Message-ID: <3ia9guFkl32eU1@individual.net> Alan Gauld wrote: > The only place I've ever found Hungarian notation useful was > in C which is a weird mix of static typing and no-typing, > and there the prefix code gives a clue as to what kind of > value you might expect to find. But when I moved to C++ I > dropped the prefixes because they added no value. > In Python Hungarian notation is meaningless since variables > aren't typed anyway. Unfortunately, the original concept of Hungarian is often misunderstood, as shown by the article pointed out by Konstantin. Reinhold From gsakkis at rutgers.edu Fri Jun 10 13:00:20 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jun 2005 10:00:20 -0700 Subject: Abstract and concrete syntax References: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Message-ID: <1118422820.110286.245370@o13g2000cwo.googlegroups.com> "Kay Schluehr" wrote: > > Thu, 09 Jun 2005 03:32:12 +0200 skrev David Baelde: > > [snip] > > > > > > set_callback(obj, > > > lambda x: (if a: > > > 2 > > > else: > > > 3) > > > > > [snip] > > > > You can do stuff like this: lambda x: x and 2 or 3 > > You can also do this > > lambda x: {True:2,False:3}.get(bool(a)) > > which is both beautiful and pythonic. > > Kay Beauty and 'pythonicity' are in the eye of the beholder; IMO both are much less obvious than the if/then/else, especially for a beginner or someone who has never seen these idioms before. I personally don't find the (ab)use of dictionaries in this case to be more beautiful or pythonic than the and/or idiom (not to mention the runtime cost of building a new dictionary every time), but YMMV. George From richie at entrian.com Tue Jun 28 05:27:19 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 28 Jun 2005 10:27:19 +0100 Subject: FlashMX and Py2exe doesn't fly... In-Reply-To: References: <1119910271.719937.101370@g43g2000cwa.googlegroups.com> Message-ID: [Jim] > They did it with Gush: (I think) > http://2entwine.com/ > > It's a py program that embeds Flash.... very nice. Very nice indeed! Does anyone know any details about the technology they used for this? It appears to be closed source, and I couldn't see anything on their site about the architecture (other than a list of credits that includes ctypes, win32all, Macromedia and SciTE|Flash). -- Richie Hindle richie at entrian.com From mkluwe at gmail.com Sat Jun 18 03:32:58 2005 From: mkluwe at gmail.com (Matthias Kluwe) Date: 18 Jun 2005 00:32:58 -0700 Subject: smtplib and TLS In-Reply-To: <7xmzposrod.fsf@ruckus.brouhaha.com> References: <1119034830.168876.26290@f14g2000cwb.googlegroups.com> <7xmzposrod.fsf@ruckus.brouhaha.com> Message-ID: <1119079978.179618.262380@o13g2000cwo.googlegroups.com> > "Matthias Kluwe" writes: >> The server accepts and delivers my messages, but the last command >> raises >> socket.sslerror: (8, 'EOF occurred in violation of protocol') >> Did I miss something? Any hint is welcome. > Looks like the module didn't send an TLS Close Notify message before > closing the socket. I don't see anything in the docs about how to > send one from smtplib or socket, though. Hmm. I tried server.sock.realsock.shutdown(2) before server.quit() with the result of SMTPServerDisconnected('Server not connected') being raised. Quite an improvement ... Matthias From guy.lateur at b-b.be Tue Jun 14 06:31:36 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Tue, 14 Jun 2005 10:31:36 GMT Subject: Where is Word? References: <42aeae07@news.home.net.pl> Message-ID: Thanks, but could you pretty please post some code that does this? I'm new to Python, let alone COM.. TIA, g "Tomasz Lisowski" schreef in bericht news:42aeae07 at news.home.net.pl... > You may try to launch Word as a COM object and control it directly from > Python using the COM object methods. This does not require you to know the > application's path, only the COM object identifier. > > TLis From wookiz at hotmail.com Thu Jun 9 13:07:08 2005 From: wookiz at hotmail.com (wooks) Date: 9 Jun 2005 10:07:08 -0700 Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> Message-ID: <1118336828.878458.202840@z14g2000cwz.googlegroups.com> I am somewhat nonplussed that the opportunity to buy a Python book cheaply is off limits for this NG. There have been alot of hits and as there are very few Python books listed on Ebay I presume they came from here. I'm sorry if you took offence . I am just trying to find a new home for a book that I have finally accepted that I am never going to get round to reading and as I am unemployed right now every little helps. From deets at web.de Fri Jun 10 08:46:11 2005 From: deets at web.de (Diez B. Roggisch) Date: Fri, 10 Jun 2005 14:46:11 +0200 Subject: python bytecode grammar In-Reply-To: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> References: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> Message-ID: M1st0 wrote: > where I can find the grammar of python bytecode ? ( better if is in BCF > ). There is no grammar for bytecodes - the are like assembly instructions. And what's BCF supposed to mean - BNF is a form for grammars, BCF I never heard of. And besides that: tell us what you're after, we might help and suggest other ways than creating/manipulating bytecode, as this is considered a implementation detail that is not supposed to work across implementations (like jython) and is subject to unannounced changes between major revisions of python. Diez From mathnoir at gmail.com Thu Jun 2 00:01:07 2005 From: mathnoir at gmail.com (spinach) Date: 1 Jun 2005 21:01:07 -0700 Subject: The need to put "self" in every method In-Reply-To: References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: <1117684867.526604.101050@f14g2000cwb.googlegroups.com> >Explicit is better than implicit. import sarcasm def whatAboutMyImplicitModuleMethod() From facundobatista at gmail.com Thu Jun 2 23:57:40 2005 From: facundobatista at gmail.com (Facundo Batista) Date: Fri, 3 Jun 2005 00:57:40 -0300 Subject: decimal and trunkating In-Reply-To: <8dKdnRm_WPb3kALfRVn-vw@powergate.ca> References: <8dKdnRm_WPb3kALfRVn-vw@powergate.ca> Message-ID: On 6/2/05, Peter Hansen wrote: > >>> d = decimal.Decimal('199.999') > >>> decimal.getcontext().rounding = decimal.ROUND_FLOOR > >>> d.quantize(decimal.Decimal('1.00')) > Decimal("199.99") > > -Peter > > (I hope this inspires someone who actually knows what he's doing with > Decimal to post an improved solution.) This is the right solution, but take in consideration that normally you'll use one rounding method and you'll round to always the same places, so, at the beggining of your program you'll do: >>> import decimal >>> decimal.getcontext().rounding = decimal.ROUND_FLOOR >>> d2 = decimal.Decimal("0.01") and each time you want to round.... >>> d = decimal.Decimal('199.999') >>> d.quantize(d2) Decimal("199.99") So it's not really that ugly.... . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From amk at amk.ca Fri Jun 24 09:09:56 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 24 Jun 2005 08:09:56 -0500 Subject: Reminder: bug day on Saturday the 25th Message-ID: The Python bug day is coming up tomorrow, Saturday June 25th, running from 1PM to 7PM UTC (9AM to 3PM Eastern). Stop by the IRC channel (#python-dev on irc.freenode.net) and join in! For more info, see . --amk From gsakkis at rutgers.edu Sun Jun 26 17:58:11 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 26 Jun 2005 14:58:11 -0700 Subject: OO approach to decision sequence? References: <1119820490.656027.249730@g14g2000cwa.googlegroups.com> Message-ID: <1119823091.503532.60180@g44g2000cwa.googlegroups.com> "Paul McGuire" wrote: > Lee C - > > Here is a technique for avoiding the if-elseif-elseif...-else method > for building objects. It is a modified form of ChainOfResponsibility > pattern, in which you have a collection of factory methods that all > have a common signature, or a collection of Factory classes that all > implement a "makeObject" method. These common methods probably take a > string, and return a generic object. Fortunately, such type > flexibility is *very* easy in Python. :) > > Example: > I want to convert individual strings to native data types. I want to > detect integers, reals, complex numbers, and booleans (indicated by > 'True' or 'False'). This is kind of similar to a parsing problem, but > it could also be used for deserializing or unpickling data of an > unknown original type. > > Note the special treatment I have to go through with boolean values - I > needed to write a special makeBool routine, since Python will take any > non-empty string to be True, when what I want is 'True' to yield true > and 'False' to yield false. > > Hope this gives you some alternative ideas to your cascading if's. > > -- Paul > > > def makeBool(s): > if s in ('True','False'): > return s == 'True' > raise ValueError > > converters = [ int, float, complex, makeBool, str ] > > def makeObject(stringVar): > for conv in converters: > try: > val = conv(stringVar) > except Exception: > continue > else: > break; > return val > > def test(s): > val = makeObject(s) > print s, val, type(val) > > test('1') > test('1.0') > test('1+2j') > test('1+0j') > test('True') > test('False') > test('A') > > prints: > 1 1 > 1.0 1.0 > 1+2j (1+2j) > 1+0j (1+0j) > True True > False False > A A Nice technique. Something that needs to be pointed out is that the order of the converters *is* important; int takes precedence over float, which take precedence over complex and bool takes precedence over string. More succinctly: { int -> float -> complex } { bool -> str } In general the converters will form a strict partially ordered set, so the list of converters should be a topological sort of the respective DAG. George From nospam at nospam.nospam Sun Jun 26 23:12:49 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Sun, 26 Jun 2005 20:12:49 -0700 Subject: Acceptance test spike example References: Message-ID: <5krub19pc962m7e2pd3545d5e3tqtdo7da@4ax.com> On Sun, 26 Jun 2005 22:42:40 -0400, "Terry Reedy" wrote: > >"Steve Jorgensen" wrote in message >news:mhcub1p3mlcbnsf0dqk9akdrm5ut347rd0 at 4ax.com... >> Note how the powerful, context-aware exec() and eval() procedures really >> help >> simplify the code. > >A stylistic note: I believe that most or all of your eval/exec uses could >be done with getattr and setattr instead, which are in the language for >precisely those situations in which the name of an attribute is in a >runtime string. To my mind, this would be simpler and better style. > >> valueExpr = "self.model." + parsed.name >> valueIs = eval(valueExpr) > >I believe this is valueIs = getattr(self.model, parsed.name) > >> methodCall = "self.model." + parsed.name +"(" + parsed.value + ")" >> exec(methodCall) > > >I believe this is getattr(self.model, parsed.name)(parsed.value). > > >> exec("self.model." + parsed.name + "=" + parsed.value) > >I believe this is setattr(self.model, parsed.name, parsed.value). > >and so on. Thanks. I'm new to Python, so I'll take all the style advice I can get. - Steve J. From jjl at pobox.com Sat Jun 4 18:30:48 2005 From: jjl at pobox.com (John J. Lee) Date: 04 Jun 2005 22:30:48 +0000 Subject: Controlling source IP address within urllib2 References: <1117839742.510669.245420@g14g2000cwa.googlegroups.com> Message-ID: <87slzxlppj.fsf@pobox.com> "Dan" writes: > Does anybody know how to control the source IP address (IPv4) when > using the urllib2 library? I have a Linux box with several IP > addresses in the same subnet, and I want to simulate several > individuals within that subnet accessing web pages independently. I > need the functionality of urllib2 because there will be redirects and > other HTTP-type functions to implement. It would be nice if I could > create (and bind) sockets myself and then tell the urllib functions to > use those sockets. Perhaps there is some sort of "back-door" way of > doing this??? Any hints are appreciated! There's no built-in support, but I expect it's very easy to do. I suppose the easiest way would be to derive from httplib.HTTPConnection, overriding .connect() to call .bind() on the socket. Call it BindingHTTPConnection, then define: class BindingHTTPHandler(urllib2.HTTPHandler): def http_open(self, req): return self.do_open(BindingHTTPConnection, req) Same goes for https: if hasattr(httplib, 'HTTPS'): class BindingHTTPSHandler(urllib2.HTTPSHandler): def https_open(self, req): return self.do_open(BindingHTTPSConnection, req) Personally, I probably wouldn't use build_opener(), but since the above classes derive from the corresponding urllib2 classes, you can do: opener = urllib2.build_opener(BindingHTTPHandler, BindingHTTPSHandler) response = opener.open('http://www.example.com/') John From tim.golden at viacom-outdoor.co.uk Wed Jun 22 11:44:40 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 22 Jun 2005 16:44:40 +0100 Subject: python create WMI instances Message-ID: <9A28C052FF32734DACB0A288A3533991EBB921@vogbs009.gb.vo.local> [future_retro at yahoo.co.uk] | Win32_Printer doesn't work with the Create method and | AddPrinterConnection only lets me add a connection to a share. I'll | try and work out how to set the printer object properties in | the format | suggested; | | oPrinter.Properties_ ("DriverName").Value = strDriver | | Cheers, MW. I'm sorry my module won't have been much use to you in this, but it would be *really* helpful if you could post [a fragment of] the code you come up with so I can see what changes I need to make to help our future instance-spawners. It's just that I've never had the need to do this, and don't have any time to experiment at present. Thanks TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From edcjones at comcast.net Wed Jun 29 23:54:17 2005 From: edcjones at comcast.net (Edward C. Jones) Date: Wed, 29 Jun 2005 23:54:17 -0400 Subject: __new__, __init__ and pickle Message-ID: <7aydnaWBHJl58V7fRVn-3w@comcast.com> Suppose I want to define the class MyClass so I can create an instance by MyClass(arg0, arg1, kwarg0=None, kwarg1=0, reuse=None, save=None) If reuse is not None, it is the name of a pickle file. Unpickle the file to get the instance. If save is not None, it is a file name. Pickle the instance into the file as part of creating the instance. How do I write MyClass? Search Google Groups for the phrase "pickling a subclass of tuple" to find a relevant article. From jarrod.roberson at gmail.com Mon Jun 13 14:15:44 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 13 Jun 2005 11:15:44 -0700 Subject: Dealing with marketing types... In-Reply-To: References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118429907.140244.298390@g43g2000cwa.googlegroups.com> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> Message-ID: <1118686544.031915.264080@o13g2000cwo.googlegroups.com> I agree about the stiffing the guys that brought you to the party, that was 100% the DotCom plan, offer crap salary and tonnes of "options" then fire/replace all the people that worked for _FREE_ practically when the next round of funding comes in, rinse, repeat. Either way . . . I think the guy needs to move on. I know I would. From peter at engcorp.com Thu Jun 9 22:02:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 22:02:08 -0400 Subject: inactive Spambayes w/ Outlook In-Reply-To: References: <1118358998.183038.192940@g14g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > The following link might help. Pay particular attention to item 6 under > "Addin doesn't load", since what you describe is very similar to a > problem I had which that sequence fixed for me. Hah! And you thought the link was going to follow in the same message. Oh no, that would be _much_ too easy. It is of course in the following *message*, specifically this one. http://cvs.sourceforge.net/viewcvs.py/spambayes/spambayes/Outlook2000/docs/troubleshooting.html?rev=HEAD -Peter From michele.simionato at gmail.com Fri Jun 17 04:25:29 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 17 Jun 2005 01:25:29 -0700 Subject: What is different with Python ? In-Reply-To: <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> Message-ID: <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Andrea Griffini: > I also must note that I, as a fourteen, found terribly > interesting the idea of programming a computer even > if the only things I could do were for example turning > on and off pixels (blocks?) on a screen with resolution > 40x50. Probably nowdays unless you show them an antialiased > texture mapped 3D floating torus with their name and > face on it in live video they'll prefer exchanging > stupid messages with the mobile phone instead. Well, on one hand I think that even 20 years ago 99% of people preferred talking about football than programming; on the other hand, I think that even now there is a 1% of people extremely interested in turning on or off a pixel. I don't think anything significant changed in the percentages. Michele Simionato From bob at passcal.nmt.edu Sun Jun 5 14:52:04 2005 From: bob at passcal.nmt.edu (Bob Greschke) Date: Sun, 5 Jun 2005 12:52:04 -0600 Subject: tkinter, option_add, entry field trouble Message-ID: I can't get Root.option_add("*Entry*highlightthickness", "2") Root.option_add("*Entry*highlightcolor", "green") to work. Anyone know why? Setting the font, background color, etc. this way works OK. Are there some options that can't be set "globally"? Setting these two options in the Entry() statements themselves works OK. I've just got about 200 Entry statements that I was hoping to not have to edit. :) This is on Linux FC1, Python 2.3. Thanks! Bob From steve at REMOVETHIScyber.com.au Sat Jun 25 21:53:50 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 11:53:50 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote: > Mandus wrote: > >> By using the builtin reduce, I >> move the for-loop into the c-code which performs better. > > No. There is no hope of ever writing fast code when you do not actually > measure its performance. Good grief! You've been spying on Mandus! How else could you possibly know that he doesn't measure performance? Are you running a key-logger on his machine? *wink* For the record, perhaps now is a good time to mention that even Guido recommended the use of map, filter and reduce in some circumstances: "Try to use map(), filter() or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function!" http://www.python.org/doc/essays/list2str.html He specifically mentions that the reason map will often beat a for loop is that it moves the work out of Python into the underlying C code. That is also one of the reasons that ''.join(L) is faster than s = '' for item in L: s = s + item Do we really need to profile our code every single time to know this? Isn't it reasonable to just say, "I use join because it is faster than adding strings" without being abused for invalid optimization? -- Steven. From kent37 at tds.net Tue Jun 14 14:11:09 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Jun 2005 14:11:09 -0400 Subject: collect data using threads In-Reply-To: References: <42aeeef3$1_1@newspeer2.tds.net> <42AF02BD.9080809@bellsouth.net> Message-ID: <42af1d4f$1_1@newspeer2.tds.net> Qiangning Hong wrote: > I actually had considered Queue and pop() before I wrote the above code. > However, because there is a lot of data to get every time I call > get_data(), I want a more CPU friendly way to avoid the while-loop and > empty checking, and then the above code comes out. But I am not very > sure whether it will cause serious problem or not, so I ask here. If > anyone can prove it is correct, I'll use it in my program, else I'll go > back to the Queue solution. OK, here is a real failure mode. Here is the code and the disassembly: >>> class Collector(object): ... def __init__(self): ... self.data = [] ... def on_received(self, a_piece_of_data): ... """This callback is executed in work bee threads!""" ... self.data.append(a_piece_of_data) ... def get_data(self): ... x = self.data ... self.data = [] ... return x ... >>> import dis >>> dis.dis(Collector.on_received) 6 0 LOAD_FAST 0 (self) 3 LOAD_ATTR 1 (data) 6 LOAD_ATTR 2 (append) 9 LOAD_FAST 1 (a_piece_of_data) 12 CALL_FUNCTION 1 15 POP_TOP 16 LOAD_CONST 1 (None) 19 RETURN_VALUE >>> dis.dis(Collector.get_data) 8 0 LOAD_FAST 0 (self) 3 LOAD_ATTR 1 (data) 6 STORE_FAST 1 (x) 9 9 BUILD_LIST 0 12 LOAD_FAST 0 (self) 15 STORE_ATTR 1 (data) 10 18 LOAD_FAST 1 (x) 21 RETURN_VALUE Imagine the thread calling on_received() gets as far as LOAD_ATTR (data), LOAD_ATTR (append) or LOAD_FAST (a_piece_of_data), so it has a reference to self.data; then it blocks and the get_data() thread runs. The get_data() thread could call get_data() and *finish processing the returned list* before the on_received() thread runs again and actually appends to the list. The appended value will never be processed. If you want to avoid the overhead of a Queue.get() for each data element you could just put your own mutex into on_received() and get_data(). Kent From dave at pythonapocrypha.com Fri Jun 24 10:16:06 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 24 Jun 2005 08:16:06 -0600 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: <42BC15A6.4040801@pythonapocrypha.com> D H wrote: > Peter Hansen wrote: >>D H wrote: >>>Peter Hansen wrote: >>>>Bo Peng wrote: >>Actually that's just one possible answer. Whether it's _the_ answer is >>obviously again a matter of opinion, and as usual we differ. > > Quit being such an idiot and refuting everything I say. The answer is > simply no, just use an if statement instead. Please keep the discussion civil; please help keep c.l.py a nice place to visit. Thanks, Dave From mandus at gmail.com Fri Jun 10 06:43:49 2005 From: mandus at gmail.com (Mandus) Date: Fri, 10 Jun 2005 10:43:49 +0000 (UTC) Subject: Abstract and concrete syntax References: Message-ID: As someone who like to do functional style programming, but without a lot of training in that dept., I miss what you ask for from time to time. I don't want to go to much into this discussion, just comment on a tiny little bit: Thu, 09 Jun 2005 03:32:12 +0200 skrev David Baelde: [snip] > > set_callback(obj, > lambda x: (if a: > 2 > else: > 3) > [snip] You can do stuff like this: lambda x: x and 2 or 3 Of course, you are still quite limited in what you can do, but it have solved some of my problems... mvh, -- Mandus - the only mandus around. From merkosh at hadiko.de Sat Jun 25 06:44:35 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 25 Jun 2005 12:44:35 +0200 Subject: Life of Python Message-ID: Hi, I have come across the following statement a number of times: http://mail.python.org/pipermail/python-list/2003-July/171805.html [... how to enforce pure abstract class ...] > Python, in general, doesn't try to stop the programmer doing things, the > way many other languages do. This is known in the community as the > "we're all consenting adults" philosophy. I have a split opinion on that: pro: If you're writing smaller apps and everything stays rather clearly laid out you don't need to care about abstract, virtual, accessor functions, private, public, interfaces, etc con: If you are planning larger applications (for a reasonable value of "large") you have to discipline yourself to write well structured code. Then you will want to specify interfaces, accessor functions with different read /write access, ... Unless you have designed the software interactions completely bevorehand (which never works out) this is the only way to incorporate changes without refactoring your source all the time. Therefore I come to the conclusion that a general purpose language like Python may well allow tampering with name-mangeling, dynamic method resolution, whatever, BUT it should also provide facilities to allow enforcing a more structured approach. This is why I welcome i.e. the decorator support in Python 2.4. And I think this should be expanded further, i.e. more build-in decorators for interfaces, abstract classes, parameter and return value restrictions. You can, but you must not; and I use both, depending on the project I'm working on. IMO this is a problem i.e. Perl is faceing: you can do even more rubbish with Perl than with Python and since there is no way of forcing a programmer to do it a certain way, its often easyer to rewrite Perl programs over 400 lines than to fix them. Ciao Uwe From tojuso at hotmail.com Fri Jun 3 19:02:22 2005 From: tojuso at hotmail.com (Dan) Date: 3 Jun 2005 16:02:22 -0700 Subject: Controlling source IP address within urllib2 Message-ID: <1117839742.510669.245420@g14g2000cwa.googlegroups.com> Does anybody know how to control the source IP address (IPv4) when using the urllib2 library? I have a Linux box with several IP addresses in the same subnet, and I want to simulate several individuals within that subnet accessing web pages independently. I need the functionality of urllib2 because there will be redirects and other HTTP-type functions to implement. It would be nice if I could create (and bind) sockets myself and then tell the urllib functions to use those sockets. Perhaps there is some sort of "back-door" way of doing this??? Any hints are appreciated! -Dan From aahz at pythoncraft.com Sun Jun 5 20:39:47 2005 From: aahz at pythoncraft.com (Aahz) Date: 5 Jun 2005 17:39:47 -0700 Subject: The need to put "self" in every method References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: In article , Piet van Oostrum wrote: >aahz at pythoncraft.com (Aahz) (A) wrote: >> >> Any objection to swiping this for the FAQ? (Probably with some minor >> edits.) > >No. >The global/local stuff needs a bit more nuance (assignments in the method >being the criterium). Done! Thanks for prodding the update. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From max at alcyone.com Mon Jun 20 11:23:50 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 20 Jun 2005 08:23:50 -0700 Subject: Python choice of database In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > I am looking for a stand-alone (not client/server) database solution for > Python. > > 1) speed is not an issue > 2) I wish to store less than 5000 records > 3) each record should not be larger than 16K > > > As I start with Python objects, I thought of using shelve, but looking at > the restrictions (record size + potential collisions) I feel I should study > my options a bit further before I get started. Why not just use native Python data structures and pickle them? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I used to walk around / Like nothing could happen to me -- TLC From piet at cs.uu.nl Mon Jun 20 06:34:31 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 20 Jun 2005 12:34:31 +0200 Subject: Can we pass some arguments to system("cmdline")? References: <1119247925.349892.263780@f14g2000cwb.googlegroups.com> <1119254048.614944.123570@g43g2000cwa.googlegroups.com> Message-ID: >>>>> "Didier Casse" (DC) wrote: >DC> Thanks all for the reply. I'll try out those things out. :) But don't try the following >>> > system("ls $dir"); with >>> dir=="/home/foo; rm -rf /" -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From claird at lairds.us Tue Jun 14 17:08:05 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Jun 2005 21:08:05 GMT Subject: Where is Word? References: <42aeae07@news.home.net.pl> <42aecaf8$1@news.home.net.pl> Message-ID: In article <42aecaf8$1 at news.home.net.pl>, Tomasz Lisowski wrote: . . . >import win32com.client >wordCOMID = "Word.Application" > >word = win32com.client.Dispatch(wordCOMID) > >Then you can use the methods of the word object, provided by the COM >object definition. Unfortunately I don't know them - you may do a >research by making a reference to the Microsoft Word type library in >Visual Basic, declaring the variable of type Word.Application, and then >watching the code assistant showing the available methods and >properties. You may also use the object browser. . . . has still more alternatives. From lycka at carmen.se Wed Jun 22 10:16:29 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 22 Jun 2005 16:16:29 +0200 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Remi Villatel wrote: > Erm... You totally missed the point. I wrote it this way because, first, > it's perfectly valid Python code and, second and most important, it's > also a valid english sentence. Remi, I think you have failed to understand what Fredrik was telling you. I can understand that, because he didn't actually explain the problem. He probably thought it was obvious, but it seems it wasn't. "if a is b:" is equivalent to "if id(a) == id(b)". It doesn't test whether two values are the equal, it tests whether a and b are the same object. None is a singleton object in Python, but True is not. (At least not in the Python versions I use.) That means that you are relying on Python to use a performance optimization (interning of some common values, in this case the integer 1, which is what True is in practice). In some cases, "==" and "is" happens to give the same result. >>> a = 1 >>> b = 1 >>> a == b 1 >>> a is b 1 But often not. >>> c = 123456789 >>> d = 123456789 >>> c == d 1 >>> c is d 0 Or, for an example of the opposite: >>> class Smaller: ... def __cmp__(self, other): ... return -1 ... >>> s = Smaller() >>> b = a >>> a < b 1 >>> b < a 1 >>> a == b 0 >>> a is b 1 In other words, a test like "if x is None:" makes sense, since None is a singleton, but "if x is True:" certainly seems like buggy code that just happens to work. You could write "if x == True:" without risking a failure in some Python implementation that doesn't intern True (i.e. 1) if you are certain that x is 0 or 1, but it's completely redundant. Why stop there? Why not write "if x == True == True:" or "if x == True == True == True:"? These are all logically equivalent. You could also write "if x and True:", or "if x or not True" :) I understand what your intentions are: You feel that your code is easier to understand written the way you did it, but it stops feeling like that once you have gotten fully into your head that the expressions (a) and (a == True) are logically equivalent if a is either True or False. If you manage to get away from this "x == True" mind-set you are likely to write better Python code. First of all, a lot of Python values except 1 (a.k.a. True) are logically true in a Python expression. It's considered good form to exploit that. E.g. if y: z = x / y if text: print text if l: cols = len(l[0]) In these cases, adding a "==True", would break the code, and adding more "correct" comparisions would just clutter the code, which hides the intent and raises the risk for bugs, and make it more difficult to keep the code as flexible as Python code can be. E.g. if you change the last statement to "if l != []: cols = len(l[0])", you'll get in trouble if it turns out that l = (). The uncluttered code will still work. Secondly, if you ever write logical expressions that are more complex, you will make them much more difficult to read unless you drop that "== True" baggage. I'm convinced that it's easier to understand if past_six or past_three and saturday or sunday: than to understand if (past_six==True or past_three==True and saturday==True or sunday==True): I'm also pretty sure it's easier to write the first without making any mistake. From Scott.Daniels at Acm.Org Sat Jun 25 12:44:08 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 25 Jun 2005 09:44:08 -0700 Subject: a dictionary from a list In-Reply-To: References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: <42bd825b$1@nntp0.pdx.net> Roy Smith wrote: > Terry Hancock wrote: > ... > I just re-read the documentation on the dict() constructor. Why does it > support keyword arguments? > > dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"} > > This smacks of creeping featurism. Is this actually useful in real code? Yes it's useful, and it grew organically from the keyword arg syntax. No new syntax was introduced to provide this; the existing syntax was used. --Scott David Daniels Scott.Daniels at Acm.Org From codedivine at gmail.com Tue Jun 7 18:40:41 2005 From: codedivine at gmail.com (Rahul) Date: 7 Jun 2005 15:40:41 -0700 Subject: computer algebra packages Message-ID: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> Hi. Well is there an open source computer algebra system written in python or at least having a python interface? I know of 2 efforts: pythonica and pyginac...are there any others? rahul From garabik-news-2005-05 at kassiopeia.juls.savba.sk Tue Jun 14 04:29:04 2005 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Tue, 14 Jun 2005 08:29:04 +0000 (UTC) Subject: Which Python Wiki engine? References: Message-ID: Kenneth McDonald wrote: > > Here are some of the features I'd greatly like to have that I haven't > seen provided by the (relatively few) wiki engines I've looked at. > Mind you, I don't claim to have looked at even these few > exhaustively. (No time!) MoinMoin is the one I've looked at the most. > I do not like to write about vapourware, but anyway.... I am writing a new simple wiki/forum in python (using Karrigell framework), the main reason being that it needs some specialties not present in any other wiki. Anyway, I am going to put some notes about what my wiki _will_ have. > 1) Automatically generated table of contents, based on the outline > structure. This would be regenerated periodically (probably nightly) easily done > 2) Ability for users to add new subsections, but not to change that > part of the document structure which has been locked by the editor. I have not considered this, but it could be doable > 3) Clear visual distinction between material added by the users, and > material added or approved by the editor. easily done > 4) Legal-style numbering of sections, subsections, etc. by section you mean section in text, or section as "a group of wiki pages" ? The first one is easily done, due to pluggable formatters. > 5) Ability to have single pages containing both locked text (which > users cannot edit or delete) and unlocked text. Such a page would > consist of one or more locked blocks of text, interspersed with > comments put in by users. Users could put comments anywhere except > side a locked text block. possible, with some limitations (internaly, the sections are represented as separate pages, each with separate set of access rights, they are just rendered as one document) > > Ideally, this would also be something that doesn't depend on a > backend database or other things besides the web server and python > packages. This is not likely to be a wiki where huge amounts of more or less - storage is directly on filesystem, only if you need a full-text search you need a database (e.g. sqlite). You need Karrigell, though. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From mwm at mired.org Thu Jun 9 17:32:27 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 09 Jun 2005 16:32:27 -0500 Subject: my golf game needs gui References: Message-ID: <86y89j5i8k.fsf@guru.mired.org> Mike Hoy writes: > hi > > i've been writing a golf game in text only. this was to work out some of > details. it's great but making a golf course with ---'s and |||'s is > kinda silly looking. (at least to some..) > > now i'm ready to begin shopping for a gui widget to work with python so > my players can have some kind of pictures and possibly some motion. > > i won't be creating figures swinging the golf clubs but would like to > show their golf ball flying thru the air and land on the green for one > example. > > will pyQT work for me? Yes. The tutorial applications for Qt - which are provided in Python with PyQt - include an animated game. > any suggestions on which way I should go next? I like PyQt. Licensing for Windows is problematical, and changing. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From eserc at vestel.com.tr Fri Jun 24 07:44:31 2005 From: eserc at vestel.com.tr (=?WINDOWS-1254?Q?Eser_=C7etinkaya?=) Date: Fri, 24 Jun 2005 14:44:31 +0300 Subject: help! Message-ID: <03FB1C8A0749414494FE4726AADD7D4302A8C579@vkomexch1.zh.corp> In your documentation, it is written : " os.path.getatime(path) Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. " what do you mean by "access" ? this function gives same outputs with the " os.path.getmtime(path) " What can change an acess time of a path different from modification? Is there any mistakes in the implementation or am i missing some points? M.Eser Cetinkaya -------------- next part -------------- An HTML attachment was scrubbed... URL: From claudio.grondi at freenet.de Thu Jun 16 12:56:08 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 16 Jun 2005 16:56:08 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net><3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com><1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com><1118914590.744021.53950@z14g2000cwz.googlegroups.com><3hdfqlFgeeorU1@individual.net> Message-ID: <3hdi98Fgjbc4U1@individual.net> >> "Also I think the fact that you think your were diteriating just goes to >> show [...]" should be probably: "In my opinion the fact that you consider you were deteriorating just shows [...]" but it can be understood as it is anyway, right? Written maybe exactly as it is, with the only purpose: to encourage you, Andrea. Claudio "Jeffrey Maitland" schrieb im Newsbeitrag news:mailman.536.1118932214.10512.python-list at python.org... > Well as for the communication skills dropping. I highly doubt that, if > anything you are just picking up on things you never noticed before (and > your communication skills far surpass the average person that writes > anything in todays' society). > > A good example for me is that I am noticing that I seem to type the like hte > often, yes a spell checker picks it up but when writing code it's sometimes > not available. > > Also I think the fact that you think your were diteriating just goes to show > how dedicated you are to detail, and making sure you give the right advice > or ask the right question. > > Jeff > > From sjh at gmail.com Sun Jun 5 21:03:56 2005 From: sjh at gmail.com (sjh at gmail.com) Date: 5 Jun 2005 18:03:56 -0700 Subject: PyArg_ParseTuple and dict References: <1118017334.664017.327250@f14g2000cwb.googlegroups.com> <42A39E67.4060909@lexicon.net> Message-ID: <1118019836.874936.47490@o13g2000cwo.googlegroups.com> > 1. On the surface, there appears to be a bug. In the interests of > finding out where the bug is, perhaps it would be better if you posted > your minimal compilable runnable example of what *doesn't* work. I'll post it later tonight. > 2. To get you off the ground: *if* there is only one argument and it can > only be described in general terms like "O" (i.e. you still need to > check the type) then there is little point in using PyArg_ParseTuple; > describe the function as using METH_O instead of METH_VARARGS, and > access the arg directly. So, I started out using "iO!" and having PyArgParseTuple do the type checking for me (passing in an &PyDict_Type). > 3. What is your platform? Which C compiler? What warnings does it give, > [or would it give if allowed free speech]? Are you running Python 2.4 or > 2.4.1? Python 2.4 (#1, Mar 10 2005, 16:54:23) [C] on sunos5 Solaris 9 x86, forte 6.2 > 4. Do you get the same symptoms when you pass in a list instead of a > dict? What about a minimal user-created object? A list works fine, as does a 1 element tuple with a dict in it. I'm not sure what you mean by minimal user-created object. -Seth From ccurvey at gmail.com Tue Jun 7 07:47:53 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 7 Jun 2005 04:47:53 -0700 Subject: separate IE instances? In-Reply-To: References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> Message-ID: <1118144873.935177.287190@g43g2000cwa.googlegroups.com> Bummer. No change at all. (In fact, I can't even call Navigate() without throwing an error). I'm on win2k, if that makes any difference. From dave.benjamin at gmail.com Thu Jun 30 01:33:39 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Wed, 29 Jun 2005 22:33:39 -0700 Subject: Inheriting from object In-Reply-To: References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <1120081591.319266.10200@z14g2000cwz.googlegroups.com> Message-ID: Steven Bethard wrote: > Guido also suggests that the explicit: > > class C(object): > pass > > is "much preferred"[2] over: > > __metaclass__ = type > > class C: > pass Really? I have been toying with the idea of using the __metaclass__ trick, since it results in completely valid Jython 2.1 code, as long as you don't use any of the new-style features. But once Brian Zimmer gets his broadband fixed, we're supposed to get a new alpha release. =) Dave From skip at pobox.com Wed Jun 1 16:08:17 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Jun 2005 15:08:17 -0500 Subject: PySol not working on WinXP, SP2 In-Reply-To: <429DC8F7.38AFB2B5@pauahtun.org> References: <429DC8F7.38AFB2B5@pauahtun.org> Message-ID: <17054.5553.369830.823280@montanaro.dyndns.org> Ivan> I can't find any later version on google... It may not help you much, but I was able to get it working on MacOSX by grabbing the latest available source and tracking down the contents of the data directory via the Wayback Machine. If you'd like to give it a try (I'm not sure how you'd get sound stuff working - I'm not a Windows guy), let me know. Skip From scott at alussinan.org Wed Jun 22 13:18:23 2005 From: scott at alussinan.org (scott) Date: Wed, 22 Jun 2005 19:18:23 +0200 Subject: how to use more than 1 __init__ constructor in a class ? Message-ID: <42b99d7b$0$21804$626a14ce@news.free.fr> hi people, can someone tell me, how to use a class like that* (or "simulate" more than 1 constructor) : #-- class myPointClass: def __init__(self, x=0, y=0): self.x = x self.y = y def __init__(self, x=0, y=0, z=0): self.__init__(self, x, y) self.z = z #-- tia people scott *this is not homework From bogus@does.not.exist.com Thu Jun 30 09:55:02 2005 From: bogus@does.not.exist.com () Date: Thu, 30 Jun 2005 13:55:02 -0000 Subject: No subject Message-ID: #! rnews 2572 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Modules for inclusion in standard library? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 39 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <3ian37Fkjle0U1 at individual.net> <11c343ho6i6hv17 at news.supernews.com> <1x6lpi6z.fsf at python.net> <7xwtodvzsv.fsf at ruckus.brouhaha.com> <7x3br1ger1.fsf at ruckus.brouhaha.com> Mime-Version: 1.0 Date: Thu, 30 Jun 2005 13:38:28 GMT Xref: news.xs4all.nl comp.lang.python:384160 Paul Rubin writes: > Rocco Moretti writes: > > Except that (please correct me if I'm wrong) there is somewhat of a > > policy for not including interface code for third party programs which > > are not part of the operating system. (I.e. the modules in the > > standard libary should all be usable for anyone with a default OS + > > Python install.) > > I've never heard of Python having such a policy and I don't understand > how such a stupid policy could be considered compatible with a > proclaimed "batteries included" philosophy. Why would Python > advocates want to make Python deliberately uncompetitive with PHP, > Java, and other languages that do include database modules? > > > A notable exception is the dbm modules, but I seem to recall hearing > > that the official position is that it was a mistake. (Now only kept > > for backward compatability.) > > Ahem: Tkinter. There's actually several more, looking in the lib docs. I typically install dozens of python packages (on IRIX, Solaris, AIX, Linux, Win2K). 21 are standalone enough to be considered for the std library. However I wouldn't necessarily want them in there, because: a) They have their own release cycles, and coordinating would be too painful. We'd get a Python-1.2.3 with a package ABC-2.3.4 which is (too late) discovered to have a bug. So everyone would have to download ABC-2.3.5 and install it anyway. b) Installing distutils-aware python packages is trivial. I'd rather the energy which might go into a bigger std library go instead into helping projects which don't have distutils-style builds. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From fraca7 at free.fr Tue Jun 21 10:39:47 2005 From: fraca7 at free.fr (fraca7) Date: Tue, 21 Jun 2005 16:39:47 +0200 Subject: multi threading and win9x In-Reply-To: References: <42B7744D.8030601@open-networks.net> Message-ID: <42b826b3$0$24504$636a15ce@news.free.fr> Tim Peters a ?crit : > All versions of Windows >= Win95 use threads heavily, have very solid > thread support, and the Win32 API was thread-aware from the start > Thread _scheduling_ is pretty bizarre <= WinME, but process scheduling > is too. Don't try to use hundreds of threads <= WinME and you should > be fine. But note that Win95 has a system memory leak of about 5 Kb per thread, if I recall correctly... From nothingcanfulfill at gmail.com Fri Jun 24 14:21:28 2005 From: nothingcanfulfill at gmail.com (ncf) Date: 24 Jun 2005 11:21:28 -0700 Subject: Newbie question: how to keep a socket listening? In-Reply-To: References: Message-ID: <1119637288.536579.249340@z14g2000cwz.googlegroups.com> I think your problem /may/ be in the following line of code: sa.listen(1) I believe what's happening is that the listen() creates a decremental counter of the number of connections to accept. Once it decrements to 0, it won't accept any more connections. (I'm not at all sure, but that sounds like what it's doing.) One thing that I have noted is that once I am done with some internet program, the connection that program created is left in the waiting state. This might explain why, when you close your application and open it back up again a short amount of time later, the connection is refused. Another thought on this matter is that your end may be closing the connection, but the daemon end might not be closing the connection, so the listen counter may not increment back up to say "Hey, I'm available for another connection." Nevertheless, I'm also relatively new to Sockets, so my guess is probably just as good as your guess. :P (Hell, I couldn't get them fully right away, and read that it was easier to use asyncore.dispatcher for a daemon, so I'm using that!) If you find out the problem, please post it up here for all to learn from :) Oh, and just a suggestion, do something like a 'netstat -a -p --inet' on the daemon end. (Might not be the completely correct command =\) Hope that helps -Wes From reinhold-birkenfeld-nospam at wolke7.net Sun Jun 5 17:02:58 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 05 Jun 2005 23:02:58 +0200 Subject: mix up a string In-Reply-To: References: Message-ID: <3gh7k3Fce4qdU1@individual.net> rbt wrote: > What's the best way to take a string such as 'dog' and mix it up? You > know, like the word jumble in the papers? ODG. I thought something like > mix = random.shuffle('dog') would do it, but it won't. Any tips? py> def shuffled(s): ... l = list(s) ... random.shuffle(l) ... return ''.join(l) Reinhold From mandus at gmail.com Sat Jun 25 16:26:41 2005 From: mandus at gmail.com (Mandus) Date: Sat, 25 Jun 2005 20:26:41 +0000 (UTC) Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1119730516.936848.195640@f14g2000cwb.googlegroups.com> Message-ID: 25 Jun 2005 13:15:16 -0700 skrev Devan L: > But by using the builtin reduce, you need to specify a function, which > probably slows it down more than any speed-up from the loop in C. Sounds reasonable, but not always the case, especially when dealing with numpy arrays. At least that what some of my test shows. But then I should probably write c-functions that deals with the numeric arrays anyway. Besides, functions like 'operator.add' is also in c, maybe that helps. But I admit it's not a perfect example. -- Mandus - the only mandus around. From jjl at pobox.com Sun Jun 5 11:05:06 2005 From: jjl at pobox.com (John J. Lee) Date: 05 Jun 2005 15:05:06 +0000 Subject: method = Klass.othermethod considered PITA References: <87oeallp44.fsf@pobox.com> Message-ID: <87acm4lu8t.fsf@pobox.com> Jeff Epler writes: > On Sat, Jun 04, 2005 at 10:43:39PM +0000, John J. Lee wrote: > > 1. In derived classes, inheritance doesn't work right: > > Did you expect it to print 'moo'? I'd have been surprised, and expected > the behavior you got. Me too. It's at the time of *writing* the code, before the subclass even exists, that the problem can arise, if you're not thinking about derivation. Sure, if you're not thinking about derivation, you have many other problems when somebody starts deriving from you, but, well, here's another issue to remember. Fine once you've noted this particular wrinkle, I suppose. And, looking again at another use case (in urllib2, the http_error_30* methods) I guess it's true that there are cases where methods are really distinct but merely happen to have the same implementation, so that method2 = method1 is actually what you want, hence better than a trivial method definition. > > 2. At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do > > this. > > In all the versions of Python I've used, classes are pickled by name. > This example you wrote doesn't pose any special problem when pickling. > > >>> pickle.dumps(A) > 'c__main__\nA\np0\n.' > >>> pickle.dumps(B) > 'c__main__\nB\np0\n.' I meant class instances. John From fuzzyman at gmail.com Fri Jun 17 07:24:02 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Jun 2005 04:24:02 -0700 Subject: log in to a website In-Reply-To: <1118942713.133261.258480@o13g2000cwo.googlegroups.com> References: <1118942713.133261.258480@o13g2000cwo.googlegroups.com> Message-ID: <1119007442.798844.149560@z14g2000cwz.googlegroups.com> passion_to_be_free at hotmail.com wrote: > I'm learning python, and my goal is to write a script that will log > into a website for me. The site uses HTTPS, the form uses the "POST" > method. > > >From what I've been able to find so far, it looks like i need to use > the urllib2 module...does anyone know where I can find some good sample > code to read up on how to do this? > > -Thx Is it just BASIC authentication ? (http error code 401). Clientform is still worth investigating - but if you want help on BASIC authentication then checkout http://www.voidspace.org.uk/python/articles/authentication.shtml Best Regards, Fuzzyman http://www.voidspace.org.uk/python From frankabel at tesla.cujae.edu.cu Mon Jun 6 13:21:30 2005 From: frankabel at tesla.cujae.edu.cu (Frank Abel Cancio Bello) Date: Mon, 6 Jun 2005 13:21:30 -0400 Subject: About size of Unicode string Message-ID: <20050606171706.8E22C3181AA@newton.cujae.edu.cu> Hi all! I need know the size of string object independently of its encoding. For example: len('123') == len('123'.encode('utf_8')) while the size of '123' object is different of the size of '123'.encode('utf_8') More: I need send in HTTP request a string. Then I need know the length of the string to set the header "content-length" independently of its encoding. Any idea? Thanks in advance Frank From newsgroups at jhrothjr.com Mon Jun 27 10:21:41 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 27 Jun 2005 08:21:41 -0600 Subject: Beginner question: Converting Single-Element tuples to list References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <3i9jdvFkhd21U1@individual.net> Message-ID: <11c02rpkqriad6c@news.supernews.com> "Reinhold Birkenfeld" wrote in message news:3i9jdvFkhd21U1 at individual.net... > vdavidster at gmail.com wrote: >> Hi, >> >> Thanks for your reply! A new thing learned.... >> >> Allow me to follow that up with another question: >> >> Let's say I have a result from a module called pyparsing: >> >> Results1 = ['abc', 'def'] >> Results2 = ['abc'] >> >> They are of the ParseResults type: >> >>>>> type(Results1) >> >>>>> type(Results2) >> >> >> I want to convert them into Python lists. list() will work fine on >> Results1, but on Results2, it will return: >> >> ['a', 'b', 'c'] >> >> Because 'abc' is a string. But I want it to return ['abc']. >> >> In short, my question is: how do I typecast an arbitrary object, >> whether a list-like object or a string, into a Python list without >> having Python split my strings into characters? > > This seems like a glitch in pyparsing. If a ParseResults class emulates > a list, it should do so every time, not only if there is more than one > value in it. Unfortunately, I've seen that behavior a number of times: no output is None, one output is the object, more than one is a list of objects. That forces you to have checks for None and list types all over the place. Granted, sometimes your program logic would need checks anyway, but frequently just returning a possibly empty list would save the caller a lot of grief. John Roth > > Reinhold From rkern at ucsd.edu Tue Jun 28 18:54:47 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 28 Jun 2005 15:54:47 -0700 Subject: Modules for inclusion in standard library? In-Reply-To: <1119997687.419539.119120@g14g2000cwa.googlegroups.com> References: <3ian37Fkjle0U1@individual.net> <1119901432.218536.289030@g47g2000cwa.googlegroups.com> <42c1662d$0$26260$626a14ce@news.free.fr> <1119977801.449923.128330@o13g2000cwo.googlegroups.com> <3idp5uFkua1fU1@individual.net> <1119997687.419539.119120@g14g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > "Reinhold Birkenfeld" wrote: >>For an easy, quick interactive interpreter, it's way to overloaded >>with functions and too slow in startup. > > Too slow ? It doesn't take more than a second or two to startup in a > two years old 1.8Ghz Athlon and an older 900Mhz sparcv9 I usually work > on. How slow is it at platforms you have experience with ? I think that it loads up too much stuff to be the default interpreter, speed issues aside. Sometimes, you really need to debug something that requires you to control the imports. It's a moot point anyways. The current ipython codebase isn't in any shape to go into the stdlib, and the rewrite hasn't quite begun, yet. Ask again in a year or two. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tdelaney at avaya.com Sun Jun 12 19:36:58 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 13 Jun 2005 09:36:58 +1000 Subject: Controlling a generator the pythonic way Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025205A2@au3010avexu1.global.avaya.com> Thomas Lotze wrote: > call. The picture might fit better (IMO) if it didn't look so much > like working around the fact that the next() call can't take > parameters for some technical reason. You might want to take a look at PEP 342 . Doesn't help you now, but it will in the future. Tim Delaney From mhoy4 at cox.net Fri Jun 10 15:23:15 2005 From: mhoy4 at cox.net (Mike Hoy) Date: Fri, 10 Jun 2005 12:23:15 -0700 Subject: try: except: ValueError In-Reply-To: <42a9d311$1_2@newspeer2.tds.net> References: <42a9d311$1_2@newspeer2.tds.net> Message-ID: <1118431395.6123.12.camel@laptop.solodiver> > The solution is to use raw_input() which returns the user input as a string. Then you can do whatever validation you wish, e.g. > menuChoice = int(raw_input("1 = write | 2 = view | 0 = quit")) > which will raise an exception if the input is not a valid integer. yes that did it, thanks From twic at urchin.earth.li Sat Jun 11 18:51:30 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Sat, 11 Jun 2005 23:51:30 +0100 Subject: What is different with Python ? In-Reply-To: References: Message-ID: On Sat, 11 Jun 2005, Philippe C. Martin wrote: > Yet for the first time I get (most) of my questions answered by a > language I did not know 1 year ago. Amazing, isn't it? Rest assured that you're not alone in feeling this way. I don't know quite why, but python is just makes writing programs immensely easier than any other language i've ever used; i think it's the very minimal amount of boilerplate it requires, the clean and powerful set of builtin types and functions and, for me, the higher-order functions. I can do in a few lines of python what would have taken me pages and pages of java. tom PS: http://jove.prohosting.com/~zahlman/cpp.html -- Jim-Jammity Jesus Krispy Kreme Christ on a twat-rocket! From steve at REMOVEMEcyber.com.au Fri Jun 24 00:19:06 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Fri, 24 Jun 2005 14:19:06 +1000 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118255048.849018.259500@g14g2000cwa.googlegroups.com> Message-ID: <42BB89BA.8010902@REMOVEMEcyber.com.au> Max wrote: > Jordan Rastrick wrote: >> Well, never, ever use equality or inequality operations with floating >> point numbers anyway, in any language, as they are notoriously >> unreliable due to the inherent inaccuracy of floating point. Thats >> another pitfall, I'll grant, but its a pretty well known one to anyone >> with programming experience. So I don't think thats a major use case. > > I think this is referring to IEEE 754's NaN equality test, which > basically states that x==x is false if-and-only-if x.isNaN() is true. No. He means exactly what he says: when using floats, it is risky to compare one float to another with equality, not just NaNs. This is platform-dependent: I remember the old Standard Apple Numerics Environment" (SANE) making the claim that testing equality on Macintoshes was safe. And I've just spent a fruitless few minutes playing around with Python on Solaris trying to find a good example. So it is quite possible to work with floats for *ages* before being bitten by this. In general, the problem occurs like this: Suppose your floating point numbers have six decimal digits of accuracy. Then a loop like this may never terminate: x = 1.0/3 while x != 1.0: # three times one third equals one print x x += 1.0/3 It will instead print: 0.333333 0.666666 0.999999 1.333332 1.666665 and keep going. (You can easily see the result yourself with one of those cheap-and-nasty calculators with 8 significant figures. 1/3*3 is not 1.) It is a lot harder to find examples on good, modern systems with lots of significant figures, but it can happen. Here is a related problem. Adding two floats together should never give one of the original numbers unless the other one is zero, correct? Then try this: py> x = 1.0 py> y = 1e-16 # small, but not *that* small py> y == 0.0 False py> x+y == x True py> x-x+y = x+y-x False (Again, platform dependent, your milage may vary.) Or try the same calculations with x=1e12 and y=1e-6. In general, the work-around to these floating point issues is to avoid floating point in favour of exact algebraic calculations whenever possible. If you can't avoid floats: - always sum numbers from smallest to largest; - never compare equality but always test whether some number is within a small amount of your target; - try to avoid adding or subtracting numbers of wildly differing magnitudes; and - be aware of the risk of errors blowing out and have strategies in place to manage the size of the error. -- Steven. From mcherm at mcherm.com Fri Jun 10 15:56:15 2005 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 10 Jun 2005 12:56:15 -0700 Subject: using python from c/c++ Message-ID: <20050610125615.oymplav2mj48g8wc@login.werra.lunarpages.com> alexandr writes: > Is it possible to create a library from my python module that can be > used from c/c++ application? Yes... the only question is how difficult it is. The basic idea is that you create a library containing Python that contains a hard-coded copy of your python script (or which reads it from a file). The basics of doing this are described here: http://docs.python.org/ext/ext.html ... it's not too difficult, but it's certainly not automated. Of course, there's not much gain over simply invoking the python interpreter with the correct command line options... the "unix way" (programs invoking other programs as command line utilities) is very powerful. What would be quite nice would be a sort of inverse to SWIG... a tool to mechanically create C wrappers around a Python program. I haven't heard of such a beast, but perhaps someone else will write in to point one out. -- Michael Chermside From tjreedy at udel.edu Sat Jun 25 21:11:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Jun 2005 21:11:27 -0400 Subject: A strange and annoying restriction, possibly a bug. A glance by amore experienced would be nice. References: <42BDD500.4060303@jippii.fi> Message-ID: "Elmo M?ntynen" wrote in message news:42BDD500.4060303 at jippii.fi... >>>> n=(100,) tuple(*n) As posted, this gives a syntax error. What is missing? tjr From johnandsarah at estragon.freeserve.co.uk Sun Jun 19 10:58:52 2005 From: johnandsarah at estragon.freeserve.co.uk (John Perks and Sarah Mount) Date: Sun, 19 Jun 2005 15:58:52 +0100 Subject: "static" data descriptors and possibly spurious calls to __set__? Message-ID: I have a peculiar problem that, naturally, I cannot reproduce outside the fairly long-winded code that spawned it. Thus the code snippets here should be taken as shorthand for what I think are the relevant bits, without actually leading to the erroneous (or at least undesired) behaviour described. The problem is that, in attempting to add an attribute to a subclass, a synonymous attribute in the base class is looked up instead, and its __set__ method invoked. The actual setting is done via type.__setattr__(cls, attr, value). The question is, under what circumstances can an attempt to add an attribute to a derived class be interpreted as setting a descriptor of the same name in the base class, and how (under those circumstances) can one coax the desired behaviour out of the interpreter? It's no good just stipulating that the derived classes are populated first to avoid this sort of name-shadowing, as new classes will be dynamically discovered by the user, and anyway existing classes can be repopulated by the user at any time. This slightly contrived example comes about in part from a need to have "static" data descriptors, where an assignment to the descriptor via the class (as opposed to via an instance), result in a call to its __set__, rather than replacing the descriptor in the class's __dict__. (If you really wanted to replace the descriptor, you'd have to del it explicitly before assigning to the attribute, and this is in fact done elsewhere in the code where needed.) I do this by having a special metaclass whose __setattr__ intercepts such calls: class Meta(type): def __setattr__(self, attr, value): if attr not in self.__dict__ or isSpecial(attr): # the usual course of action type.__setattr__(self, attr, value) else: self.__dict__[attr].__set__(None, value) (The isSpecial() function checks for __special_names__ and other things that should be hadled as normal). I've subsequently found that applications such as jpype have successfully used this approach, so it doesn't seem to be a bad idea in itself. Then, if we have a descriptor... class Descr(object): def __get__(self, inst, owner=None): print "Getting!", self, inst, owner return 17 def __set__(self, inst, value): print "Setting", self, inst, value ...and then we have a (dynamically-created) class heirarchy... Base = Meta('Base', (), {}) Derived = Meta('Derived', (Base,), {}) ...then we (dynamically) assign a static descriptor to Base... setattr(Base, 'x', Descr()) ...and then to Derived... setattr(Derived, 'x', Descr()) ...it's this last one that causes the problem. In the real code, the call to type.__setattr__ referred to above seems to lead to a call to something like cls.__base__.__dict__[attr].__set__(cls, value). It doesn't appear possible to recover from this from within the descriptor's __set__ itself, as any attempt to set the class attribute from there naturally leads to recursion. I can't set the class's __dict__ directly, as it's a dictproxy and only exposes a read-only interface (why is that, by the way?). One further factor that may be relevant (though I couldn't see why), is that the metaclass in question is set up (via __class__ reassignment) to be an instance of itself, like the builtin type. Any enlightenment on this matter would be gratefully received. Thanks John. From Jon_Slaughter at Hotmail.com Sat Jun 11 02:22:28 2005 From: Jon_Slaughter at Hotmail.com (Jon Slaughter) Date: Sat, 11 Jun 2005 01:22:28 -0500 Subject: Best Web dev language Message-ID: <11al0nhr4opfgaa@corp.supernews.com> I'm trying to get into web development for creating a professional web site and I'm confused on which language I should use. I've read some comparisons between the major languages and I was thinking that python might be the way to go for the most powerful and general language but I am not sure. Does anyone know of any detailed and objective comparisons between the major languages(perl, php, java, javascript, etc...) that might help me get a clearer picture? I have some experience with C/C++ but it has been some time since I have done any real programming... I'd prefer to use C++ style so I would no thave to learn a new language completely. I've also read that one can use C/C++ to develop just as one would use any other language and I'm wondering if this is advisable? (since it seems most web pages are done in perl, python, or php?) Also, can anyone recommend any book or web page that gives an introduction to the method in which one programs web sites? I am not clear on who one, for instance, would use C++ as the language for a web site except by using it to create html... I'm not sure if basicaly all languages goal is creating html dynamically or if there is more to do. What I mean is that basicaly one is using some other language to wrap the html code or possibly generate it at run-time for dynamic results. (so all client based web interfaces are really just html readers but all this "extra" stuff is used to make certain things easier and dynamic(just as generating tables and forms and all that). Thanks for any help, Jon From prashanthellina at gmail.com Tue Jun 7 09:28:33 2005 From: prashanthellina at gmail.com (Prashanth Ellina) Date: 7 Jun 2005 06:28:33 -0700 Subject: How do I know when a thread quits? Message-ID: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> Hi, I have used the low-level thread module to write a multi-threaded app. tid = thread.start_new_thread(process, ()) tid is an integer thread ident. the thread takes around 10 seconds to finish processing. Meanwhile the main thread finished execution and exits. This causes an error because the child thread tries to access something in the sys module which has already been GC'ed. I want a reliable way of knowing when the child thread finished execution so that I can make the main thread wait till then. Any ideas? TIA, Prashanth Ellina From jrastrick at student.usyd.edu.au Wed Jun 8 14:44:43 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 8 Jun 2005 11:44:43 -0700 Subject: Annoying behaviour of the != operator In-Reply-To: References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> Message-ID: <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Just because a behaviour is documented, doesn't mean its not counter intutitive, potentially confusing, and unnessecary. I have spent a fair amount of time reading the Python docs. I have not yet memorised them. I may have read this particular section of the reference manual, or I may have not, I can't remember. This is the first time I've had cause to override the __eq__ operator, and so the first time I've encountered the behaviour in a concrete setting, which I feel is a far more effective way to learn than to read all the documentation cover to cover. Where are the 'number of situations' where __ne__ cannot be derived from __eq__? Is it just the floating point one? I must admit, I've missed any others. And no, I don't think I really want Python to assume anything much - explicit is better than implicit after all. If I don't override __eq__, or __gt__, or __cmp__, i certainly don't expect Python to infer the behaviour I want. But I explicitly provided a method to test equality. And look at the plain english meaning of the term "Not equals" I think its pretty reasonable As far as __gt__, __lt__, __ge__, and the rest go, the answer is simple. Anyone defining things the 'obvious' way would override __cmp__, and sidestep the whole issues. Those who want the less obvious behaviour of can provide it explicitly. But as PEP207 says, you shouldn't have to override cmp if you don't want to provide an arbitrary ordering. And its the people doing the non-obvious thing, having __ne__ and __eq__ inconsistent, who should have to code it and state it explicitly. If want an orderable object, I'll just define __cmp__. If I want an equal-comparable object, I should just be able to define __eq__. If I want anything fancy, I can go ahead and explicitly write methods for __gt__, __ne__, etc. From tim.golden at viacom-outdoor.co.uk Thu Jun 23 09:46:54 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Jun 2005 14:46:54 +0100 Subject: Single Application Instance Example Message-ID: <9A28C052FF32734DACB0A288A3533991EBB92E@vogbs009.gb.vo.local> [DeRRudi] | | Whit this mutex is it possible when an instance is running in | background and you try to open a new instance. you cancel it and show | the first? | | Greetz All the Mutex is doing is providing a single token which only one instance of the app can hold at a time. Of itself, it doesn't provide any facility to awake background applications or do anything at all except exclude other apps from holding the same token. What you describe could be achieved a number of ways. (He says, sounding knowledegeable, but having little real experience to back himself up). Once the Mutex check proves that you're not the only instance running, you could, for example, find the top-level window of your app and activate it (assuming it has a window). You could embed some sort of mini-messaging within the application, say a small Pyro class, or a socket server, or a Windows pipe, or whatever, which will let your second instance send a message to the first which will then activate (whatever that means). In fact, you could probably combine the two by using a private Windows pipe which would both serve as a "anyone else here?" check and as a signal to an existing instance to wake up and dance. It all depends on what the app is doing, and how hard you want to try. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From philippe at philippecmartin.com Fri Jun 10 13:42:57 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 10 Jun 2005 17:42:57 GMT Subject: Release announcement Message-ID: Dear all, I am very happy to anounce the release of SnakeCard's School-ID, a school/university Smart Card based security solution that can be extended using Python or other languages that can "talk" to Python modules. The current release includes the following features: Student/Faculty Identification Data Security File Encryption PC Access E-purse Network Integration Grade Book Management Library Books Checkout Management Attendance Management Report Card Management Health/Emergency Information Retrieval The card can also be extended to areas such as web and building security. I invite you to look at the online presentations of the features at http://www.snakecard.com/page2.html where you may also download the brochure. Best regards, Philippe From steve at holdenweb.com Fri Jun 3 05:31:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Jun 2005 05:31:44 -0400 Subject: Simple Kiosks Serve The World In-Reply-To: References: <429e7155.6739473@news.alphalink.com.au> Message-ID: jabailo at texeme.com wrote: > Jeff_Relf wrote: > > >>As I've told you a quintillion times, Earthlink's insanity aside, >>Win_XP is a virtual network, quite indepent of the connection used. >>Linux is hardly an OS, it's just a kernel. > > > The world doesn't need a 'virtual network'...it needs an Internet Kiosk. > > While Jeff the Bolshevik was sleeping; American Capitalism produced what the > Governments of India, Africa and China could not: A $69 Internet Kiosk from > which they can derive Knowledge, Commerce and Society. > > Yes, listen here World Bank, Unicef, UN, Bono, Gate$ Foundation: > > Do you want the world to have computers? > > Then cough up $69 a head to Microtek and have them send it Ground Freight to > Burkina Faso, Outer Mongolia and Bangalore. > > As for 'virtual networks' -- yes, virtual in the sense of not being > real...in the sense of not having substance. Yes. virtual. > Since this appears to have nothing at all to do with Python, perhaps you guys could go and fight in some other corner of the playground? heard-it-all-before-ly y'rs - steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From skip at pobox.com Fri Jun 17 07:29:03 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 17 Jun 2005 06:29:03 -0500 Subject: PEP 304 "Controlling Generation of Bytecode Files" - patch updated In-Reply-To: References: Message-ID: <17074.46079.101393.509174@montanaro.dyndns.org> Skip> http://python.org/sf/677103 Thomas> There's no patch attached. *sigh* Thanks for noticing the problem. Apparently, since I last updated the patch, SF implemented a 250kbyte limit on file uploads. This one is big because it includes a suitably modified configure script that was generated with a slightly different version of autoconf than what's in the current Python distro so people don't need to have autoconf installed to work with the patch. I've attached a gzipped version of the patch (bcb.diffs.gz). Skip From percivall at gmail.com Fri Jun 3 03:47:13 2005 From: percivall at gmail.com (Simon Percivall) Date: 3 Jun 2005 00:47:13 -0700 Subject: PYTHONSTARTUP and the -i command line option In-Reply-To: References: Message-ID: <1117784833.435671.94380@z14g2000cwz.googlegroups.com> After entering the interpreter, you could do an execfile on the .pythonrc file. From greg at cosc.canterbury.ac.nz Wed Jun 8 22:37:53 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 14:37:53 +1200 Subject: Writing func_closure? In-Reply-To: References: Message-ID: <3gpocfFcqskgU1@individual.net> Fernando Perez wrote: > I can reuse the closure from a different > function, but the docs don't say how to make a valid closure tuple. This is > the typical problem of the stdlib docs, which under-specify what is supposed to > go into a call and don't give at least a specific example. As far as I know, there is currently no supported way of directly creating or modifying cell objects from Python; it can only be done by some obscure trickery. So the docs are telling the truth here, in a way. :-) -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From andreas at kostyrka.org Wed Jun 22 05:03:27 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 22 Jun 2005 11:03:27 +0200 Subject: Embedding Python - Deleting a class instance In-Reply-To: References: Message-ID: <20050622090327.GB32017@heaven.kostyrka.org> On Tue, Jun 21, 2005 at 12:06:47PM +0000, Bue Krogh Vedel-Larsen wrote: > How do I delete a class instance created using PyInstance_New? I've tried > calling Py_CLEAR on the instance, but __del__ isn't called. I've also tried > calling PyObject_Del, but this gives an access violation in > _PyObject_DebugDumpAddress so I guess that ain't a good idea :) > > I've noticed that the PyObject returned by PyInstance_New has refcount = 2, > does this have any significance? Well, the only way to do that is to call PyDECREF. And this is only legal when you really remove the reference, or else you get dangling pointers which will lead to a corrupted heap and/or segfault somewhere in the future of your program. Andreas From kaka.hui at gmail.com Mon Jun 20 19:56:54 2005 From: kaka.hui at gmail.com (Cathy Hui) Date: 20 Jun 2005 16:56:54 -0700 Subject: Install MySQL-python-0.9.1 Message-ID: <1119311814.780099.296440@f14g2000cwb.googlegroups.com> I am trying to install MySQL-Python 0.9.1 on my Solaris 8 system. The system has Python 2.3.3 and Mysql 4.0.21 installed. This is where I downloaded the distribution of the Mysql-python package: http://www.ravenbrook.com/project/p4dti/import/2001-10-16/MySQL-python-0.9.1/MySQL-python-0.9.1.tar.gz I have been doing whatever instructed from the README file. i.e. change the setup.py according to what OS I'm using: elif sys.platform == "sunos5": # Solaris 2.8 include_dirs = ['/usr/local/mysql/include/mysql'] library_dirs = ['/usr/local/mysql/lib/mysql'] libraries = [mysqlclient, "z"] runtime_library_dirs = ['/usr/local/lib:/usr/openwin/lib:/usr/dt/lib'] extra_objects = [] Then run the setup.py script with Python, here is the problem. I am encountering the following issue when running the setup.py script. Do u know why is that? Thanks! ====================================================================== python setup.py build Traceback (most recent call last): File "setup.py", line 123, in ? extra_objects=extra_objects, File "/usr/local/lib/python2.3/distutils/core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "/usr/local/lib/python2.3/distutils/dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' python setup.py install Traceback (most recent call last): File "setup.py", line 123, in ? extra_objects=extra_objects, File "/usr/local/lib/python2.3/distutils/core.py", line 101, in setup _setup_distribution = dist = klass(attrs) File "/usr/local/lib/python2.3/distutils/dist.py", line 130, in __init__ setattr(self, method_name, getattr(self.metadata, method_name)) AttributeError: DistributionMetadata instance has no attribute 'get___doc__' From dalke at dalkescientific.com Sat Jun 4 13:59:27 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 04 Jun 2005 17:59:27 GMT Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: On Sat, 04 Jun 2005 10:43:48 -0600, Steven Bethard wrote: > Ilpo Nyyss?nen wrote: >> How about this instead: >> >> with locking(mutex), opening(readfile) as input: >> ... > I don't like the ambiguity this proposal introduces. What is input > bound to? It would use the same logic as the import statement, which already supports an 'as' like this >>> import sys, math, cStringIO as StringIO, xml.sax.saxutils as su >>> > But the point is > that, whatever decision you make, I now have to *memorize* that decision. It's the same rule so the rule would be "ahh, uses the 'as' form". Andrew dalke at dalkescientific.com From nnorwitz at gmail.com Thu Jun 2 09:46:47 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 2 Jun 2005 06:46:47 -0700 Subject: any macro-like construct/technique/trick? References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> <1117676088.978273.272940@g47g2000cwa.googlegroups.com> <1117680577.332110.241060@g47g2000cwa.googlegroups.com> Message-ID: <1117720007.261053.48380@g47g2000cwa.googlegroups.com> Andrew's approach is good, but you could so something a little simpler/more flexible. Untested of course. :-) Every callable object is followed by the args to pass it. So this: debug_emit(DbgObjFoo(a, b, costly_function(c))) becomes: debug_emit(DbgObjFoo, (a, b, costly_function, (c,))) def debug_emit(*args): if not debug: return # assume last arg is not a callable and skip it i = len(args) - 2 while i > 0: if callable(args[i]): # call it! assume the next arg is a tuple of params new_value = args[i](*args[i+1]) args = args[:i] + (new_value,) + args[i+2:] emit_dbg_code(*args) cheers, n From tzot at sil-tec.gr Tue Jun 28 11:52:29 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 28 Jun 2005 18:52:29 +0300 Subject: What is different with Python ? (OT I guess) References: <42AED7B3.8060009@carmen.se> <6kh2c151vvhda93jghhm8qcrf9v64llf7t@4ax.com> Message-ID: On Tue, 28 Jun 2005 15:46:01 +0300, rumours say that Christos "TZOTZIOY" Georgiou might have written: >(kudos to Steve Holden for >mailman.1390.1112714031.1799.python-list at python.org where the term PIPO >(Poetry In, Poetry Out) could be born) oops! kudos to Michael Spencer (I never saw Michael's message on my newsserver, so I archived Steve's). -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From nidoizo at yahoo.com Mon Jun 27 23:14:09 2005 From: nidoizo at yahoo.com (Nicolas Fleury) Date: Mon, 27 Jun 2005 23:14:09 -0400 Subject: Better console for Windows? In-Reply-To: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: Brett Hoerner wrote: > This is a pretty basic, mostly un-python-related question, although I'm > asking because of Python. > > Is there a different shell I can use (other than cmd.com) to run Python > in, where I can full-screen the window (if I pleased), etc? As it is, > things that would run far off the right have to be word wrapped after > very few characters. I don't know if you absolutely want a shell, but if what you want is a Python interactive prompt, I find PyShell coming with wxPython really nice. It has autocompletion and support copy-paste with/without the preceding >>>. Regards, Nicolas From thomas at thomas-lotze.de Mon Jun 13 20:56:27 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Tue, 14 Jun 2005 02:56:27 +0200 Subject: Controlling a generator the pythonic way References: Message-ID: Thomas Lotze wrote: > I'm trying to figure out what is the most pythonic way to interact with a > generator. JFTR, so you don't think I'd suddenly lost interest: I won't be able to respond for a couple of days because I've just incurred a nice little hospital session... will be back next week. -- Thomas From sxanth at ceid.upatras.gr Tue Jun 21 11:21:50 2005 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Tue, 21 Jun 2005 18:21:50 +0300 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <42B8308E.8050000@ceid.upatras.gr> Magnus Lycka wrote: > Konstantin Veretennicov wrote: > >> On 6/21/05, Magnus Lycka wrote: >> >>> I don't know anything about the Python compiler internals, >>> but it doesn't seem very hard to identify simple literals following >>> while and if, and to skip the runtime test. (Perhaps it's done >>> already?) >> >> >> >> True doesn't seem to be a literal, it is looked up by name and can be >> rebound to, say, 0 anytime: > > > Right. Silly me. Maybe in some future Python version, True and False > will be constants, like None is since Python 2.4. Actually, there is support in marshal to write True and False objects so I don't understand why this isn't in 2.4 Anyway, if you can't wait for 2.5 either use 'while 1:', or pyc[1] Stelios [1] http://students.ceid.upatras.gr/~sxanth/pyc/ From anonymousnerd at gmail.com Sat Jun 25 01:41:00 2005 From: anonymousnerd at gmail.com (anonymousnerd at gmail.com) Date: 24 Jun 2005 22:41:00 -0700 Subject: How does one write a function that increments a number? References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> <1119676986.613202.315140@g47g2000cwa.googlegroups.com> Message-ID: <1119678060.774799.244920@g43g2000cwa.googlegroups.com> Wait... so this means it is impossible to write a function that increments an integer without turning the integer into a list? From lycka at carmen.se Tue Jun 14 13:29:17 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 14 Jun 2005 19:29:17 +0200 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42aeeee1$1@nntp0.pdx.net> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <42AED7B3.8060009@carmen.se> <42aeeee1$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Magnus Lycka wrote: > >> It seems to me that *real* computer scientists are very rare. > > I suspect the analysis of algorithms people are among that group. > It is intriguing to me when you can determine a lower and upper > bound on the time for the best solution to a problem relatively > independent of the particular solution. On the other hand, you could argue that algorithms and mathematics are branches of philosophy rather than science. :) Very useful for science, just as many other parts of philosophy, but algorithms are really abstract concepts that stand on their own, regardless of the physical world. But perhaps that distinction is fuzzy. After all, all philosophical theories rest on observations of the world, just as scientific theories. Hm...we're really far off topic now. From duncan.booth at invalid.invalid Wed Jun 22 04:51:07 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jun 2005 08:51:07 GMT Subject: tree functions daily exercise: Table References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> <1119357221.467207.149480@f14g2000cwb.googlegroups.com> <1119389873.409227.225680@f14g2000cwb.googlegroups.com> Message-ID: Duncan Booth wrote: > Ok, so, if I understand you, the definition of Table is just: > > def Table(f, *lists): > return Outer(f, > *[range(start,end+1,step) for (start,end,step) in lists]) > > Is that about right? > And lest you think I left a bit too much as an "exercise for the reader": -------------- xah.py -------------------- def Table(f, *lists): """Xah Lee's Table function >>> Table(f,[3,10,2]) [f(3), f(5), f(7), f(9)] >>> Table(f,[1,2,1],[2,6,2]) [[f(1, 2), f(1, 4), f(1, 6)], [f(2, 2), f(2, 4), f(2, 6)]] """ return Outer(f, *[range(start,end+1,step) for (start,end,step) in lists]) def explode(lists): """Form all combinations of 1 element from each list. >>> explode([[1,2], [3]]) [(1, 3), (2, 3)] >>> explode([[1,2], [3,4]]) [(1, 3), (1, 4), (2, 3), (2, 4)] >>> explode([[1,2], [3,4], [5]]) [(1, 3, 5), (1, 4, 5), (2, 3, 5), (2, 4, 5)] """ result = [()] for l in lists[::-1]: result = [ (val,) + tail for val in l for tail in result ] return result def groupsOfN(it, n): """Returns tuples of length n taken from it. >>> groupsOfN(range(12), 3) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)] >>> groupsOfN(range(12), 1) [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,), (10,), (11,)] """ it = iter(it) return zip(*([it]*n)) def Outer(f, *lists): """ >>> Outer(f, range(1,3), range(2,7,2)) [[f(1, 2), f(1, 4), f(1, 6)], [f(2, 2), f(2, 4), f(2, 6)]] """ result = [f(*args) for args in explode(lists)] for l in lists[:0:-1]: result = [list(v) for v in groupsOfN(result, len(l))] return result def _test(): global f class f: def __init__(self, *args): self.args = args def __repr__(self): if len(self.args) == 1: return "%s(%r)" % (self.__class__.__name__.split('.')[-1], self.args[0]) else: return "%s%r" % (self.__class__.__name__.split('.')[-1], self.args) import doctest doctest.testmod() if __name__ == "__main__": _test() ------------------------------------------ From tjreedy at udel.edu Sat Jun 11 15:16:07 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 11 Jun 2005 15:16:07 -0400 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> Message-ID: "Terry Hancock" wrote in message news:200506102209.49469.hancock at anansispaceworks.com... > http://naeblis.cx/rtomayko/2005/05/28/ibm-poop-heads > > which is probably what you meant. Thanks for digging this up. It solidified my understanding of why LAMP. TJR From spam.csubich+block at block.subich.spam.com Wed Jun 8 17:13:28 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 17:13:28 -0400 Subject: Fast text display? In-Reply-To: <7xll5ka7mv.fsf@ruckus.brouhaha.com> References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> <7xll5ka7mv.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > No, it's a big pain. I'm a big boy and gave up on trying to install > wxpython for bittorrent on FC3 (the problem was with wxwidgets needing > an obsolete version of gtk, not with wxpython itself). There's just > no compelling reason to want to deal with this stuff. Tkinter has its > warts but it allows making functional gui's without all that much > fuss. If it were replaced in the default distro then I'd say use > whatever the new default is, but as it is, it's best to not impose > unnecessary extra headache on users. Fair enough. At the moment, the expected user base for the program is exactly one, but making it easy has its advantages. Since you've obviously used it yourself, if I end up going with tkinter, are there any performance gotchas on text rendering that I should be aware of? From agriff at tin.it Tue Jun 14 15:39:37 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 14 Jun 2005 19:39:37 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118734620.851366.291360@f14g2000cwb.googlegroups.com> Message-ID: On 14 Jun 2005 00:37:00 -0700, "Michele Simionato" wrote: >It looks like you do not have a background in Physics research. >We *do* build the world! ;) > > Michele Simionato Wow... I always get surprises from physics. For example I thought that no one could drop confutability requirement for a theory in an experimental science... I mean that I always agreed with the logic principle that unless you tell me an experiment whose result could be a confutation of your theory or otherwise you're not saying anything really interesting. In other words if there is no means by which the theory could be proved wrong by an experiment then that theory is just babbling without any added content. A friend of mine however told me that this principle that I thought was fundamental for talking about science has indeed been sacrified to get unification. I was told that in physics there are current theories for which there is no hypotetical experiment that could prove them wrong... (superstrings may be ? it was a name like that but I don't really remember). To me looks like e.g. saying that objects are moved around by invisible beings with long beards and tennis shoes and that those spirits like to move them under apparent laws we know because they're having a lot of fun fooling us. However every now and then they move things a bit differently just to watch at our surprised faces while we try to see where is the problem in our measuring instrument. My temptation is to react for this dropping of such a logical requirement with a good laugh... what could be the result of a theory that refuses basic logic ? On a second thought however laughing at strange physics theories is not a good idea. Especially if you live in Hiroshima. Andrea From richardlewis at fastmail.co.uk Fri Jun 3 12:13:16 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Fri, 03 Jun 2005 17:13:16 +0100 Subject: minidom Node to Element In-Reply-To: <1117814857.13561.235587400@webmail.messagingengine.com> References: <1117814857.13561.235587400@webmail.messagingengine.com> Message-ID: <1117815196.14036.235588083@webmail.messagingengine.com> Hang on! It *knows*! Wow, you can call getElementsByTagName() on a Node object and it does the right thing. Weird, but I like it! Very Python! R. On Fri, 03 Jun 2005 17:07:37 +0100, "Richard Lewis" said: > Hey, > > Can I convert an xml.dom.Node object to an xml.dom.Element object? I > want to do the conversion inside a condition like this: > > if node.nodeType == Node.ELEMENT_NODE: > # do conversion: > element = Element(node) > element = node.toElement() > > so it definitely won't cause problems. I just can't find a way to do it! > > (I want to be able to call getElementsByTagName() on the resultant > object; any other workarounds which allow the same functionality would > be just as cool ;-) > > Cheers, > Richard > -- > http://mail.python.org/mailman/listinfo/python-list From ccurvey at gmail.com Sat Jun 4 18:17:28 2005 From: ccurvey at gmail.com (Chris Curvey) Date: 4 Jun 2005 15:17:28 -0700 Subject: weird cgi problem w/ apache In-Reply-To: <1117856044.857442.221610@g43g2000cwa.googlegroups.com> References: <1117856044.857442.221610@g43g2000cwa.googlegroups.com> Message-ID: <1117923448.900544.143460@f14g2000cwb.googlegroups.com> could it be the umask? From steve at REMOVEMEcyber.com.au Wed Jun 15 01:13:33 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Wed, 15 Jun 2005 15:13:33 +1000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> Message-ID: <42AFB8FD.1060504@REMOVEMEcyber.com.au> Roy Smith wrote: > Steven D'Aprano wrote: > > >High and low tides aren't caused by the moon. > > > They're not??? Nope. They are mostly caused by the continents. If the Earth was completely covered by ocean, the difference between high and low tide would be about 10-14 inches. (Over deep ocean, far from shore, the difference is typically less than 18 inches.) The enormous difference between high and low tide measured near the shore (up to 45 feet in the Bay of Fundy in Canada, almost forty times larger) is caused by the interaction of the continents with the ocean. In effect, the water piles up against the shore, like in a giant bathtub when you slosh the water around. The true situation is that tides are caused by the interaction of the gravitational fields of the sun, the moon and the Earth, the rotation of the Earth, the physical properties of water, its salinity, the depth, shape and composition of the coast and shoreline, the prevailing ocean currents, vibrationary modes of the ocean (including up to 300 minor harmonics), ocean storms, and even the wind. You can understand why we usually simplify it to "the moon causes the tides", even though the moon isn't even the largest contributing factor. See, for example: http://home.hiwaay.net/~krcool/Astro/moon/moontides/ -- Steven From mistobaan at gmail.com Fri Jun 10 09:04:40 2005 From: mistobaan at gmail.com (M1st0) Date: 10 Jun 2005 06:04:40 -0700 Subject: python bytecode grammar References: <1118406741.403982.319720@g44g2000cwa.googlegroups.com> Message-ID: <1118408680.008103.203670@g49g2000cwa.googlegroups.com> Ops yes is BNF :P Bacus Normal Form if I am not wrong... However...... I'am tryng to recognizing patterns in a bytecoded file in orderd to optimize... But I would like to "parse" i.e reconstruct it in something like a tree.. in order to apply rules on a tree recursively. I have seen compile.c in the Python dist... From anonymousnerd at gmail.com Sat Jun 25 00:53:03 2005 From: anonymousnerd at gmail.com (anonymousnerd at gmail.com) Date: 24 Jun 2005 21:53:03 -0700 Subject: How does one write a function that increments a number? Message-ID: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> Apologies if this question seems stupid: How does one write a function that increments a value in Python? When I tried, the variable never changed. The session went like this: >>> def incr(counter): counter = int(counter) counter += 1 >>> counter = 1 >>> incr(counter) >>> print counter 1 >>> Thanks in advance, Vaibhav From laurent.rahuel at net-ng.com Tue Jun 7 15:57:24 2005 From: laurent.rahuel at net-ng.com (Laurent RAHUEL) Date: Tue, 07 Jun 2005 21:57:24 +0200 Subject: Reading a CSV file into a list of dictionaries References: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> Message-ID: <42a5fc08$0$302$7a628cd7@news.club-internet.fr> RFQ wrote: > Hi, I'm struggling here to do the following with any success: > > I have a comma delimited file where each line in the file is something > like: > > PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... This is NOT a CSV file. A CSV file would be : PNumber,Contractor,Architect,... 2056,XYZ Contracting,ABC Architects,... Then, you could use the built-in CSV module of recent python versions. > > So each line is intended to be: key1,value1,key2,value2,key3,value3... > and each line is to be variable in length (although it will have to be > an even number of records so that each key has a value). > > I want to read in this csv file and parse it into a list of > dictionaries. So each record in the list is a dictionary: > > {"PNumber":"3056","Contractor":"XYZ Contracting", ... } > > I have no problem reading in the CSV file to a list and splitting each > line in the file into its comma separated values. But I can't figure > out how to parse each resulting list into a dictionary. > > Any help on this? By, From gene.tani at gmail.com Sun Jun 19 04:41:14 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jun 2005 01:41:14 -0700 Subject: What platforms have Python Virtual Machines and what version(s) ofPython do they support? References: <361ab1trhpgra9hig255r7arv68gfpe7lj@4ax.com> Message-ID: <1119170474.644310.102840@g49g2000cwa.googlegroups.com> http://dmoz.org/Computers/Programming/Languages/Python/Ports/ From peter at engcorp.com Fri Jun 17 09:18:38 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Jun 2005 09:18:38 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <1119012614.4268.18.camel@athop1.ath.vt.edu> References: <42ae3411@news.eftel.com> <1118928457.18452.13.camel@athop1.ath.vt.edu> <42B23670.70103@lexicon.net> <1119012614.4268.18.camel@athop1.ath.vt.edu> Message-ID: <6sudnWgJw6l7UC_fRVn-iQ@powergate.ca> rbt wrote: > The script is too long to post in its entirety. In short, I open the > files, do a binary read (in 1MB chunks for ease of memory usage) on them > before placing that read into a variable and that in turn into a list > that I then apply the following re to > > ss = re.compile(r'\b\d{3}-\d{2}-\d{4}\b') > > like this: > > for chunk in whole_file: > search = ss.findall(chunk) > if search: > validate(search) This seems so obvious that I hesitate to ask, but is the above really a simplification of the real code, which actually handles the case of SSNs that lie over the boundary between chunks? In other words, what happens if the first chunk has only the first four digits of the SSN, and the rest lies in the second chunk? -Peter From steven.bethard at gmail.com Thu Jun 2 20:32:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 02 Jun 2005 18:32:45 -0600 Subject: REQ: Small Perl to Python conversion needed In-Reply-To: <020620052018031433%user@unknown.invalid> References: <020620052018031433%user@unknown.invalid> Message-ID: <0KSdnUXWwbOxOALfRVn-og@comcast.com> Koncept wrote: > #!/usr/bin/perl > > # Parse comma delimited lines and create a final frequency hash > # Real example would read a file line by line > my %dict = {}; > my @lines = ( "1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5" ); > foreach(@lines) { map( $dict{ $_ }++, split( "," ) ); } > foreach( sort byKeys keys %dict ) { > print "Key: $_\tFrequency: ", "*" x $dict{ $_ }, "\n" > if $dict{ $_ } =~ /\d+/g; > } > sub byKeys { $dict{$b} <=> $dict{$a} } > > __DATA__ > Results: > Key: 5 Frequency: ***** > Key: 4 Frequency: **** > Key: 3 Frequency: *** > Key: 2 Frequency: ** > Key: 1 Frequency: * I don't speak Perl, but based on your output, I'd probably do something like: py> lines = ["1,2,3,4,5", "2,3,4,5", "3,4,5", "4,5", "5"] py> counts = {} py> for items in lines: ... for item in items.split(','): ... counts[item] = counts.get(item, 0) + 1 ... py> for key in sorted(counts, key=counts.__getitem__, reverse=True): ... print 'Key: %s Frequency: %s' % (key, '*'*counts[key]) ... Key: 5 Frequency: ***** Key: 4 Frequency: **** Key: 3 Frequency: *** Key: 2 Frequency: ** Key: 1 Frequency: * I'm probably missing a few subtleties, but hopefully this will get you started. STeVe From elmo13 at jippii.fi Tue Jun 28 19:46:18 2005 From: elmo13 at jippii.fi (=?ISO-8859-1?Q?Elmo_M=E4ntynen?=) Date: Wed, 29 Jun 2005 02:46:18 +0300 Subject: I need help figuring out how to fix this code. In-Reply-To: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: <42C1E14A.1000808@jippii.fi> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Nathan Pinno wrote: > Hi all, > > I need help figuring out how to fix my code. I'm using Python 2.2.3, and > it keeps telling me invalid syntax in the if name == "Nathan" line. Here is > the code if you need it. > > #This program asks for a password, then asks for the user's name after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" > > What's wrong with the code? How do I fix it, so that it works? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > > > I think about all the problems in your code are solved by suggestions sent before me, but I have some advice for future situations: Especially with more complex problems, larger code blocks using external libs, etc, you should, if appropriate, include the Traceback, some explanation on the given code(what it should do etc.) and maybe consider documenting the code a little with comments and docstrings(try reading some code you haven't seen before or in a long time, without any commentation. What about debugging it without knowing what the code is supposed to do?) Don't be intimidated by this, you just seemed to be new with programming with python and thought of sharing this with you. You have maybe read something like this before from a book or tutorial(there are a couple of good free books for learning python, for example "byte of python"), but good commenting and the like are usually appreciated only when they're not available:) Hope I didn't scare you. Happy tinkering with python! Elmo M?ntynen -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFCweCuctNFyQJObrsRAuXsAJ0auOEcnZDZB/A8hLHNS7D5C1Rl2ACfQNp1 7PAZLqG7H/6Fv6hC2m9CO50= =cesa -----END PGP SIGNATURE----- From cam.ac.uk at mh391.invalid Thu Jun 23 03:13:12 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 23 Jun 2005 08:13:12 +0100 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Stelios Xanthakis wrote: > Magnus Lycka wrote: > >> Right. Silly me. Maybe in some future Python version, True and False >> will be constants, like None is since Python 2.4. > > Actually, there is support in marshal to write True and False objects so > I don't understand why this isn't in 2.4 Because it would break existing code. -- Michael Hoffman From roy at panix.com Fri Jun 10 17:08:30 2005 From: roy at panix.com (Roy Smith) Date: 10 Jun 2005 17:08:30 -0400 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118431497.113944.261450@z14g2000cwz.googlegroups.com> Message-ID: Kay Schluehr wrote: > Python projects are submarines. Sometimes submarines disappear without a trace and loss of all hands aboard. From michele.petrazzo at TOGLIunipex.it Mon Jun 6 09:01:14 2005 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 06 Jun 2005 15:01:14 +0200 Subject: odbc and python In-Reply-To: <1117785062.654497.192330@g44g2000cwa.googlegroups.com> References: <1117785062.654497.192330@g44g2000cwa.googlegroups.com> Message-ID: <42a44815$0$17106$5fc30a8@news.tiscali.it> Giles Brown wrote: > MM wrote: > >>Are there any other odbc packages other than the win32all and mxodbc >>ones? The win32all odbc.pyd can't access table structure info like >>SQLColumns, and mxobdc requires a commercial license which is >>unjustifiable for this tiny project. Any other OS alternatives for >>win32?. Thanks. > > > You could potentially make the ODBC calls using ctypes a la: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303667 > > Not tried this myself and imagine it could be a bit tedious. > > Cheers, > Giles > This is the new version that work very well into my projects: http://unipex.it/vario/RealPyOdbc.py This can work on all the platforms where ctypes work. In the future I'll make it db-api 2.0 compliant. If you have some question, email me directly. Bye, Michele From greg at cosc.canterbury.ac.nz Wed Jun 8 22:14:41 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 14:14:41 +1200 Subject: need some cgi help please In-Reply-To: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> References: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> Message-ID: <3gpn0vFdp53cU1@individual.net> nephish at xit.net wrote: > IOError: [Errno 2] No such file or directory: > '/var/www/stretch/web_root/SidCrops/tenderloin/Tue Jun 7 20:13:35 > 2005.txt' > args = (2, 'No such file or directory') The web server isn't running in a chrooted environment or anything, is it? Are there any other files that it *can* open? -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From caseyhHAMMER_TIME at istar.ca Wed Jun 22 20:51:02 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Thu, 23 Jun 2005 00:51:02 GMT Subject: Looking For Geodetic Python Software References: <447po2-iqt.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: >Is anyone aware of freely available Python modules that can do any of >the following tasks: > >1) Given the latitude/longitude of two locations, compute the distance > between them. "Distance" in this case would be either the straight-line > flying distance, or the actual over-ground distance that accounts for > the earth's curvature. Do your planes fly over the earth's surface or through the ground? -- Regards, Casey From roy at panix.com Thu Jun 30 22:31:07 2005 From: roy at panix.com (Roy Smith) Date: Thu, 30 Jun 2005 22:31:07 -0400 Subject: map vs. list-comprehension References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: Robert Kern wrote: > Looks like the PSU got to yoNO CARRIER No, the trackpad on my PowerBook seems to have gone a little haywire and I'm getting the occasional random mouse click. In that case, it seemed to have clicked the "Post" button. From guettli at thomas-guettler.de Wed Jun 8 10:44:11 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 08 Jun 2005 16:44:11 +0200 Subject: circular import Module References: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Message-ID: Am Wed, 08 Jun 2005 01:11:50 -0700 schrieb ajikoe at gmail.com: > Hello, > > I have two modules (file1.py and file2.py) > Is that ok in python (without any weird implication) if my module > import each other. I mean in module file1.py there exist command import > file2 and in module file2.py there exist command import file1? > > This is not working in C#. Circular import does not work on module level, but you can import the module in a method: file1.py: import file2 .... file2.py: # import file1 # Does not work! def foo(): import file1 # Does work HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From jrastrick at student.usyd.edu.au Mon Jun 20 18:06:04 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 20 Jun 2005 15:06:04 -0700 Subject: reading a list from a file In-Reply-To: References: <223874235.UzX6FoQtyG@teancum> Message-ID: <1119305164.006906.133590@z14g2000cwz.googlegroups.com> Be careful, though - make sure you can absolutely trust your source of data before calling eval on it. If an unauthorised person could forseeably modify your file, then they could insert a string containing arbitrary Python code into it in place of your list, and then running your program would cause that code to be executed. So, to put it bluntly, eval is dangerous. Sure is convenient, though :) From dalke at dalkescientific.com Fri Jun 10 11:23:58 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 10 Jun 2005 15:23:58 GMT Subject: Is pyton for me? References: <42a98c1d$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Where do you find check_call()? It's not in the docs and I get > >>> import subprocess > >>> subprocess.check_call > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'check_call' > > with Python 2.4.1. Interesting. I got my subprocess.py from CVS. The CVS log revision 1.12 date: 2005/01/01 09:36:34; author: astrand; state: Exp; lines: +39 -1 New subprocess utility function: check_call. Closes #1071764. The bug tracker is http://sourceforge.net/tracker/index.php?func=detail&aid=1071764&group_id=5470&atid=305470 which says it's a 2.5ism. Oops! Sorry about that post from the future. I didn't realize it. Andrew dalke at dalkescientific.com From http Thu Jun 23 16:57:17 2005 From: http (Paul Rubin) Date: 23 Jun 2005 13:57:17 -0700 Subject: OT: Re: Looking For Geodetic Python Software References: <447po2-iqt.ln1@eskimo.tundraware.com> <3hvrhjFj3qfmU1@uni-berlin.de> Message-ID: <7xu0jodc5u.fsf@ruckus.brouhaha.com> Tim Daneliuk writes: > Huh? When traversing along the surface of the earth, it's curvature > is relevant in computing total distance. An airplane flies more-or-less > in a straight line above that curvature. For sufficiently long airplane > routes (where the ascent/descent distance is trivial compared to the > overall horizontal distance traversed), a straight line path shorter > than the over-earth path is possible. That's why I specified the > desire to compute both path lengths. Where's the humor? It's just not clear what you meant: A) The shortest path between two points on a curved surface is called a geodesic and is the most meaningful definition of "straight line" on a curved surface. The geodesic on a sphere is sometimes called a "great circle". B) By a straight line you could also mean the straight line through the 3-dimensional Earth connecting the two points on the surface. So the straight line from the US to China would go through the center of the earth. C) Some people seem to think "straight line" means the path you'd follow if you took a paper map, drew a straight line on it with a ruler, and followed that path. But that path itself would depend on the map projection and is generally not a geodesic, and neither is it straight when you follow it in 3-space. From luismgz at gmail.com Fri Jun 3 18:10:39 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 3 Jun 2005 15:10:39 -0700 Subject: mod_python config problem In-Reply-To: References: Message-ID: <1117836639.485847.268100@g47g2000cwa.googlegroups.com> Getting mod_python to work is hard because there are many things to get into account. Your Apache version should match the proper mod_python version, as well as the python version amd so on... If you are having many problems, I suggest installing Apache2Triad, which is a package that will install everything you need (and more) all at once. www.apache2triad.net From __peter__ at web.de Thu Jun 16 04:03:50 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 16 Jun 2005 10:03:50 +0200 Subject: Regex for repeated character? References: <5J9se.136$Q75.39412@newshog.newsread.com> Message-ID: Leif K-Brooks wrote: > How do I make a regular expression which will match the same character > repeated one or more times, instead of matching repetitions of any > (possibly non-same) characters like ".+" does? In other words, I want a > pattern like this: > > >>> re.findall(".+", "foo") # not what I want > ['foo'] > >>> re.findall("something", "foo") # what I want > ['f', 'oo'] This is as close as I can get: >>> [m.group() for m in re.compile(r"(.)(\1*)").finditer("foo bar baaaz")] ['f', 'oo', ' ', 'b', 'a', 'r', ' ', 'b', 'aaa', 'z'] Peter From l.serwatka at gazeta-dot-pl.no-spam.invalid Tue Jun 7 08:49:28 2005 From: l.serwatka at gazeta-dot-pl.no-spam.invalid (ls) Date: Tue, 7 Jun 2005 12:49:28 +0000 (UTC) Subject: how to export data from ZODB to text files Message-ID: Hi All, I looking for help with ZODB data export to text file. I have file Data.fs (file becomes from Plone CMS) and I have to display content structure, data like intro, body of article, etc and save it in to simple file. However I can't use Plone XML export because is broken, Zope Corp. set low priority for this bug, so I have to find other way how to digg in to data. Could you point me in to some Python code examples, code contributions and so on. Thank you for any suggestions, Lukasz From kbilsted at hotmail.com Thu Jun 9 04:27:47 2005 From: kbilsted at hotmail.com (newseater) Date: 9 Jun 2005 01:27:47 -0700 Subject: multiple inheritance In-Reply-To: References: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> Message-ID: <1118305667.847406.58280@g44g2000cwa.googlegroups.com> if I only use the super() construct it seems not to call B class A(object): def foo(self): print "a" class B(object): def foo(self): print "b" class C(A,B): def foo(self): print "c" super(C,self).foo() c = C() produces c a oddly i can produce a "b" by using super(A,self).foo() i'm not sure why it isn't super(B,self).foo() From darkpaladin79 at hotmail.com Thu Jun 9 12:33:47 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 12:33:47 -0400 Subject: help with sending mail in Program In-Reply-To: <007101c56d0f$a0afa5d0$ccbefea9@twilliams> Message-ID: > >#!/usr/local/bin/python > >''' Send mail to me ''' > >from smtplib import SMTP > >def sendToMe(subject, body): > me = '"Ivan Shevanski" ' > send(me, me, subject, body) > > >def send(frm, to, subject, body): > s = SMTP() >#///On or off for test\\\ #s.set_debuglevel(1) > s.connect('mail.hotmail.com',) > s.ehlo('69.137.27.32') # IP address of my computer, I don't > >remember why I needed this > msg = '''From: %s >Subject: %s >To: %s > >%s >''' % (frm, subject, to, body) > > s.sendmail(frm, to, msg) > > s.sendmail(frm, [to], msg) > > s.quit() > > >if __name__ == '__main__': > sendToMe('test', 'test') > > >It says it sends it but I get nothing in my inbox or anywhere! This is >really frustrating me. > >_________________________________________________________________ > >[tim williams]> No it definitely works, but Hotmail will blackhole your >constructed email as it is obviously fake. It has no headers, dates, >msg-id etc. > >[tim williams]> View the source of a real email in your mail client, >then >cut & paste the whole thing into your message variable like this > > msg = ''' ''' > >[tim williams]> you should remove the " % (frm, subject, to, body) " at >the end of the msg string > >[tim williams]> for correctness, you also need an " s.rset() " in >between >each " s.sendmail " (but the script does work in its current form) > >[tim williams]> HTH :) > > Im good with everything except viewing the source. . .Do you mean the html source? Because I use hotmail, and not outlook or thunderbird or something like that. Sorry, i'm a noob. -Ivan _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From grante at visi.com Sun Jun 12 17:37:33 2005 From: grante at visi.com (Grant Edwards) Date: Sun, 12 Jun 2005 21:37:33 -0000 Subject: How to test if an object IS another object? References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> <1118608093.758427.280220@g49g2000cwa.googlegroups.com> <1118609353.934316.109870@g49g2000cwa.googlegroups.com> Message-ID: <11apaotitftps2b@corp.supernews.com> On 2005-06-12, eloff777 at yahoo.com wrote: > Fascinating. With small strings, it uses the same object, and with > small numbers like 3. With 300 they were different objects (why, It's purely an implimentation detail. The small integers get used a lot, so Python keeps a pre-created set of small integers handy. It would be a bit, uh, wasteful to pre-create all of possible integer objects, so "large" integers get created on the fly without checking to see if there are any existing ones with the right value. Large integers could get cached and re-used, but that would be extra overhead with little chance for benefit. > shouldn't they both be ints still?) They are. -- Grant Edwards grante Yow! .. over in west at Philadelphia a puppy is visi.com vomiting... From jgrahn-nntq at algonet.se Tue Jun 21 07:21:39 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 21 Jun 2005 11:21:39 GMT Subject: Using print with format to stdout generates unwanted space References: <3hmt4rFhnn89U1@individual.net> <42b6bc99@news.highway1.com.au> <3ho63fFi1o93U1@individual.net> Message-ID: On Tue, 21 Jun 2005 00:08:03 +0100, Tim Williams (gmail) wrote: ... > For quick and simple removal of the extra space, append a '\b' > backspace character to your output "string" For things that are only ever to be viewed on the terminal, yes. But this does, of course, print an actual backspace character. If you feed this output to another program, chances are it will not treat as no space at all. I prefer building up a list and doing ' '.join(thelist) in these situations. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From __peter__ at web.de Wed Jun 15 14:13:59 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Jun 2005 20:13:59 +0200 Subject: Tkinter question References: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> Message-ID: Fredrik Lundh wrote: > note that you're assigning all buttons to the same instance variable, so > even if the above did work, it would always return a plus. > > since the command callback doesn't know what widget it was called > from, you need to create a separate callback for each widget.??here's > one way to do that: > > for?x?in?range(4): > for?y?in?range(4): > text?=?i[t]?#?label?text > def?callback(): > self.pressed(text) Change the above function to def?callback(text=text): self.pressed(text) Otherwise you have distinct callbacks, but they are still all seeing the same 'text' variable, probably bound to "+" by the time you press a button. Peter From peter at engcorp.com Thu Jun 2 12:46:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 12:46:17 -0400 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <7PudnWY-ZMJ2qgLfRVn-tw@powergate.ca> rbt wrote: > Peter Hansen wrote: >> Philosophy not entirely aside, you should note that object code in any >> language can "easily" be reverse-engineered in the same way, with the >> only difference being the degree of ease involved. If the code is >> worth enough to someone that they are willing to risk violating your >> license terms, they *will* be able to recover enough source code >> (whether it was Python, C, or assembly) to do what they need. > > Don't intend to hijack this thread, but this bit interests me. I know > several accomplished C/assembly programmers who have told me that > reverse engineering object code from either of these two languages is > anything but trivial. Yet, I *hear* and *read* the opposite all of the > time. Can anyone actually demonstrate a decompile that mirrors the > original source? It all depends on the definition of "reverse engineering". In my opinion and experience, very little code in the world is so sophisticated that it is not roughly as easy to write equivalent code from scratch (with the original, working program as a guide of what the code actually does) as it would be to convert the object code back into source. (Exceptions such as "decompyle" which may make the job near trivial aside.) If that's true, it leaves us with a very small subset of the code in any given program, that might actually be worth the effort of converting back to source. That bit of code will generally turn out to be so small that once again an automated conversion to source is not really necessary, since analysis of the object code would with relatively little effort allow one to "reverse engineer" some equivalent source, in whatever language (or pseudo-code) one chose. So, for languages like C, where the compilation process is fairly "destructive" to things like the variable names and control structures used, "reverse engineering" in the sense of "automated conversion back to equivalent source code" is rather difficult, probably infeasibly so for most non-trivial programs. I personally don't understand the need for this, other than in the case of "I lost my source", and the correct answer there is a session of pummelling, followed by tarring and feathering with the pages of the Subversion Book. On the other hand, "reverse engineering" in the sense of "creating source code capable of reproducing the effects of the valuable and interesting parts of the object code" is not that difficult, and in the sense of "understanding how this code works" is even easier, being just the first part of that step. Software development is far more about choosing the right problems to solve and the right ways to solve them than it is about writing source code for the program that will do the job. And if I had an automated tool to reproduce source code for a given program, I'd still be very concerned that I didn't end up with any of its automated test cases. ;-) -Peter From d at e.f Fri Jun 24 10:00:04 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 09:00:04 -0500 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Message-ID: Peter Hansen wrote: > D H wrote: > >> Peter Hansen wrote: >> >>> Bo Peng wrote: >>> >>>> I need to pass a bunch of parameters conditionally. In C/C++, I can do >>>> func(cond1?a:b,cond2?c:d,.....) >>>> >>>> Is there an easier way to do this in Python? >>> >>> >>> Please read the FAQ to learn the answer and much other useful ... >> >> >> The answer is no. Use if statements. > > > Actually that's just one possible answer. Whether it's _the_ answer is > obviously again a matter of opinion, and as usual we differ. Quit being such an idiot and refuting everything I say. The answer is simply no, just use an if statement instead. From deets at web.de Thu Jun 2 10:55:38 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 02 Jun 2005 16:55:38 +0200 Subject: DOM question In-Reply-To: References: Message-ID: > > Yes, in fact: > > //section[@id=$id_param]//*[name()!='section'] > > would do the trick. > > I was trying to avoid using anything not in the standard Python > distribution if I could help it; I need to be able to use my code on > Linux, OS X and Windows. > > The xml.path package is from PyXML, yes? I'll just have to battle with > installing PyXML on OS X ;-) As a fresh member of the MacOSX community I can say that so far except pygame I made everything run. So - I don't expect that to be too much of a problem. Diez From roy at panix.com Mon Jun 13 20:27:46 2005 From: roy at panix.com (Roy Smith) Date: Mon, 13 Jun 2005 20:27:46 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: Andrea Griffini wrote: > Hehehe... a large python string is a nice idea for modelling > memory. Actually, a Python string is only good for modelling ROM. If you want to model read-write memory, you need a Python list. From bokr at oz.net Sun Jun 26 00:54:42 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 04:54:42 GMT Subject: OO approach to decision sequence? References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> Message-ID: <42be2920.217477255@news.oz.net> On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek wrote: [...] > >Now, the same sort of behaviour where the "if type" testing has been >replaced with code more in keeping with the OOP approach: > > >>> class C(object): >... def report(self): >... print "Found a C" >... > >>> class D(object): >... def report(self): >... print "Found a D" >... > >>> c = C() > >>> d = D() > >>> for item in (c, d): >... item.report() >... >Found a C >Found a D > >>> > The OP might want to consider factoring report into a base class, e.g., >>> class Base(object): ... def art_name(self): ... cname = type(self).__name__ ... art = 'an'[:1+(cname.upper() in 'A E F H I L M N O R S X' or ... len(cname)>1 and cname.upper()[0] in 'AEIOU')] ... return art, cname ... >>> class A(Base): pass ... >>> class B(Base): pass ... >>> class F(Base): pass ... >>> class Foo(Base): pass ... >>> class U(Base): pass ... >>> class Uhuh(Base): pass ... >>> items = A(), B(), F(), Foo(), U(), Uhuh() >>> for item in items: print 'Found %s %s' % item.art_name() ... Found an A Found a B Found an F Found a Foo Found a U Found an Uhuh Returning info rather than printing to stdout allows you to access and use it differently, e.g., >>> items[3].art_name() ('a', 'Foo') >>> items[3].art_name()[1] 'Foo' (Don't know if the a/an logic is really general ;-) Regards, Bengt Richter From nephish at xit.net Sat Jun 11 11:56:11 2005 From: nephish at xit.net (nephish at xit.net) Date: 11 Jun 2005 08:56:11 -0700 Subject: cgi script runs under Opera, but not firefox In-Reply-To: References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> <1118501642.065924.83560@z14g2000cwz.googlegroups.com> Message-ID: <1118505371.230328.231880@o13g2000cwo.googlegroups.com> Ok, i made a change in the source. now here is the source from Opera, still cant get firefox to work with me. Customer Data

Watkins Crop Consulting

1915 Cherokee
Dalhart, Tx 79022
333-5943

gandalf

Field field one
Crop crop one
GS growing, yep

Weeds many weeds
Water lots o water
Incects lots o insects

Remarks comment block, could be short, could be long, however will we know?


Field another field
Crop another crop
GS another growth stage

Weeds many many weeds
Water lots more water
Incects lots more insects

Remarks ok , short comment this time



maybe there is another place i have gakked up the source. From patrick.down at gmail.com Tue Jun 14 18:24:43 2005 From: patrick.down at gmail.com (Patrick Down) Date: 14 Jun 2005 15:24:43 -0700 Subject: Python in Games (was RE: [Stackless] Python in Games) References: Message-ID: <1118787883.193470.125620@f14g2000cwb.googlegroups.com> My understanding is that the upcoming Civilization IV will have python scripting. From peter at engcorp.com Thu Jun 2 09:47:54 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 09:47:54 -0400 Subject: decimal and trunkating In-Reply-To: <3g8fcjFarp9dU1@individual.net> References: <429f0656$0$32668$626a14ce@news.free.fr> <3g8fcjFarp9dU1@individual.net> Message-ID: <8f-dnecR35jVkwLfRVn-tw@powergate.ca> Reinhold Birkenfeld wrote: > He is speaking of Decimals... > > d = Decimal("199.999") > d._round(5, decimal.ROUND_DOWN) Is one really supposed to call the underscore methods like that? -Peter From ka_czor at poczta.onet.pl Mon Jun 13 06:13:52 2005 From: ka_czor at poczta.onet.pl (ka_czor at poczta.onet.pl) Date: Mon, 13 Jun 2005 12:13:52 +0200 Subject: Java to Python - how to?? Message-ID: <20050613101402Z1180569-3166+223@kps8.test.onet.pl> Hello I just start programing in Python. I've got a qestion, how translate the example code writen in Java to Python?? public class ConnectionManager { public ConnectionManager() { super(); } public void sendAgent(Agent anAgent, WorkplaceAddress anAddress) { } } bye From Sivakumar.Bhaskarapanditha at abaqus.com Fri Jun 10 14:33:42 2005 From: Sivakumar.Bhaskarapanditha at abaqus.com (Sivakumar Bhaskarapanditha) Date: Fri, 10 Jun 2005 14:33:42 -0400 Subject: lstat(fileName)[ST_SIZE] Message-ID: <20050610183340.9EDCA37466@postoffice.hks.com> Hi, I need your help in this. What is the type of os.lstat(fileName)[stat.ST_SIZE]. In python 2.0 I am getting it as int and in 2.3 it is long. Because it is an int in 2.0 the file size reported is negative for file sizes > INT_MAX. Do you know if this is a bug in 2.0. Are there other ways of getting file sizes. In 2.3 everything is alright. Any help in this matter will be greatly appreciated. Best regards, Siva -------------- next part -------------- An HTML attachment was scrubbed... URL: From avera at coes.org.pe Thu Jun 30 16:24:19 2005 From: avera at coes.org.pe (Alberto Vera) Date: Thu, 30 Jun 2005 15:24:19 -0500 Subject: doc 2 pdf Message-ID: <000a01c57db1$b1fcdf30$1603a8c0@pc22> Hello. I tried to use reportlab to convert a doc to pdf file, but i didn't found any script to do this using python. Do you have any script to convert a doc file? (doc->pdf) Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Jun 1 17:19:49 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 02 Jun 2005 07:19:49 +1000 Subject: creating a hex value In-Reply-To: <7xbr6pzzs6.fsf@ruckus.brouhaha.com> References: <1285743.rKB6TKaXDy@teancum> <7xbr6pzzs6.fsf@ruckus.brouhaha.com> Message-ID: <429e2675@news.eftel.com> Paul Rubin wrote: > David Bear writes: > >>I'm not seeing it in my python essential ref. how can I do >> >>delim = 0x15 > > > delim = chr(0x15) Ooooh -- a function with a constant arg; I wonder what that evaluates to? >>> chr(0x15) '\x15' Sheeeesh. From spam.csubich+block at block.subich.spam.com Wed Jun 8 16:44:43 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 16:44:43 -0400 Subject: Fast text display? In-Reply-To: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Use tkinter if you care about cross-platform operation. Everything > else requires downloading and installing separate toolkits. Oh, the downloading and installing isn't a big deal. If in the far-flung future anyone else uses this program, they'll be big boys who can install things themselves. :) I'm just concerned about availability; the cross-platform operation for me would exclude things like direct Win32API calls, or direct linux-terminal calls (which apparently mcl uses to great effect). From simonwittber at gmail.com Sun Jun 19 03:38:50 2005 From: simonwittber at gmail.com (simonwittber at gmail.com) Date: 19 Jun 2005 00:38:50 -0700 Subject: pickle alternative In-Reply-To: <7xd5qi3ldp.fsf@ruckus.brouhaha.com> References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> <1119161205.327572.136150@g44g2000cwa.googlegroups.com> <7xd5qi3ldp.fsf@ruckus.brouhaha.com> Message-ID: <1119166730.350374.178510@o13g2000cwo.googlegroups.com> > See also bug# 471893 where jhylton suggests a PEP. Something really > ought to be done about this. I know this, you know this... I don't understand why the suggestion is meeting so much resistance. This is something I needed for a real world system which moves lots of data around to untrusted clients. Surely other people have had similar needs? Pickle and xmlrpclib simply are not up to the task, but, perhaps Joe Programmer is content to use a pickle, and not care for the security issues. Owell. I'm not sure what I can say to make the case any clearer... Sw. From xah at xahlee.org Sat Jun 18 05:49:38 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jun 2005 02:49:38 -0700 Subject: Python documentation problem In-Reply-To: References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Message-ID: <1119088178.088667.227150@g44g2000cwa.googlegroups.com> > what is wrong with python doc > http://python.org/doc/2.4.1/lib/typesfunctions.html the problem is that the page essentially says nothing. Nothing that is relevant to programing, and such nothingness occupies a significant portion of the python doc. (at least a quarter) It is like reading a manual to operate a machinery, and in every other paragraph it offers the (technically-fantastically-correct) explanations of what bolt or material were used where. the cause of such nothingness situation is because the brainlessness approach to doc organization coupled with standard computer industry geeking moron's need to computer-sciency speak with implementation infatuation. And in part it came to that really because they are comparative morons. for a more sincere, detailed account, please see: http://xahlee.org/perl-python/re-write_notes.html Thanks. Xah xah at xahlee.org ? http://xahlee.org/ From enleverlesO.OmcO at OmclaveauO.com Fri Jun 24 06:44:18 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 24 Jun 2005 12:44:18 +0200 Subject: Thanks for PIL (and other stuff) References: <1119579123.611615.197720@g14g2000cwa.googlegroups.com> Message-ID: <42bbe40b$0$25026$8fcfb975@news.wanadoo.fr> +1 -- Michel Claveau From cpunerd4 at gmail.com Sat Jun 18 10:51:08 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 07:51:08 -0700 Subject: extreme newbie In-Reply-To: <1119106093.097295.320940@g44g2000cwa.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> Message-ID: <1119106268.831809.287550@g47g2000cwa.googlegroups.com> by the way, you guys have talked me out of java. Im thinking about this py2exe thing. (anyother suggestions) I like this list. :) From desertgarden at netscape.com Sat Jun 18 22:08:19 2005 From: desertgarden at netscape.com (Brian) Date: Sun, 19 Jun 2005 02:08:19 GMT Subject: extreme newbie In-Reply-To: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> Message-ID: Hi Cpunerd4, For beginners, I would strongly recommend checking out http://www.GreenTeaPress.com -- they publish a FREE, online book that is used in Highschools and other educational facilities to teach Python programming. Excellent -- a must have for those who wish to learn about the language. Brian --- cpunerd4 wrote: > Hello programmers, > I stumbled onto the python language by chance and it looks like a > great language. Although from what I've read so far (which isn't much) > I've guessed that python is purely an interpreted language unless its > compiled into another language (ie. it needs python installed in order > to run programs). Is this correct? If it is, I guess my plan of action > would be to use python embeded in java applets. > Another question I have: Does any one know any really good, really > easy to understand python books? I would prefer one that is avalible > online for free, but I would also like to know my choices in print. > Thanks in advance for any advice, > cpunerd4 > > P.S. I'm 14 and I know HTML, PHP, and I know about many others! > From peter at rt.sk Tue Jun 28 13:29:23 2005 From: peter at rt.sk (Peter Szinek) Date: Tue, 28 Jun 2005 19:29:23 +0200 Subject: How to compress a folder and all of its sub directories and files into a zip file? In-Reply-To: <311b5ce105062723167e892833@mail.gmail.com> References: <311b5ce105062723167e892833@mail.gmail.com> Message-ID: <42C188F3.7010704@rt.sk> Hi, What about this: import os,zipfile from os.path import join zip = zipfile.ZipFile("myzipfile.zip", 'w') for root, dirs, files in os.walk('.'): for fileName in files: zip.write(join(root,fileName)) zip.close() Maybe it zips also the myzipfile.zip ;-) Probably this is not needed, so an additional test (something like fileName != 'myfile.zip' would be needed. HTH, Peter could ildg wrote: > I want to compress a folder and all of its sub files including empty folders > into a zip file. what's the pythonic way to do this? > > Thanks in advance. From d at e.f Sat Jun 11 11:26:30 2005 From: d at e.f (D H) Date: Sat, 11 Jun 2005 10:26:30 -0500 Subject: Best Web dev language In-Reply-To: <11al0nhr4opfgaa@corp.supernews.com> References: <11al0nhr4opfgaa@corp.supernews.com> Message-ID: Jon Slaughter wrote: > I'm trying to get into web development for creating a professional web site > and I'm confused on which language I should use. I've read some comparisons > between the major languages and I was thinking that python might be the way > to go for the most powerful and general language but I am not sure. Does > anyone know of any detailed and objective comparisons between the major > languages(perl, php, java, javascript, etc...) that might help me get a > clearer picture? The one that is most popular and has by far the most open source example applications out there is PHP (plus MySQL for databases). It's been that way for many years now. It is also much cheaper and easier to find PHP/MySQL hosting. Search sourceforge.net for many example PHP web applications. I hope you realize that by posting your question on the Python newsgroup instead of a general web development newgroup, you're going to get extremely biased answers. If you do go with Python, check out the mod_python module for the Apache web server. From arazavi at swen.uwaterloo.ca Mon Jun 13 12:34:39 2005 From: arazavi at swen.uwaterloo.ca (Ali Razavi) Date: Mon, 13 Jun 2005 12:34:39 -0400 Subject: implicit variable declaration and access In-Reply-To: References: Message-ID: Ali Razavi wrote: > Is there any reflective facility in python > that I can use to define a variable with a > name stored in another variable ? > like I have : > x = "myVarName" > > what can I do to declare a new variable with the name of the string > stored in x. And how can I access that implicitly later ? Got it! use higher order functions like Lisp! code = x + '= 0' exec(code) code = 'print ' + x exec(code) From jabel at plus.net Thu Jun 9 07:18:53 2005 From: jabel at plus.net (John Abel) Date: Thu, 09 Jun 2005 12:18:53 +0100 Subject: optparse.py: FutureWarning error In-Reply-To: References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> Message-ID: <42A8259D.4070505@plus.net> Magnus Lycka wrote: >John Abel wrote: > > >>Magnus Lycka wrote: >> >> > > > >>As a programmer on Win32, and *nix platforms, I agree with needing >>better tools. however, I find cygwin a pita. For tools such as grep >>and find, try this http://unxutils.sourceforge.net/. No need for cygwin >>( though that's not say cygwin isn't useful ). >> >> > >Is there any shell there? While I do think that "cd /cygdrive/c" is a >bit silly, I still prefer bash to Microsoft's cmd.exe (even if cmd.exe >is much, much better than the old command.com). > > There is a sh, but no bash, scroll down the the linked page for a full list of the executables. J From grante at visi.com Sat Jun 18 09:24:27 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 13:24:27 -0000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: <11b884bj3bp164@corp.supernews.com> On 2005-06-18, cpunerd4 wrote: > thanks all for the advice. The reason I was thinking about using java > (or C or something) was that it is a little more secure than > distributing the source code isn't it? A little. Not much. You don't have to distribute Python source code, you know. You can distribute the compiled bytecode the same way you do in Java. > And also, from what I know, the Java virtual machine is more > popular (and installed on more computers). I don't know about that. Python is pretty much required on most Linux systems. All Redhat systems have had Python installed since the beginning (the redhat installer and system admin stuff was all written in Python). Same with Mandrake: Python is required and Java is optional and not installed by default in the Linux distros I'm familiar with. I don't know how many Windows systems have Java installed. I don't think any of mine do. > Although it might take me awhile to get to that stage. once > again thanks for your advice. The Dive into Python book looks > promising. -- Grant Edwards grante Yow! Now, I think it would at be GOOD to buy FIVE or SIX visi.com STUDEBAKERS and CRUISE for ARTIFICIAL FLAVORING!! From benji at benjiyork.com Fri Jun 24 23:01:25 2005 From: benji at benjiyork.com (Benji York) Date: Fri, 24 Jun 2005 23:01:25 -0400 Subject: http POST only returning GET data In-Reply-To: <1119666846.766429.68550@f14g2000cwb.googlegroups.com> References: <1119666846.766429.68550@f14g2000cwb.googlegroups.com> Message-ID: <42BCC905.50904@benjiyork.com> vm wrote: > Hi, for some reason my POST is not working properly. Look at the URL again, you missed a character. You had: httpSess.request("POST","/",params,headers) It should be: httpSess.request("POST","/q",params,headers) -- Benji York From kent37 at tds.net Wed Jun 15 12:36:36 2005 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Jun 2005 12:36:36 -0400 Subject: how to use pyparsing for identifiers that start with a constant string In-Reply-To: <1118849624.117660.165240@o13g2000cwo.googlegroups.com> References: <1118784164.619007.74150@g14g2000cwa.googlegroups.com> <42af57c0$1_2@newspeer2.tds.net> <1118849624.117660.165240@o13g2000cwo.googlegroups.com> Message-ID: <42b058a2_3@newspeer2.tds.net> Paul McGuire wrote: > Be careful, Kent. You may get tagged as "the new pyparsing guy." :) Yeah, I was a little surprised I beat you to that one :-) Kent From richard.a.patterson at lmco.com Tue Jun 28 18:27:37 2005 From: richard.a.patterson at lmco.com (Richard Patterson) Date: Tue, 28 Jun 2005 18:27:37 -0400 Subject: building 2.4.1 on HPUX Message-ID: I'm trying to compile python 2.4.1, on HPUX10.20, with support for tk and tcl 8.4 (installed in /opt/tk and /opt/tcl). I assume this means I need to compile the tkinter module too.. I was getting make errors, saying it couldn't find tcl/tk libs or headers... so I changed the setup.py script, hard coding library and include paths for tcl/tk, but it still didn't build the _tkinter module. So next I modified the Modules/Setup file, uncommenting, and changing compiler arguments to point to the correct lib and include paths. At least it built this time... so I ran make test, and got the following error for test_tcl: TclError: Can't find a usable tk.tcl in the following directories: /opt/tcl8.4.4/lib/tk8.4 On my system, /opt/tk is a link to /opt/tk8.4.4, therefore, the tk.tcl file is really in /opt/tk/lib/tk8.4/tk.tcl, but why didn't it look there? I'm stumped. Did I really have to hack the setup.py and Setup files? Where is it getting its paths from? Is my environment wrong, or do I need to change some configure parameters? I'm hoping someone out there knows what I'm doing wrong, or perhaps can point me in the right direction. Thanks again Rich From aahz at pythoncraft.com Sun Jun 12 18:37:18 2005 From: aahz at pythoncraft.com (Aahz) Date: 12 Jun 2005 15:37:18 -0700 Subject: Scaling down (was Re: Dealing with marketing types...) References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <7xwtp09jh3.fsf@ruckus.brouhaha.com> <7xhdg3xwzc.fsf@ruckus.brouhaha.com> Message-ID: In article <7xhdg3xwzc.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: >aahz at pythoncraft.com (Aahz) writes: >> >> So what? I think you're missing the real point of the article: using >> LAMP scales *DOWN* in a way that enterprise systems don't. Getting your >> first prototype up and running is far more important than sheer >> scalability, > >There comes a day when your first prototype can no longer handle the >traffic. The question then is how do you deal with that. Then you scale with hardware or do profiling and rewrite chunks, whichever costs less FOR THE BUSINESS. >> and LAMP does have many mechanisms to obtain scalability when it's >> needed. > >LAMP seems to have no solution other than scaling (i.e. blowing more >money on hardware and colo space). One really gets the impression >that a more thoughtful design could handle the traffic without needing >to scale the hardware. Is there some reason you keep repeating yourself without actually paying attention to other people? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From http Sun Jun 19 17:22:21 2005 From: http (Paul Rubin) Date: 19 Jun 2005 14:22:21 -0700 Subject: pickle alternative References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <7x4qchwh7a.fsf@ruckus.brouhaha.com> <1119161205.327572.136150@g44g2000cwa.googlegroups.com> <7xd5qi3ldp.fsf@ruckus.brouhaha.com> <1119166730.350374.178510@o13g2000cwo.googlegroups.com> Message-ID: <7x64waavoy.fsf@ruckus.brouhaha.com> simonwittber at gmail.com writes: > > See also bug# 471893 where jhylton suggests a PEP. Something really > > ought to be done about this. > > I know this, you know this... I don't understand why the suggestion is > meeting so much resistance. This is something I needed for a real world > system which moves lots of data around to untrusted clients. Surely > other people have had similar needs? Pickle and xmlrpclib simply are > not up to the task, but, perhaps Joe Programmer is content to use a > pickle, and not care for the security issues. I don't think there's serious objection to a PEP, but I don't read python-dev. Maybe there was objection to some specific technical point in your PEP. Why don't you post it here? From tim.peters at gmail.com Thu Jun 23 12:01:12 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 23 Jun 2005 12:01:12 -0400 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: References: <11bh7ffsps4ea3@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <1f7befae05062217465da484ab@mail.gmail.com> <42BA2B05.8510740D@pauahtun.org> Message-ID: <1f7befae05062309012e86599d@mail.gmail.com> [Tim Peters'] >> Well, I try, Ivan. But lest the point be missed , 754 doesn't >> _want_ +0 and -0 to act differently in "almost any" way. The only >> good rationale I've seen for why it makes the distinction at all is in >> Kahan's paper "Branch Cuts for Complex >> Elementary Functions, or Much Ado About Nothing's Sign Bit". There >> are examples in that where, when working with complex numbers, you can >> easily stumble into getting real-world dead-wrong results if there's >> only one flavor of 0. And, of course, atan2 exists primarily to help >> convert complex numbers from rectangular to polar form. [Steven D'Aprano] > It isn't necessary to look at complex numbers to see the difference > between positive and negative zero. Just look at a graph of y=1/x. In > particular, look at the behaviour of the graph around x=0. Now tell me > that the sign of zero doesn't make a difference. OK, I looked, and it made no difference to me. Really. If I had an infinitely tall monitor, maybe I could see a difference, but I don't -- the sign of 0 on the nose makes no difference to the behavior of 1/x for any x other than 0. On my finite monitor, I see it looks like the line x=0 is an asymptote, and the graph approaches minus infinity on that line from the left and positive infinity from the right; the value of 1/0 doesn't matter to that. > Signed zeroes also preserve 1/(1/x) == x for all x, No, signed zeros "preverse" that identity for exactly the set {+Inf, -Inf}, and that's all. That's worth something, but 1/(1/x) == x isn't generally true in 754 anyway. Most obviously, when x is subnormal, 1/x overflows to an infinity (the 754 exponent range isn't symmetric around 0 -- subnormals make it "heavy" on the negative side), and then 1/(1/x) is a zero, not x. 1/(1/x) == x doesn't hold for a great many normal x either (pick a pile at random and check -- you'll find counterexamples quickly). > admittedly at the cost of y==x iff 1/y == 1/x (which fails for y=-0 and x=+0). > > Technically, -0 and +0 are not the same (for some definition of "technically"); but > practicality beats purity and it is more useful to have -0==+0 than the alternative. Can just repeat that the only good rationale I've seen is in Kahan's paper (previously referenced). >> Odd bit o' trivia: following "the rules" for signed zeroes in 754 >> makes exponeniation c**n ambiguous, where c is a complex number with >> c.real == c.imag == 0.0 (but the zeroes may be signed), and n is a >> positive integer. The signs on the zeroes coming out can depend on >> the exact order in which multiplications are performed, because the >> underlying multiplication isn't associative despite that it's exact. > That's an implementation failure. Mathematically, the sign of 0**n should > depend only on whether n is odd or even. If c**n is ambiguous, then that's > a bug in the implementation, not the standard. As I said, these are complex zeroes, not real zeroes. The 754 standard doesn't say anything about complex numbers. In rectangular form, a complex zero contains two real zeroes. There are 4 possiblities for a complex zero if the components are 754 floats/doubles: +0+0i +0-0i -0+0i -0-0i Implement Cartesian complex multiplication in the obvious way: (a+bi)(c+di) = (ac-bd) + (ad+bc)i Now use that to raise the four complex zeroes above to various integer powers, trying different ways of grouping the multiplications. For example, x**4 can be computed as ((xx)x)x or (xx)(xx) or x((xx)x) etc. You'll discover that, in some cases, for fixed x and n, the signs of the zeroes in the result depend how the multiplications were grouped. The 754 standard says nothing about any of this, _except_ for the results of multiplying and adding 754 zeroes. Multiplication of signed zeroes in 754 is associative. The problem is that the extension to Cartesian complex multiplication isn't associative under these rules in some all-zero cases, mostly because the sum of two signed zeroes is (under 3 of the rounding modes) +0 unless both addends are -0. Try examples and you'll discover this for yourself. I was part of NCEG (the Numerical C Extension Group) at the time I stumbled into this, and they didn't have any trouble following it . It was a surprise to everyone at the time that Cartesian multiplication of complex zeroes lost associativity when applying 754 rules in the obvious way, and no resolution was reached at that time. >> I stumbled into this in the 80's when KSR's Fortran compiler failed a >> federal conformance test, precisely because the test did atan2 on the >> components of an all-zero complex raised to an integer power, and I >> had written one of the few 754-conforming libms at the time. They >> wanted 0, while my atan2 dutifully returned -pi. I haven't had much >> personal love for 754 esoterica since then ... > Sounds to me that the Feds wanted something broken and you gave them > something that was working. No wonder they failed you :-) Yup, and they did a lot of that <0.9 wink>. Luckily(?), Fortran is so eager to allow optimizations that failure due to numeric differences in conformance tests rarely withstood challenge. From chad.hughes at pnl.gov Wed Jun 1 18:35:27 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Wed, 01 Jun 2005 15:35:27 -0700 Subject: Thread Stack Size Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6139@pnlmse27.pnl.gov> I am using the threading module to create a great deal of threads. Is there any way to set the thread stack size? It looks like each thread is being given a default stack size of 1MB. I have looked all over and I cannot find a way to shrink the stack to a few KB. When I try to create a large number of threads (say 1000 of them) I run into trouble, due to the fact that I have one Gig of memory. -------------- next part -------------- An HTML attachment was scrubbed... URL: From val at vtek.com Thu Jun 2 11:59:28 2005 From: val at vtek.com (val) Date: Thu, 2 Jun 2005 11:59:28 -0400 Subject: link to the HP 3115 iPAQ - list of features for info -- $350 w/Bluetooth built-in Message-ID: <3g8on4FbbojvU1@individual.net> http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=5778810554&ssPageName=MER C_VIC_ReBay_Pr4_PcY_BIN From listserver at tdw.net Wed Jun 22 05:48:19 2005 From: listserver at tdw.net (Tim Williams) Date: Wed, 22 Jun 2005 10:48:19 +0100 Subject: need to strip stuff off email References: <11bhc9u7925cv38@news.supernews.com> Message-ID: <003701c5770f$855f7e90$ccbefea9@twilliams> > "nephish" wrote in message > news:mailman.723.1119399951.10512.python-list at python.org... > > hey there, > > i have a script that retrieves my email, but i need it to > > be able to strip all the stuff off except the body (the message itself) > > so i can later write it to a text file. > > > > anyone know how to accomplish this? > > thanks The body is: The rest of the email after "the first blank line after the subject header". In practice it is the first blank line. If you get the message into a string it can sometimes be easier to just RSPLIT the string at '\r\n\r\n', if the message is in a list then the body = '\r\n'.join(msg[x:]) where x = that blank line +1 , that way if you don't need any of the header info, you don't have to decode the message and rebuild it in a file. if you *are* using the email module, eg msg = email.message_from_file(a_file) then rsplit the msg to get the same result. As someone will no doubt point out, some emails are broken and parts of the headers will end up in the body (even when you view the email it in a client), this is very rare though. From chinook.nr at tds.net Sat Jun 18 04:51:06 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 18 Jun 2005 04:51:06 -0400 Subject: Migrating from Windows to OS X References: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> Message-ID: <0001HW.BED958BA00131F70F0407550@news.gmane.org> On Sat, 18 Jun 2005 03:26:23 -0400, ladasky at my-deja.com wrote (in article <1119079582.973569.191490 at f14g2000cwb.googlegroups.com>): > Hello, fellow programmers! > > I am sitting in front of a nice new PowerBook portable which has OS > 10.4 installed. The Python.org web site says that Apple has shipped OS > 10.4 with Python 2.3.5 installed. How exactly do I access this? I > have searched through the Applications and Libraries folders. I found > the site-packages directory, but nothing other than that. > > Thanks for your help, > John Ladasky > > You might also want to take a look at: http://undefined.org/python/#TigerPython24Fix That is if you want to use Python 2.4.1 There is also a Python SIG for us Mac elitists :~) http://mail.python.org/mailman/listinfo/pythonmac-sig Lee C From http Sat Jun 11 21:36:15 2005 From: http (Paul Rubin) Date: 11 Jun 2005 18:36:15 -0700 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <200506102209.49469.hancock@anansispaceworks.com> <7xekb84rsa.fsf@ruckus.brouhaha.com> Message-ID: <7x7jh0l5kg.fsf@ruckus.brouhaha.com> Andrew Dalke writes: > My question to you is - what is "something big"? I've not been > on any project for which "LAMP" can't be used, and nor do I > expect to be. After all, there's only about 100,000 people in > the world who might possibly interested using my software. (Well, > the software I get paid to do; not, say, the couple of patches I've > sent in to Python). If you're running a web site with 100k users (about 1/3 of the size of Slashdot) that begins to be the range where I'd say LAMP starts running out of gas. Yes, Slashdot is a LAMP site, but it's split across a rack full of servers and is spending kilobucks a month on colo space and hosting fees. Other similarly sized sites face similar expenses. It seems to me that by using implementation methods that map more directly onto the hardware, a site with Slashdot's traffic levels could run on a single modest PC (maybe a laptop). I believe LiveJournal (which has something more like a million users) uses methods like that, as does ezboard. There was a thread about it here a year or so ago. As a simple example, that article's advice of putting all fine grained session state into the database (so that every single browser hit sets off SQL queries) is crazy. One site I worked on got a huge speedup by simply storing the most frequently used stuff from the user session in a browser cookie. That required zero extra work to handle multiple servers (whichever server got the query, got the cookie) and it saved a ton of SQL traffic. As for "big", hmm, I'd say as production web sites go, 100k users is medium sized, Slashdot is "largish", Ebay is "big", Google is huge. From willie at macleod-group.com Sat Jun 18 17:53:03 2005 From: willie at macleod-group.com (willie at macleod-group.com) Date: 18 Jun 2005 14:53:03 -0700 Subject: Threading and serial port access References: <1119100180.442972.244100@g14g2000cwa.googlegroups.com> <3hilk5FhbnplU1@uni-berlin.de> Message-ID: <1119131583.931941.183540@g47g2000cwa.googlegroups.com> Diez wrote: > Apart from that the approach you use is wasting resources - if you are > concerned about that (or better style...) use e.g. twisted with the > serial and parallel support and its so-called select reactor. The idea > behind that concept is that the OS is responsible for scannig IO-Ports. > It notifies an application about newly arrived data by the system > function select - which means that your program sits and waits not > cosuming any resources until actual data arrives. See the module select > for an overview, and google for "python twisted serial". Thanks for the help, the code you previously posted worked, but I can see it could get very messy if the number of ports increased... I'm going to look at twisted python. Thanks again for the pointers, much appreciated. Regards William MacLeod From bwallis at NoSpAm.fathen.net Thu Jun 9 02:23:22 2005 From: bwallis at NoSpAm.fathen.net (Brian Wallis) Date: Thu, 09 Jun 2005 16:23:22 +1000 Subject: Saving/retrieving user preferences References: <42a78012@dnews.tpgi.com.au> Message-ID: <42a7e05c@dnews.tpgi.com.au> (my last post seemed to not get out, sorry if you see it twice) This may be a FAQ,but I cannot find it. I want to save user preferences, window sizes, recently opened file names, etc for a python application and I am looking for a package that does this in a way that is portable across unix/linux and windows (and mac would be nice as well). Is there a 'standard' package for doing this in python? thanks, -- brian... From chinook.nr at tds.net Sun Jun 19 21:29:40 2005 From: chinook.nr at tds.net (Chinook) Date: Sun, 19 Jun 2005 21:29:40 -0400 Subject: functions with unlimited variable arguments... Message-ID: <0001HW.BEDB94440002D142F00FF3B0@smtp.tds.net> Xah said unto the world: >oops... it is in the tutorial... sorry. > >though, where would one find it in the python reference? i>.e. the function def with variable/default parameters. > >This is not a rhetorical question, but where would one start to look >for it in the python ref? > >a language is used by programers. Subroutine definition with >variable/default parameters is a basic issue a programer wants to know, >and different languages differs very much in how they handle this. This >is what i mean that the language doc should be programing oriented, as >opposed to computer-sciency or implementation oriented... I don't get to the reference docs much. Mostly I use the quick reference guide and it's noted there in an easy to find manner. If you have not checked it out then see: http://rgruet.free.fr/#QuickRef Lee C From exogen at gmail.com Wed Jun 1 13:21:14 2005 From: exogen at gmail.com (Brian Beck) Date: 1 Jun 2005 10:21:14 -0700 Subject: Pressing A Webpage Button In-Reply-To: References: Message-ID: <1117646473.951893.167000@z14g2000cwz.googlegroups.com> Elliot Temple wrote: > How do I make Python press a button on a webpage? I looked at > urllib, but I only see how to open a URL with that. I searched > google but no luck. Check out mechanize: http://wwwsearch.sourceforge.net/mechanize/ -- Brian Beck Adventurer of the First Order From davecook at nowhere.net Wed Jun 22 14:14:11 2005 From: davecook at nowhere.net (Dave Cook) Date: Wed, 22 Jun 2005 18:14:11 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> Message-ID: On 2005-06-22, Cameron Laird wrote: > Are you saying that Python-based applications are particularly > vulnerable in this all-too-common scenario? If so, I'm not > getting it; why is the architecture described more fragile than > more traditional Windows-oriented development patterns? If not, > then, ... well then I truly don't get your point. Maybe the point is the downside of depending on installed DLLs rather than shipping your own. Dave Cook From magnus at thinkware.se Wed Jun 1 20:19:27 2005 From: magnus at thinkware.se (Magnus Lyck?) Date: 1 Jun 2005 17:19:27 -0700 Subject: plotting with Python References: <429aeac6$1@news.fhg.de> <429c2564$1@news.fhg.de> Message-ID: <258fd9b8.0506011619.78dd1290@posting.google.com> Rolf Wester wrote in message news:<429c2564$1 at news.fhg.de>... > Philippe C. Martin wrote: > > Look at wxPython > I will do it, thank you for your reply. What you want specifically for the drawing in wx is probably a Device Context. (Typically a wxClientDC, but you might want to swap to e.g. a wxPrinterDC at times...) Read more at http://wxwidgets.org/manuals/2.5.3/wx_dcoverview.html From devlai at gmail.com Tue Jun 28 15:13:36 2005 From: devlai at gmail.com (Devan L) Date: 28 Jun 2005 12:13:36 -0700 Subject: regulars expressions ? In-Reply-To: <42c18cc9$0$6342$636a15ce@news.free.fr> References: <42c18cc9$0$6342$636a15ce@news.free.fr> Message-ID: <1119986016.228538.63930@g14g2000cwa.googlegroups.com> re.findall(r'"?(.+?)"?(?:,|$)', yourtexthere) From peter at engcorp.com Mon Jun 13 20:26:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Jun 2005 20:26:48 -0400 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> <0q-dnXbbdaJNAzDfRVn-gA@powergate.ca> Message-ID: Steven D'Aprano wrote: > So going back to the original question... if I open in "r" mode a text > file which was created under Windows, I will get \r characters in the > text and have to deal with them regardless of what platform I am running > Python under. Correct? Almost, but the way you phrased that makes it incorrect in at least one case. I suspect you are clear on the actual situation now, but just to correct your wording: you will get \r characters and have to deal with them on any platform which does *not* use \r\n for its line endings. (Under Windows, of course, you won't have to deal with them at all.) > If I use "rU" mode Python suppress the \r characters. When I write a > string back, I'm responsible for making sure the EOL markers are correct > for whatever platform I expect the file to be read under. Unless Python > can somehow magically read my mind and know that even though I'm writing > the file under Linux it will be read later under Windows. Am I close? Python can't magically read your mind, although if you manage to steal the time machine (in the future) you could always just come back and fix the files as they are written, and you (in present time) would *think* that Python had magically read your mind... A few more trinkets: some programs on Windows will work just fine even if they encounter files with only \n line endings. Decent text editors will either adapt or let you specify what line ending should be expected. Trying always to work with only \n line endings in files you write will help us move towards the day when we can obliterate the abomination that is \r\n so try it out and use "rU" to read, "w" to write on Linux if that works in your case. -Peter From dsa at unilestemg.br Tue Jun 7 17:45:04 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Tue, 7 Jun 2005 21:45:04 +0000 Subject: Binary numbers In-Reply-To: <1118190881.484857.122970@f14g2000cwb.googlegroups.com> References: <1118190881.484857.122970@f14g2000cwb.googlegroups.com> Message-ID: <200506072145.04847.dsa@unilestemg.br> Hi ! Pardon me, but what itoa has to do it the history ? See ya ! Em Quarta 08 Junho 2005 00:34, Dan Bishop escreveu: > Douglas Soares de Andrade wrote: > > Hi ! > > > > How to work with binary numbers in python ? Is there a way to print a > > number in its binary form like we do with oct() or hex() ? > > > > Im doing a project that i have to work with binaries and i tired of > > convert numbers to string all the time to perform some operations. > > > > I searched about it in many places like python.org and google, but not > > found anything useful. > > Search for "itoa". -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From tim.golden at viacom-outdoor.co.uk Thu Jun 23 07:51:59 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Jun 2005 12:51:59 +0100 Subject: List of all installed applications (XP)? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB929@vogbs009.gb.vo.local> [Guy Lateur] | | | [TJG] | | What -- from your point of view -- is an "application"? | | Good question. Let me try to elaborate: I would like to know | if people in | our company (building techniques) are using non-licensed software (eg | Photoshop, Office, AutoCad). So I guess by 'application' I | mean commercial software packages like those. Hmmm. While I understand your requirement, it's not as thought there's some easily-discernible charactersistics of "commercial software packages which should have licenses but which don't" unless you're prepared to compile a list and to add to it over time. | Is it safe to assume those apps get listed in AppPath? I wouldn't have said so: AppPaths is basically useful if you want to be able to go Start > Run > blah.exe without having to hunt through "Program Files" etc. Since many apps simply set up a Start Menu shortcut, there's no need for this. | Just out of curiosity: can one read the info/list one gets in | Add/Remove | Programs? It's not a problem I get results that aren't | actually apps, but it | is important I get all apps. I honestly don't know: I imagine Googling around will give some hits (for the question in general and for Add/Remove in particular): it can hardly be an unheard of issue. If someone's solved it in one way, it's almost certainly possible to translate that to Python (or to use their tool, if it's accessible). I have an idea it's held in the registry, but I'm not sure. You could try running up regedit and searching for likely strings. By the sound of it, you're almost better off compiling a list of .exe from machines and building up a blacklist from those. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From grante at visi.com Mon Jun 6 15:45:46 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 06 Jun 2005 19:45:46 -0000 Subject: Destructive Windows Script References: Message-ID: <11a99vais6kj95f@corp.supernews.com> On 2005-06-06, Terry Reedy wrote: > OT but I am curious: does a metallic case act as a metallic shield, It depends on the metal and the case thickness. Thin sheet-aluminum provides virtually no magnetic shielding. Some good thick iron plate will provide shielding. > so that the case needs to be opened to do this? No. > (Conversely, is a magnet near a disk drive a danger to it?) Yes, if it's strong enough. >> wiped everything, including control tracks, and played >> with the R/W head and positioning magnets. > > I take this to mean the the drive is non-functional and might > have well been melted, except that demagnetising is cheaper. Yup. -- Grant Edwards grante Yow! Why are these at athletic shoe salesmen visi.com following me?? From gene.tani at gmail.com Mon Jun 6 22:17:31 2005 From: gene.tani at gmail.com (gene tani) Date: 6 Jun 2005 19:17:31 -0700 Subject: easiest way to split a list into evenly divisble smaller lists, and assign them to variables? In-Reply-To: <1118043546.195468.87720@g44g2000cwa.googlegroups.com> References: <1118040724.644534.259460@g44g2000cwa.googlegroups.com> <7xekbgj6y2.fsf@ruckus.brouhaha.com> <1118043546.195468.87720@g44g2000cwa.googlegroups.com> Message-ID: <1118110651.168113.280110@g14g2000cwa.googlegroups.com> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060 OR: collections.deque: http://python.org/doc/2.4/lib/deque-recipes.html flamesrock wrote: > hmmm..that makes much more sense. thanks :) From guy.lateurNNOOSSPPAAMM at pandora.be Thu Jun 23 15:00:31 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Thu, 23 Jun 2005 19:00:31 GMT Subject: List of all installed applications (XP)? References: Message-ID: | [TJG] | Hmmm. While I understand your requirement, it's not as | thought there's some easily-discernible charactersistics | of "commercial software packages which should have licenses | but which don't" No? Really? How disappointing.. ;) | [TJG] | By the sound of it, you're almost better off compiling | a list of .exe from machines and building up a blacklist | from those. That was kind of the idea at first. However, we have a file server (H:), and I've seen apps installed on it. So it's pretty hard to know who actually uses that app just by the .exe - could be several people, too, I guess. That's why I thought of the registry - which, as you rightfully pointed out, isn't a perfect strategy, either. I do understand that I can remove those apps by removing the .exe (+ containing folder, probably), but I'd also like to get an idea of who is using what right now (and why). That might come in handy at some point later on. Btw, is there a module called pyWhy or something? :) Maybe I should also follow Paul's advice and go through the registry on a vendor/app basis. I mean, ATM, I'm not really concerned about a user having, say, Cubase installed without a license. My priority right now is to make sure we have licenses for certain apps we use professionally/commercially (ACad, Office, ..). Thanks for the input, people, much appreciated, g From greg at cosc.canterbury.ac.nz Wed Jun 8 22:22:23 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 14:22:23 +1200 Subject: OO re-factoring (was Pythonese/Efficiency/Generalese critique [on Tutor]) In-Reply-To: References: Message-ID: <3gpnfeFdneoeU1@individual.net> Dan Sommers wrote: > I don't remember the original post, but methods and recursion are *not* > mutually exclusive (e.g., an Integer class with a factorial method, or a > binary tree class whose nodes are also binary trees). Also, don't think that you have to make everything OO. OO isn't necessarily better than non-OO. It's a means to an end, not an end in itself. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From steven.bethard at gmail.com Fri Jun 3 20:52:16 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 03 Jun 2005 18:52:16 -0600 Subject: how to get name of function from within function? In-Reply-To: References: Message-ID: Christopher J. Bottaro wrote: > Basically I want to wrap every function in try/except automatically. [snip] > every function (err, method) is enclosed in the exact > same try/except error handling code. Everytime I make a new function, I > copy/paste that try/catch block. Yes, has's suggestion is probably the right way to go here. I'm still uncertain as to your exact setup here. Are the functions you need to wrap in a list you have? Are they imported from another module? A short clip of your current code and what you want it to do would help. For example, if they are the only thing another module contains, you can use has's wrapFunction function and do something like: import functionmodule for name in dir(functionmodule): if not name.startswith('_'): func = wrapFunction(getattr(functionmodule, name)) setattr(functionmodule, name, func) > Is there something like PHP's __call() method in Python? I don't know. What does PHP's __call() do? I don't know PHP, and it wasn't in the online manual http://www.php.net/docs.php. >>>Also, is there a way to turn normal positional args into a tuple without >>>using *? Like this: >>> >>>def f(a, b, c): >>> print get_args_as_tuple() >>> >>> >>>>>>f(1, 2, 3) >>> >>>(1, 2, 3) >> >>Um... >> >>py> def f(a, b, c): >>... print (a, b, c) >>... >>py> f(1, 2, 3) >>(1, 2, 3) >> >>? > > In your method, if the name and/or number of positional arguments changes, > the body of the function must change. I want to avoid that. But if the name and/or number of positional arguments changes, you're already changing the function definition. What's the real use case here? Are you really just printing them? Or are you doing something else? STeVe From mailman at hanez.org Fri Jun 24 12:20:19 2005 From: mailman at hanez.org (Johannes Findeisen) Date: Fri, 24 Jun 2005 18:20:19 +0200 Subject: help! In-Reply-To: <20050624121401.GA7890@heaven.kostyrka.org> References: <03FB1C8A0749414494FE4726AADD7D4302A8C5B4@vkomexch1.zh.corp> <20050624121401.GA7890@heaven.kostyrka.org> Message-ID: <1119630019.4945.4.camel@phantom.wg.xw3.org> On Fri, 2005-06-24 at 14:14 +0200, Andreas Kostyrka wrote: > On Fri, Jun 24, 2005 at 02:49:01PM +0300, Eser ?etinkaya wrote: > > > > > > In your documentation, it is written : > > " > > os.path.getatime(path) > > Return the time of last access of path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise os.error if the file does not exist or is inaccessible. New in version 1.5.2. Changed in version 2.3: If os.stat_float_times() returns True, the result is a floating point number. > > " > > > > what do you mean by "access" ? this function gives same outputs with the " os.path.getmtime(path) " > > What can change an acess time of a path different from modification? > > Is there any mistakes in the implementation or am i missing some points? > > > Just out of curiosity, does the filesystem support seperate a/m/c > times? Hello Andreas, some filesystems do support that. From the ext2 specification ( http://e2fsprogs.sourceforge.net/ext2intro.html ): "As a response to these problems, two new filesytems were released in Alpha version in January 1993: the Xia filesystem and the Second Extended File System. The Xia filesystem was heavily based on the Minix filesystem kernel code and only added a few improvements over this filesystem. Basically, it provided long file names, support for bigger partitions and support for the three timestamps." ^^^^^^^^^^^^^^^^ Regards -- Johannes Findeisen From tpherndon at gmail.com Thu Jun 23 16:46:18 2005 From: tpherndon at gmail.com (Peter Herndon) Date: 23 Jun 2005 13:46:18 -0700 Subject: suggestions invited In-Reply-To: <1119555027.087947.100970@g43g2000cwa.googlegroups.com> References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119552092.000448.10230@g47g2000cwa.googlegroups.com> <1119555027.087947.100970@g43g2000cwa.googlegroups.com> Message-ID: <1119559578.075157.289290@g44g2000cwa.googlegroups.com> Reasonable enough. As per Mike's suggestion below, building a few web pages to document the apps is a good start. To expand on that idea, you could write daemons/cron jobs, perhaps in Python if Python runs on OS/400, that monitor each app's status and log that information to the web server. You could then write a web application that takes the monitoring data and formats it appropriately for human consumption. Perhaps an RSS or Atom feed for each application's status. I don't know anything about OS/400, but if it has a tool similar to syslog, you could configure the application hosts to report their status to a remote syslogd, perhaps on your web server, and parse the log file for the status data. From tim.peters at gmail.com Wed Jun 1 22:19:17 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 1 Jun 2005 22:19:17 -0400 Subject: Strange KeyError using cPickle In-Reply-To: <1117677914.469065.301370@g49g2000cwa.googlegroups.com> References: <1117671230.384189.120030@f14g2000cwb.googlegroups.com> <1117677914.469065.301370@g49g2000cwa.googlegroups.com> Message-ID: <1f7befae0506011919534e0a1a@mail.gmail.com> [Tim Peters] >> What is "XWwz"? Assuming it's a bizarre typo for "open", change the >> 'w' there to 'wb'. Pickles are binary data, and files holding pickles >> must be opened in binary mode, especially since: >> >>> ... >>> (on WinXP, CPython 2.4.1) [Rune Strand] > Thanks Tim. The bizarre 'typo' appears to be caused by ad-blocking > software confusing python code with javascript (i think). > > I had the feeling this was a red facer. > > Setting the protocol to 0 (text) also make it work. Not really. Repeat: pickles are binary data, and files holding pickles must be opened in binary mode. The horribly named "text mode" pickles (and this is one reason they're called "protocol 0" now instead) are binary data too. Pickles created with protocol 0 may also fail if transported across platforms, if written to a file opened in text mode. Pickle files should always be opened in binary mode, regardless of pickle protocol, and regardless of platform. From listserver at tdw.net Tue Jun 21 12:49:25 2005 From: listserver at tdw.net (Tim Williams) Date: Tue, 21 Jun 2005 17:49:25 +0100 Subject: smtplib and TLS References: <1119034830.168876.26290@f14g2000cwb.googlegroups.com><7xmzpoyusq.fsf@ruckus.brouhaha.com> <1119368342.884338.266040@g43g2000cwa.googlegroups.com> Message-ID: <001c01c57681$302b4cd0$ccbefea9@twilliams> ----- Original Message ----- From: "Matthias Kluwe" > > Have you verified that its your end that is broken, not gmail's, do other > > servers give the same response ? > > No, I have not -- I should have, as I know now: Connecting, starttls, > login and sending mail works fine without the above mentioned error > using my previous mail provider. > > Does that mean Gmail is in error here? I don't know... Looks like it is GMAIL , (though TLS is not required to be able to send via smtp.gmail.com:587 ) TLS using TLSlite also fails when connecting to GMAIL, but not to other servers. ('5 send:', '(16:39:23) ehlo x\r\n') ('6 reply:', '(16:39:23) 250-mx.gmail.com at your service\r\n') ('6 reply:', '(16:39:23) 250-SIZE 20971520\r\n') ('6 reply:', '(16:39:23) 250-8BITMIME\r\n') ('6 reply:', '(16:39:23) 250-STARTTLS\r\n') ('6 reply:', '(16:39:23) 250 ENHANCEDSTATUSCODES\r\n') ('5 send:', '(16:39:23) STARTTLS\r\n') ('6 reply:', '(16:39:23) 220 2.0.0 Ready to start TLS\r\n') ('Status:', '(16:39:24) 2202.0.0 Ready to start TLS') ('5 send:', '(16:39:24) ehlo x\r\n') ('6 reply:', '(16:39:24) 250-mx.gmail.com at your service\r\n') ('6 reply:', '(16:39:24) 250-SIZE 20971520\r\n') ('6 reply:', '(16:39:24) 250-8BITMIME\r\n') ('6 reply:', '(16:39:24) 250-AUTH LOGIN PLAIN\r\n') ('6 reply:', '(16:39:24) 250 ENHANCEDSTATUSCODES\r\n') ('5 send:', '(16:39:24) noop\r\n') ('6 reply:', '(16:39:24) 250 2.0.0 OK\r\n') ('5 send:', '(16:39:24) rset\r\n') ('6 reply:', '(16:39:24) 250 2.1.0 Flushed d61sm2700367wra\r\n') ('5 send:', '(16:39:24) noop\r\n') ('6 reply:', '(16:39:24) 250 2.0.0 OK\r\n') ('5 send:', '(16:39:24) quit\r\n') Traceback (most recent call last): File "C:\test\tls.py", line 103, in ? s.quit() File "C:\test\smtplib.py", line 737, in quit self.docmd("quit") File "C:\test\smtplib.py", line 395, in docmd return self.getreply() File "C:\test\smtplib.py", line 367, in getreply line = self.file.readline() File "C:\Python23\Lib\site-packages\tlslite\FileObject.py", line 152, in readline data = self._sock.recv(self._rbufsize) File "C:\Python23\Lib\site-packages\tlslite\TLSRecordLayer.py", line 393, in recv return self.read(bufsize) File "C:\Python23\Lib\site-packages\tlslite\TLSRecordLayer.py", line 182, in read for result in self.readAsync(max, min): File "C:\Python23\Lib\site-packages\tlslite\TLSRecordLayer.py", line 201, in readAsync for result in self._getMsg(ContentType.application_data): File "C:\Python23\Lib\site-packages\tlslite\TLSRecordLayer.py", line 564, in _getMsg for result in self._getNextRecord(): File "C:\Python23\Lib\site-packages\tlslite\TLSRecordLayer.py", line 737, in _getNextRecord raise TLSAbruptCloseError() tlslite.errors.TLSAbruptCloseError From steve at REMOVETHIScyber.com.au Sat Jun 25 21:21:38 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 11:21:38 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: On Sat, 25 Jun 2005 19:23:18 +0000, Mandus wrote: > Sat, 25 Jun 2005 16:06:57 GMT skrev Lee Harr: >>>> Higher-order functions like map, filter and reduce. As of Python 3000, >>>> they're non-python tricks. Sigh - i guess it's time for me to get to know >>>> list comprehensions a bit better. >>>> >> >> >> Couldnt there just be a "functional" module ?... >> >> from functional import map, filter, reduce > > but lambda is grammar, so probably not so easy to import? "from __future__ import something" can change the compile-time behaviour of Python, so it is possible. -- Steven. From grahamd at dscpl.com.au Thu Jun 9 23:18:05 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 9 Jun 2005 20:18:05 -0700 Subject: Embedding: many interpreters OR one interpreter with many thread states ? References: <1118239578.831376.218370@o13g2000cwo.googlegroups.com> <3gppn9FdnnldU1@individual.net> Message-ID: <1118373485.748978.310660@z14g2000cwz.googlegroups.com> Greg Ewing wrote: > adsheehan at eircom.net wrote: > > > - creating many sub-interpreters (Py_NewInterpreter) with a thread > > state each > > > > Or > > > > - creating one interpreter with many thread states (PyThreadState_New) > > My understanding is that using multiple interpeters isn't > really supported properly, despite there being apparent > support in the API. So I suggest using a single interpeter > with multiple threads. Huh. Mod_python uses multiple interpreters and within each interpreter could be running multiple threads at one time corresponding to different incoming HTTP requests. It hasn't helped though that a bug was introduced in Python 2.3.5/4.0 which has been causing grief for some users creating additional threads from within Python code itself. :-( http://sourceforge.net/tracker/index.php?func=detail&aid=1163563&group_id=5470&atid=105470 From adurdin at gmail.com Wed Jun 29 02:27:42 2005 From: adurdin at gmail.com (Andrew Durdin) Date: Wed, 29 Jun 2005 16:27:42 +1000 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: <42c1ecaf$1@nntp0.pdx.net> References: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> <86y88um4y3.fsf@bhuda.mired.org> <42c1ecaf$1@nntp0.pdx.net> Message-ID: <59e9fd3a0506282327180dec05@mail.gmail.com> On 6/29/05, Scott David Daniels wrote: > result = [(lambda: expr0), lambda: expr1][cond]() Which still has an error, as evidenced by the following: >>> cond = "" >>> result = [(lambda: expr0), lambda: expr1][cond]() Traceback (most recent call last): File "", line 1, in ? TypeError: list indices must be integers Corrected version: result = [(lambda: expr0), lambda: expr1][bool(cond)]() Or if using python < 2.3: result = [(lambda: expr0), lambda: expr1][__import__("operator").truth(cond)]() Andrew From travis.ray at gmail.com Mon Jun 13 19:50:52 2005 From: travis.ray at gmail.com (travis ray) Date: Mon, 13 Jun 2005 19:50:52 -0400 Subject: reading a python file object in c extension crashes python Message-ID: Hi, I have an extension in which a file object is created in python and passed down to a c extension which attempts to read from it or write to it. Writing to the file pointer seems to work okay, but reading from it results in EBADF. It also causes python to crash on exit. I've attached the minimal (I think) c code, python code, build script, build log, and run log. Any and all help is greatly appreciated. Thanks. System: Win-XP Professional Compiler: Vc7 (MSVS 2003) Python: Python 2.4.1 Builder: SCons 0.96.1 P.S. Sorry for including everything in one message. I keep getting bounced when I attach them. ### file:my_module.c ------------------------------------------------- #include #define MAXLEN 128 int my_read(char *buffer, int max, FILE *fp) { int n = 0; fprintf (stdout, "[c] pre-read: errno=%d, fp=%x\n", errno, fp); n = fread(buffer, 1, max, fp); fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d, data='%s'\n", errno, fp, n, buffer); return n; } int my_write(const char *buffer, FILE *fp) { int n = 0; fprintf (stdout, "[c] pre-write: errno=%d, fp=%x, data='%s'\n", errno, fp, buffer); n = fprintf(fp, "%s", buffer); fprintf (stdout, "[c] post-write: errno=%d, fp=%x, count=%d\n", errno, fp, n); return n; } static PyObject * my_module_my_read(PyObject *self, PyObject *args) { char buffer[MAXLEN]; int count = 0; FILE *fp = NULL; PyObject* py_file = NULL; memset((void*)&(buffer),0,sizeof(char)*MAXLEN); if (!PyArg_ParseTuple(args, "O", &py_file)) return NULL; if (PyFile_Check(py_file)) { count = my_read((char*)&(buffer), MAXLEN, PyFile_AsFile(py_file)); return Py_BuildValue("(is)", count, (char*)buffer); } return NULL; } static PyObject * my_module_my_write(PyObject *self, PyObject *args) { char buffer[MAXLEN]; int count = 0; FILE *fp = NULL; PyObject* py_file = NULL; const char* py_string; memset((void*)&(buffer),0,sizeof(char)*MAXLEN); if (!PyArg_ParseTuple(args, "sO", &py_string, &py_file)) return NULL; if ((PyFile_Check(py_file)) && (py_string != NULL)) { count = my_write(py_string, PyFile_AsFile(py_file)); return Py_BuildValue("i", count); } return NULL; } static PyMethodDef MyModuleMethods[] = { {"my_read", my_module_my_read, METH_VARARGS, "read at most 128 bytes from a file"}, {"my_write", my_module_my_write, METH_VARARGS, "write a string to a file"}, {NULL,NULL,0,NULL} }; PyMODINIT_FUNC initmy_module(void) { PyObject *m; m = Py_InitModule("my_module", MyModuleMethods); } ### file: my_module.py ------------------------------------------------ import my_module filename = "hello.txt" fp1 = open(filename, "wb") print "[py] pre-write: fp=%s" % (fp1) result1 = my_module.my_write("Hello, World!", fp1) print "[py] result=", result1 fp1.close() fp2 = open(filename, "rb") print "[py] pre-read: fp=%s" % (fp2) result2 = my_module.my_read(fp2) print "[py] result=", result2 #fp2.close() # crashes python here EBADF when fp2.close() is called print "done" # crashes python here when fp2.close() is commented out ### file: Sconstruct -------------------------------------------------- env = Environment() import os python_include_path = os.path.join(os.path.sep,'Python24','include') python_lib_path = os.path.join(os.path.sep,'Python24','libs') python_libs = 'python24' my_module_name = 'my_module' my_module_sources = 'my_module.c' library = env.SharedLibrary(my_module_name, my_module_sources, CPPPATH=[python_include_path], LIBPATH=[python_lib_path], LIBS=[python_libs]) ### file: build.log --------------------------------------------------- scons: Reading SConscript files ... scons: done reading SConscript files. scons: Building targets ... cl /nologo /I\Python24\include /c my_module.c /Fomy_module.obj my_module.c link /nologo /dll /out:my_module.dll /implib:my_module.lib /LIBPATH:\Python24\libs python24.lib my_module.obj Creating library my_module.lib and object my_module.exp scons: done building targets. ### file: run.log ----------------------------------------------------- [py] pre-write: fp= [c] pre-write: errno=0, fp=7c38b548, data='Hello, World!' [c] post-write: errno=0, fp=7c38b548, count=13 [py] result= 13 [py] pre-read: fp= [c] pre-read: errno=0, fp=7c38b548 [c] post-write: errno=9, fp=7c38b548, count=0, data='' [py] result= (0, '') done From aahz at pythoncraft.com Thu Jun 9 23:57:44 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Jun 2005 20:57:44 -0700 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> Message-ID: In article <1118372596.003161.290690 at g49g2000cwa.googlegroups.com>, wooks wrote: > >I am sorry. I don't have any other Python books to sell so it won't >happen again. The reason people jumped on you is that historically groups get overrun with "just one ad" posts, and there goes the neighborhood. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From peter at engcorp.com Sat Jun 18 12:52:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:52:06 -0400 Subject: pysqlite - Checking the existance of a table In-Reply-To: References: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> Message-ID: Gerhard H?ring wrote: > Or you can query the sqlite_master table (don't know any specification > off-hand, but it contains the schema information). Item #9 in the FAQ (http://www.sqlite.org/faq.html#q9) shows it as: CREATE TABLE sqlite_master ( type TEXT, name TEXT, tbl_name TEXT, rootpage INTEGER, sql TEXT ); -Peter From grante at visi.com Wed Jun 22 13:08:42 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 22 Jun 2005 17:08:42 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> Message-ID: <11bj6oqh1jbruae@corp.supernews.com> On 2005-06-22, Scott David Daniels wrote: >> I finally figured out why one of my apps sometimes fails under >> Win32 when it always works fine under Linux: Under Win32, the >> pickle module only works with a subset of floating point >> values. In particular the if you try to dump/load an infinity >> or nan value, the load operation chokes: > > There is no completely portable way to do this. Python deals with all sorts of problems for which there is no completely portable solution. Remember: "practicality beats purity." > Any single platform can have a solution, but (since the C > standards don't address how NaNs and Infs are represented) > there is not a good portable way to do the pickle / unpickle. Likewise, there is no completely portable python implimentation. Any single platform can have a Python implimentation, but since the C standards don't address a universal standard for "a computer" there is not a good portable way to do Python. I guess we'd better give up on Python. :) > It is nice the exception is raised, since at one point it was > not (and a simple 1.0 was returned). That would be even worse. >> [NaN and Infinity are prefectly valid (and extremely useful) >> floating point values, and not using them would require huge >> complexity increases in my apps (not using them would probably >> at least triple the amount of code required in some cases).] > > You could check to see if the Python 2.5 pickling does a better > job. Otherwise, you've got your work cut out for you. Fixing it is really quite trivial. It takes less than a dozen lines of code. Just catch the exception and handle it. def load_float(self): s = self.readline()[:-1] try: f = float(s) except ValueError: s = s.upper() if s in ["1.#INF", "INF"]: f = 1e300*1e300 elif s in ["-1.#INF", "-INF"]: f = -1e300*1e300 elif s in ["NAN","1.#QNAN","QNAN","1.#IND","IND","-1.#IND"]: f = -((1e300*1e300)/(1e300*1e300)) else: raise ValueError, "Don't know what to do with "+`s` self.append(f) Obviously the list of accepted string values should be expanded to include other platforms as needed. The above example handles Win32 and glibc (e.g. Linux). Even better, add that code to float(). -- Grant Edwards grante Yow! Is the EIGHTIES at when they had ART DECO visi.com and GERALD McBOING-BOING lunch boxes?? From michele.simionato at gmail.com Thu Jun 9 10:33:21 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Jun 2005 07:33:21 -0700 Subject: Generating HTML from python In-Reply-To: References: Message-ID: <1118327601.205586.289990@f14g2000cwb.googlegroups.com> You could generate your report in reStructuredText format (Google is your friend) and then convert them in HTML, PS, PDF, etc. Michele Simionato From claird at lairds.us Thu Jun 23 10:08:02 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 23 Jun 2005 14:08:02 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <42b9d01e$0$2588$da0feed9@news.zen.co.uk> Message-ID: In article , Dave Cook wrote: >On 2005-06-23, Peter Hansen wrote: . . . >>Type checking? SQLite currently supports >> neither. > >sqlite3 has a "strict affinity" mode, but I'm not exactly sure how one sets >it. > >http://www.sqlite.org/datatype3.html . . . While I'm still learning SQLite3, I already know enough to reinforce Mr. Cook's point, and report that Version 3 re- tains the data manager's yummy lightness, while significantly enhancing its functionality in such regards as type correctness. From news at NOwillmcguganSPAM.com Wed Jun 29 18:54:30 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 29 Jun 2005 23:54:30 +0100 Subject: Graphs/statistics using wxPython In-Reply-To: <42c2df8b$1@griseus.its.uu.se> References: <42c2df8b$1@griseus.its.uu.se> Message-ID: <42c326a8$0$18805$da0feed9@news.zen.co.uk> Jan Danielsson wrote: > Hello all, > > I wanted to plot some statistics, so I wrote a simple wxPython class > to do it. Then I realized that I would like to draw bar graphs, so I > added that too. > > Since I'm a complete Python newbie, I haven't done much of it the > "Python way", I suspect. So, I'm wondering if someone would like to show > me some of the tricks I should have used. > > You can find the code at: > http://user.it.uu.se/~jada3673/drawtest.py > > It's not finished[*], but it is usable. Oh, you can do whatever you > want with it. Since I had never touched wxPython before working with > this, I used some doodle application as a starting point. > > Btw... Has anyone already written statistics classes for wxPython? If > so, where can I find them? If nothing similar exists, I'll probably add > support for loading data from a file, and a few other features. Feel > free to make requests or enhancements. > > [*] There are some size/offset bugs which I am aware of, but they are > easily fixed. I just haven't got around to it yet. If you ever want to add an extra dimension, then using OpenGL with wxWindows is a breeze. See attached file for a 3d pie char.. Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: piechartwindow.py URL: From mwidj at yahoo.com Tue Jun 28 16:45:53 2005 From: mwidj at yahoo.com (mwidj at yahoo.com) Date: 28 Jun 2005 13:45:53 -0700 Subject: Python C extenstion and __init__.py Message-ID: <1119991553.608909.196840@f14g2000cwb.googlegroups.com> I'm building python extension for some solaris specific functions. My setup.py looks like this: setup.py: from distutils.core import setup, Extension sol_ex = Extension('sun.solaris', ['src/solarismodule.c', ]) setup (name = "solaris", version = "0.1", description = "Solaris specifics system calls module", ext_modules = [ sol_ex ], After doing the 'python setup.py build' successfuly, I setup a test script that looks like the following : test.py: import sun.solaris After setting the PYTHONPATH to ./build/lib.solaris-2.9-sun4u-2.3 and running the test.py, I got the following: Traceback (most recent call last): File "test.py", line 1, in ? import sun.solaris ImportError: No module named sun.solaris It turns out that in addition to solaris.so, I also need __init__.py (manually created) in ./build/lib.solaris-2.9-sun4u-2.3 to make the extension works. My question is how do I automate the creation (in setup.py) of __init__.py so that when I build the extension, it will also creates __init__.py in the build directory? Thanks From andreas at kostyrka.org Mon Jun 6 13:22:38 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 6 Jun 2005 19:22:38 +0200 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: <20050606172238.GA17775@heaven.kostyrka.org> On Sat, Jun 04, 2005 at 11:49:28PM -0700, Robert Kern wrote: > Well, the FSF at least thinks that internal use within an organization > does not constitute distribution. Well, the problem are contractors. It's very important (for example in Germany) for a number of legal reasons that contractors are separate from the organization. This basically makes it a case of distribution. And while the GPL FAQ claims that this is not a problem, it seems only to handle the easy case: Company X gives a "standard" SP to contractor C, and C returns SP2. While this is okay, the problems start when X discovers that it wants to distribute SP2 to contractor C2, because it has to do this under the GPL. Contractor C2 might by free will refrain from distributing SP2, but putting that as a requirement on paper would violate the GPL. Basically having a GPLed internal program limits what a company might do with it in the future ;) Andreas From tim.peters at gmail.com Wed Jun 22 20:46:49 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 22 Jun 2005 20:46:49 -0400 Subject: pickle broken: can't handle NaN or Infinity under win32 In-Reply-To: <42b9e6d4$1@nntp0.pdx.net> References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> Message-ID: <1f7befae05062217465da484ab@mail.gmail.com> [with the start of US summer comes the start of 754 ranting season] [Grant Edwards] >>>> Negative 0 isn't a NaN, it's just negative 0. [Scott David Daniels] >>> Right, but it is hard to construct in standard C. [Paul Rubin] >> Huh? It's just a hex constant. [Scott David Daniels] > Well, -0.0 doesn't work, C89 doesn't define the result of that, but "most" C compilers these days will create a negative 0. > and (double)0x80000000 doesn't work, In part because that's an integer , and in part because it's only 32 bits. It requires representation casting tricks (not conversion casting tricks like the above), knowledge of the platform endianness, and knowledge of the platform integer sizes. Assuming the platform uses 754 bit layout to begin with, of course. > and.... I think you have to use quirks of a compiler to create > it. You at least need platform knowledge. It's really not hard, if you can assume enough about the platform. > And I don't know how to test for it either, x < 0.0 is > not necessarily true for negative 0. If it's a 754-conforming C compiler, that's necessarily false (+0 and -0 compare equal in 754). Picking the bits apart is again the closest thing to a portable test. Across platforms with a 754-conforming libm, the most portable way is via using atan2(!): >>> pz = 0.0 >>> mz = -pz >>> from math import atan2 >>> atan2(pz, pz) 0.0 >>> atan2(mz, mz) -3.1415926535897931 It's tempting to divide into 1, then check the sign of the infinity, but Python stops you from doing that: >>> 1/pz Traceback (most recent call last): File "", line 1, in ? ZeroDivisionError: float division That can't be done at the C level either, because _some_ people run Python with their 754 HW floating-point zero-division, overflow, and invalid operation traps enabled, and then anything like division by 0 causes the interpreter to die. The CPython implementation is constrained that way. Note that Python already has Py_IS_NAN and Py_IS_INFINITY macros in pyport.h, and the Windows build maps them to appropriate Microsoft-specific library functions. I think it's stuck waiting on others to care enough to supply them for other platforms. If a platform build doesn't #define them, a reasonable but cheap attempt is made to supply "portable" code sequences for them, but, as the pyport.h comments note, they're guaranteed to do wrong things in some cases, and may not work at all on some platforms. For example, the default #define Py_IS_NAN(X) ((X) != (X)) is guaranteed never to return true under MSVC 6.0. > I am not trying to say there is no way to do this. I am > trying to say it takes thought and effort on every detail, > in the definition, implementations, and unit tests. It's par for the course -- everyone thinks "this must be easy" at first, and everyone who persists eventually gives up. Kudos to Michael Hudson for persisting long enough to make major improvements here in pickle, struct and marshal for Python 2.5! From http Tue Jun 28 21:16:33 2005 From: http (Paul Rubin) Date: 28 Jun 2005 18:16:33 -0700 Subject: How to find Windows "Application data" directory?? Message-ID: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> I'm writing a Windows program that needs to store some user files. The logical place to store them is in "Application Data", right? Is there a good way to find the correct location of that directory, preferably without any C extensions? It's ok if the directory is found at installation time rather than runtime, and bdist_wininst does have a way to find it from a post-installation script. The trouble is that the post-installation script doesn't seem to have an obvious way to communicate the info to the application for later use! Any suggestions? Thanks. From correiajREMOVECAPS at hotmail.com Mon Jun 6 23:48:39 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Tue, 07 Jun 2005 03:48:39 GMT Subject: separate IE instances? References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> Message-ID: "Chris Curvey" wrote in message news:1118102755.309346.169810 at g14g2000cwa.googlegroups.com... > I need to create a set of IE instances that have different sets of > session cookies. I thought that using the win32com.DispatchEx function > would do this, but it doesn't seem to. In other words > > ie1 = win32com.DispatchEx("InternetExplorer.Application") > ie2 = win32com.DispatchEx("InternetExplorer.Application") > > gives me two IE windows, but only one IEXPLORE process in Task Manager. > And if I login to a site that uses session cookies to track sessions > using ie1, when I move ie2 to the same site, ie2 is already logged in. > > Any help appreciated. > > -Chris from win32com.client import Dispatch ie1 = pythoncom.CoCreateInstance("InternetExplorer.Application", None,\ pythoncom.CLSCTX_SERVER, pythoncom.IID_IDispatch) ie1 = Dispatch(ie1) ie2 = pythoncom.CoCreateInstance("InternetExplorer.Application", None,\ pythoncom.CLSCTX_SERVER, pythoncom.IID_IDispatch) ie2 = Dispatch(ie2) . . . From stephen.thorne at gmail.com Mon Jun 20 03:42:43 2005 From: stephen.thorne at gmail.com (stephen.thorne at gmail.com) Date: 20 Jun 2005 00:42:43 -0700 Subject: login website that using PHP In-Reply-To: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> References: <1119233498.837593.76450@g47g2000cwa.googlegroups.com> Message-ID: <1119253363.266640.228090@z14g2000cwz.googlegroups.com> pbpscript is a little python toolkit for simulating a webbrowser, specifically for doing testing. It handles all the cookies and stuff for you. You might want to have a look at it. Stephen. From grante at visi.com Wed Jun 22 22:54:06 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 23 Jun 2005 02:54:06 -0000 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> <7xzmth3nv5.fsf@ruckus.brouhaha.com> Message-ID: <11bk92er94785df@corp.supernews.com> On 2005-06-23, Paul Rubin wrote: > Scott David Daniels writes: >> >>>Negative 0 isn't a NaN, it's just negative 0. >> >> >> >>Right, but it is hard to construct in standard C. >> > Huh? It's just a hex constant. >> Well, -0.0 doesn't work, and (double)0x80000000 doesn't work, >> and.... I think you have to use quirks of a compiler to create >> it. And I don't know how to test for it either, x < 0.0 is >> not necessarily true for negative 0. > > Aren't we talking about IEEE 754 arithmetic? Mainly, yes. > There's some specific bit pattern(s) for -0.0 and you can > assign a float variable to such a pattern. Yup. -- Grant Edwards grante Yow! My Aunt MAUREEN was at a military advisor to IKE & visi.com TINA TURNER!! From python at rcn.com Tue Jun 7 03:02:19 2005 From: python at rcn.com (Raymond Hettinger) Date: 7 Jun 2005 00:02:19 -0700 Subject: the python way? References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> Message-ID: <1118127739.226122.280830@g47g2000cwa.googlegroups.com> import random from itertools import ifilter, ifilterfalse def reinterpolate(word): word = list(word) random.shuffle(word) isvowel = dict.fromkeys('aeiouy').has_key vowels = ifilterfalse(isvowel, word) consonants = ifilter(isvowel, word) result = [] for v, c in map(None, vowels, consonants): if c: result.append(c) if v: result.append(v) return ''.join(result) print reinterpolate("encyclopedias") From grante at visi.com Sat Jun 18 09:37:52 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 13:37:52 -0000 Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> Message-ID: <11b88tgtjrm3p01@corp.supernews.com> On 2005-06-18, Xah Lee wrote: [...] > Fuck the python doc wasted my time. Fuck python coders. Each > time i tried to use python doc and got frustrated because it > being grossly incompetent, i'll post a message like this, no > more frequent than once a week. This will go on as long the > python community does nothing to fix it or that i remain > coding in python. I guess it's kind of him to warn everybody who hasn't already plonked him... -- Grant Edwards grante Yow! I'm wet! I'm wild! at visi.com From jobauk at hotmail.com Tue Jun 28 06:29:35 2005 From: jobauk at hotmail.com (Jorge Louis de Castro) Date: Tue, 28 Jun 2005 10:29:35 +0000 Subject: Non-blocking raw_input In-Reply-To: Message-ID: Thanks very much for you reply. I have indeed tried the msvcrt module but none of the examples given works as described on a XP+SP2 box. I have also looked at the twisted module but some functions there do not work on windows too, and I was told by one of the devs that it would stay that way for some time. Basically, I just want to wait for user input and echo it, though while the user is not typing anything I'd like to have a background thread printing "Come on, you're taking too long" or similar stuff. The problem is that I can only read (and in batch) the background thread printout messages on the console after feeding the raw_input function. I can't find any examples or useful directions on the documentation and I've spent a few days googling this to no avail. Is it not possible to have the thread print its stuff and then return to raw_input() ? Or use any function other than raw_input? Any code examples, pseudo-code, or documentation directions will be highly appreciated! Thanks in advance Cheers jorge >From: Peter Hansen >To: python-list at python.org >Subject: Re: Non-blocking raw_input >Date: Mon, 27 Jun 2005 18:43:45 -0400 > >Jorge Louis de Castro wrote: > > Could anyone tell me whether I can find a non blocking alternative to > > raw_input that works on windows? Is there not a python way of achieving > > this? Can I find it somewhere in the documentation? > > Any help will be highly appreciated > >Depending on what your requirements are (since you don't really say), >the functionality in the standard msvcrt module might help. >-- >http://mail.python.org/mailman/listinfo/python-list From no at spam Tue Jun 28 00:03:20 2005 From: no at spam (D H) Date: Mon, 27 Jun 2005 23:03:20 -0500 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: <9sKdnVdyJtGNUV3fRVn-gw@comcast.com> BORT wrote: > So, that said... In ~simplest~ terms for the stated goal -- Forth or > Python? > ...the goal is NOT the spelling tutor... it is learning how to use a > tool to solve a problem. I am asking which tool is more suited to an > otherwise arbitrary direction of "spelling tutor program." Python is easier to learn that most other popular programming languages. For a games approach, check out this online "book" targeted to kids: http://staff.easthighschool.net/lee/computers/book/ It uses pygame and Lee Harr's pygsear. For another graphical approach, playing around with images and sound files, see the Jython Environment for Students (JES). Jython is python running on top of java's virtual machine. http://coweb.cc.gatech.edu/mediaComp-plan/94 http://coweb.cc.gatech.edu/mediaComp-plan/27 http://coweb.cc.gatech.edu/mediaComp-plan For text-to-speech, if you are using Windows and python, see the pyTTS module and this link: http://www.cs.unc.edu/~parente/tech/tr02.shtml If you are using jython, see FreeTTS instead: http://freetts.sourceforge.net/docs/index.php But since your son is only 10 years old, I'd really recommend first some non-python development environments that are even more geared to kids: - Lego Mindstorms, which has a graphical programming environment to control robots you build (you connect a flow chart to describe the program instead of having to type and indent everything perfectly). It is targetted specifically for kids his age, but it is a bit expensive. - http://agentsheets.com/ - Very neat java-based authoring tool, but unfortunately costs money too. Trial version only lasts 10 days, but you can learn a lot in that time using this tool. - NetLogo (and the older version StarLogo): http://ccl.northwestern.edu/netlogo/ Uses Logo to script hundreds of "turtles" in parallel. This is a free tool. - http://e-slate.cti.gr/ really awesome authoring tool, but hasn't been updated in a couple of years because I guess the funding ran out. From kent37 at tds.net Sat Jun 4 05:40:25 2005 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Jun 2005 05:40:25 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: <42A1715F.5060101@jessikat.fsnet.co.uk> References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> <42A1715F.5060101@jessikat.fsnet.co.uk> Message-ID: <42a176d0$1_2@newspeer2.tds.net> Robin Becker wrote: > Ilpo Nyyss?nen wrote: >> >> with locking(mutex), opening(readfile) as input: >> ... > > with EXPR as x: > BLOCK > > EXPR can be a tuple so the above would be ambiguous. I don't think EXPR can be a tuple; the result of evaluating EXPR must have __enter__() and __exit__() methods. *x* can be a tuple. Kent From thys at sentechsa.com Mon Jun 27 11:45:29 2005 From: thys at sentechsa.com (Thys Meintjes) Date: Mon, 27 Jun 2005 17:45:29 +0200 Subject: delphi to python converter Message-ID: <1119887129.5222.23.camel@localhost.localdomain> Greets, I have need of a Delphi/pascal to python converter. Googling didn't suggest any obvious leads so I'm trying here... Thanks Thys From peterbe at gmail.com Fri Jun 17 16:16:37 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 17 Jun 2005 13:16:37 -0700 Subject: ANN: IssueTrackerProduct 0.6.9 with AJAX and Reports Message-ID: <1119039397.722318.243960@g49g2000cwa.googlegroups.com> (I don't know if this is the right place to make an announcement but I've seen other projects doing it so I thought why not?) I've now released version 0.6.9 of the IssueTrackerProduct http://www.issuetrackerproduct.com/News/0.6.9 It's a issue/bug tracker built on top of Zope (Python) that is known for being simple but powerful. Homepage: www.issuetrackerproduct.com From donn at u.washington.edu Fri Jun 3 17:29:14 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 03 Jun 2005 14:29:14 -0700 Subject: calling ksh script from python References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> <1117788937.207065.18670@z14g2000cwz.googlegroups.com> Message-ID: In article <1117788937.207065.18670 at z14g2000cwz.googlegroups.com>, ronan_boisard at yahoo.com wrote: > thanks for your input... > well I just find out that modifying environment through ksh call is not > possible (can't get the new evironment back to python). I think the > best thing to do is to translate all my ksh to pure python... I thought > that I could re-use some stufff, but I guest I'm going to translate > everything... Right, that's true - more generally, no process can modify another's environment. Donn Cave, donn at u.washington.edu From gerrit.muller at embeddedsystems.nl Wed Jun 29 02:46:14 2005 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Wed, 29 Jun 2005 08:46:14 +0200 Subject: whois like functionality on Windows? In-Reply-To: <342dnX3zuo5XB1zfRVn-pg@powergate.ca> References: <342dnX3zuo5XB1zfRVn-pg@powergate.ca> Message-ID: Peter, Thomas, thanks for your suggestion. I did indeed look broader than whois, and reverse DNS maybe a better description. Unfortunately I did try the socket.gethostbyaddr("194.109.137.226"), but the result was a disappointing "host not found", both at home on an XP machine as well as at work on a NT machine. Your comments stimulated me too experiment with this apporach, and I discovered that unresolved IP addresses in my old logfiles return "host not found". However many IP addresses in my new logfile can be translated successfully! Apparantly there are IP addresses that cannot be reversely resolved by the DNS servers. I did translate these addresses manually so far via the whois service. So you definitely helped me a lot, but I keep interested in a complementary whois solution. kind regards, Gerrit > Gerrit Muller wrote: > >> I am migrating a website from a UNIX based machine to an Windows >> machine. In the logfiles I got from the old machine I mostly got >> domain names and sometimes only IP addresses. The Windows machine >> seems to produce only IP addresses. >> >> Somehow I cannot find a windows solution to translate an IP address >> back into a domain-name. Searching with Google shows that more people >> have been wrestling with this problem. >> >> I did find working whois scripts, but unfortunately: > > [snip] > > Part of your problem is looking for the wrong thing. You are looking > for the capability provided by "domain name servers" (DNSes), not > "whois" servers. But Thomas has just given you the solution... > > -Peter -- Gaudi systems architecting: From agriff at tin.it Fri Jun 17 02:42:56 2005 From: agriff at tin.it (Andrea Griffini) Date: Fri, 17 Jun 2005 06:42:56 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118914590.744021.53950@z14g2000cwz.googlegroups.com> <3hdfqlFgeeorU1@individual.net> Message-ID: On Thu, 16 Jun 2005 10:30:04 -0400, "Jeffrey Maitland" wrote: >Also I think the fact that you think your were diteriating just goes to show >how dedicated you are to detail, and making sure you give the right advice >or ask the right question. [totally-OT] Not really, unfortunately. I found not long ago that I used the very same word eight times in two consecutive sentences, plus similar words and words with similar endings. Re-reading that phrase the day later it seemed like something got stuck in my brain while I was writing that. Sure more or less the idea was there, and IMO clear enough to be understood, but the form and the choice of words seemed incredibly poor. I was curious of this strange fact and I checked out other text I was writing in that period. What really scared me is that this word repeating seemed a quite evident problem. This *both* in italian (my native language) and in english. Googling for old posts I however found that years ago my english was even worse than it is now... but this repetition was not present (not that evident, that is). Needless to say I spent some hours googling for informations about this kind of word repetition problem :D Anyway after some time things got better. I always thought about our intellect being something "superior" to this world made of fragile bones and stinking flesh. However I realized that there's probably no real magic in it... knowing there are pills to make you happy is sort of shocking from a philosophical point of view :-) If you'll see me walking around with an esoskeleton and an happy face it will mean I tried the chemical approach ;) (don't try to understand this phrase, either you know what I mean - and you like dilbert strips - or it can't make sense). Andrea From jurgenex at hotmail.com Sat Jun 18 09:49:04 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sat, 18 Jun 2005 13:49:04 GMT Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> <1119082311.658973.169610@o13g2000cwo.googlegroups.com> Message-ID: Xah Lee wrote: > i wanted to find out if Python supports eval. e.g. > > somecode='3+4' > print eval(somecode) # prints 7 > > in the 14 hundred pages of python doc, where am i supposed to find > this info? Why are you asking in a Perl NG for information about Python? Or are you also asking your backer how to trim a steak? jue From agriff at tin.it Mon Jun 13 02:13:13 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 13 Jun 2005 06:13:13 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: On Sun, 12 Jun 2005 19:53:29 -0500, Mike Meyer wrote: >Andrea Griffini writes: >> On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen >> wrote: >> Also concrete->abstract shows a clear path; starting >> in the middle and looking both up (to higher >> abstractions) and down (to the implementation >> details) is IMO much more confusing. > >So you're arguing that a CS major should start by learning electronics >fundamentals, how gates work, and how to design hardware(*)? Because >that's what the concrete level *really* is. Start anywhere above that, >and you wind up needing to look both ways. Not really. Long ago I've drawn a line that starts at software. I think you can be a reasonable programmer even without the knowledge about how to design hardware. I do not think you can be a reasonable programmer if you never saw assembler. >Admittedly, at some level the details simply stop mattering. But where >that level is depends on what level you're working on. Writing Python, >I really don't need to understand the behavior of hardware >gates. Writing horizontal microcode, I'm totally f*cked if I don't >understand the behavior of hardware gates. But you better understand how, more or less, your computer or language works, otherwise your code will be needless thousand times slower and will require thousand times more memory than is necessary. Look a recent thread where someone was asking why python was so slow (and the code contained stuff like "if x in range(low, high):" in an inner loop that was itself pointless). >In short, you're going to start in the middle. I've got "bad" news for you. You're always in the middle :-D. Apparently it looks like this is a constant in our universe. Even counting (i.e. 1, 2, 3, ...) is not the "start" of math (you can go at "lower" levels). Actually I think this is a "nice" property of our universe, but discussing this would bring the discussion a bit OT. >Is it really justified to confuse them all >by introducing what are really extraneous details early on? I simply say that you will not able to avoid introducing them. If they're going to write software those are not "details" that you'll be able to hide behind a nice and perfect virtual world (this is much less true about bus cycles... at least for many programmers). But if you need to introduce them, then IMO is way better doing it *first*, because that is the way that our brain works. You cannot build on loosely placed bricks. >You've stated your opinion. Personally, I agree with Abelson, Sussman >and Sussman, whose text "The Structure and Interpretation of Computer >Programs" was the standard text at one of the premiere engineering >schools in the world, and is widely regarded as a classic in the >field: they decided to start with the abstract, and deal with concrete >issues - like assignment(!) later. Sure. I know that many think that starting from higher levels is better. However no explanation is given about *why* this should work better, and I didn't even see objective studies about how this approach pays off. This is of course not a field that I've investigated a lot. What I know is that every single competent programmer I know (not many... just *EVERY SINGLE ONE*) started by placing firmly concrete concepts first, and then moved on higher abstractions (for example like structured programming, OOP, functional languages ...). Andrea From tom at dtsam.com Mon Jun 6 11:11:06 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Mon, 6 Jun 2005 10:11:06 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: "bruno modulix" wrote in message news:42a3fc70$0$30762$626a14ce at news.free.fr... > Thomas Bartkus wrote: > > "rzed" wrote in message > > news:Xns9667883C1D343jreeder at 63.223.7.253... > > > > > >>So what do you think? What's wrong with the picture? Why isn't > >>there a greater priority to work in this direction? > > > > > > > What's wrong with the picture? > > > > Just one teeny little item. > > > > The Python world lacks the phenomenally successful development models > > enjoyed by the now ancient Turbo Pascal, Delphi and Visual Basic. > > AND > > If the likes of Visual Basic can have it, then it becomes really, *really* > > hard to convince the world that Python is a serious, professional system. > > You mean the "wimp gui builder + db -> ui pipeline" model ? If yes, C > doesn't have it, C++ doesn't have it (in fact most languages doesn't > have it) - and the fact is that C and C++ are usually considered as much > more "serious and professionnal" than VB and the likes. > From simon.brunning at gmail.com Tue Jun 21 05:35:08 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 21 Jun 2005 10:35:08 +0100 Subject: FAQ: __str__ vs __repr__ In-Reply-To: References: <42b021ba$1@griseus.its.uu.se> Message-ID: <8c7f10c6050621023518890fa4@mail.gmail.com> On 6/15/05, Peter Hansen wrote: > __repr__ shouldn't be anything, if you don't have an actual need for it. > Neither should __str__. Oh, I don't know. __str__ is so frequently useful in debugging and logging that I always try and do something useful with it. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tundra at tundraware.com Thu Jun 23 17:57:51 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jun 2005 17:57:51 EDT Subject: OT: Re: Looking For Geodetic Python Software In-Reply-To: <7xu0jodc5u.fsf@ruckus.brouhaha.com> References: <447po2-iqt.ln1@eskimo.tundraware.com> <3hvrhjFj3qfmU1@uni-berlin.de> <7xu0jodc5u.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tim Daneliuk writes: > >>Huh? When traversing along the surface of the earth, it's curvature >>is relevant in computing total distance. An airplane flies more-or-less >>in a straight line above that curvature. For sufficiently long airplane >>routes (where the ascent/descent distance is trivial compared to the >>overall horizontal distance traversed), a straight line path shorter >>than the over-earth path is possible. That's why I specified the >>desire to compute both path lengths. Where's the humor? > > > It's just not clear what you meant: > > A) The shortest path between two points on a curved surface is > called a geodesic and is the most meaningful definition of > "straight line" on a curved surface. The geodesic on a sphere is > sometimes called a "great circle". > > B) By a straight line you could also mean the straight line through > the 3-dimensional Earth connecting the two points on the surface. > So the straight line from the US to China would go through the > center of the earth. > > C) Some people seem to think "straight line" means the path you'd > follow if you took a paper map, drew a straight line on it with a > ruler, and followed that path. But that path itself would depend > on the map projection and is generally not a geodesic, and neither > is it straight when you follow it in 3-space. Yeah, after rereading my original question, I realize that it could be read that way. My Bad. What I had in mind was this: A ------------------------------ E --------------------------- / \ / \ Where A was an airplane's line of flight between endponts and E was the great circle (geodesic) distance over ground. It seemed to me that if the ascent/descent distance for A is very small compared to the length of A, the flight distance would be shorter than the over-ground distance. But, as Rocco points out in another response, this is not so. I stand (well, sit, actually) corrected! Many thanks to all of you who took the time to unscramble my English and lack of geometric understanding... ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From edvard+news at majakari.net Wed Jun 29 06:10:52 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 29 Jun 2005 13:10:52 +0300 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119956464.362328.290370@o13g2000cwo.googlegroups.com> Message-ID: <87ekala2xf.fsf@titan.staselog.com> phil writes: > From 30 years of application development experience I will tell you > NOT HUMBLY, that Python is easily the most productive, the most read-write > and the most elegant of any of the above. Handsdown better than Java, the > runner up in that group. I don't want to start a flamewar here - but I would like to point out that not only the language you use affects productivity, but also tools that support working with the language affect a lot too. For example, I once thought I would start writing any documents longer than say, two A4 pages with lout (I've used LaTeX so far). However, realising how much more supporting tools, add-ons and utilities LaTeX had, I stayed with that (moreover, some of the other people already new LaTeX but didn't know lout). Recently I participated in creating a visual FSM editor as Eclipse plugin. I hadn't used Eclipse before, but seeing how easy it was to create tests, refactor code (bicyclerepairman is not even close to features offered by Eclipse) and use gazillion other tools designed to improve Java productivity made me realise the language has a really, really great selection of tools and utilities available. Now, I earn my bread by coding Python and I do like coding in Python the most, but sometimes I think I would have been better off with Java - not because of the language, but because of the environment and sheer selection of tools available. Let me emphasize a little more. Even though Python itself is great, I think we don't have quite yet tools that offer * Industrial-grade reverse-engineering tool (ie. automatic UML diagram generation out of code) which also supports creating classes/interfaces out of UML diagrams, and modifies the other automatically when the other changes * Automatic unit test case generation (pydev is going to this direction, I think) * Decent code coverage tools - and I don't mean statement coverage, but path coverage or multi-condition coverage Just see how many handy tools there are for Java if you use Eclipse: http://eclipse-plugins.2y.net/eclipse/plugins.jsp (Yes, I know that many of those plugins are not related to any language but Eclipse and that some of the plugins are specifically Python related, but most of the good stuff is for Java Development) Pydev looks really promising, though. With Eclipse, I think it is a very good alternative to commercial Python IDEs and could mature to the Other Way(TM) for developing Python programs (the other is, of course, vi(m)/(X)Emacs) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From jjl at pobox.com Sat Jun 4 17:54:01 2005 From: jjl at pobox.com (John J. Lee) Date: 04 Jun 2005 21:54:01 +0000 Subject: Q: functional/equational language, smells a little of Python Message-ID: <871x7hn5za.fsf@pobox.com> Saw this on LWN: http://q-lang.sourceforge.net/ Looks interesting, and reminiscent of symbolic algebra systems like Mathematica. Also, the website mentions dynamic typing and "Batteries Included", which made me think of Python. Damned silly name, though (perhaps pre-Google?). Anybody here used it? Snippet from the FAQ: 2. Yet another "Haskell for the poor"? Not quite. Even though the syntax and some of the stuff in the standard library looks superficially similar, Q is different in a number of ways: * First and foremost, Q is an equational rather than just a functional language, meaning that it is based on general term rewriting instead of the lambda calculus (which is just one, and very special, rewriting system). In particular, Q has no a priori distinction between "constructors" and "defined" function symbols, and argument patterns are not restricted to "constructor terms". This allows you to have symbolic evaluation rules like the following distributivity rule: X*(Y+Z) = X*Y+X*Z. Such rules are not allowed in ML and Haskell because they violate the "constructor discipline". Moreover, the Q interpreter also happily reduces expressions involving variables, so that you can try your definitions with symbolic inputs (e.g., map F [X,Y] will evaluate to [F X,F Y]), which is quite useful for debugging purposes. * While other functional languages are either "eager" or "lazy", Q tries to give you the best of both worlds: It uses eager (call-by-value) evaluation by default (which lends itself to an efficient implementation), but also allows you to define your own special forms, which can be used to implement both call-by-name functions and lazy data constructors. Using special forms you can also define your own "meta functions" which manipulate arbitrary (not necessarily irreducible) expressions as literal terms. This gives you full control over the reduction strategy, where this is desired, as well as a kind of "macros" and "self-modifying programs", since constructs like lambda abstractions can be analyzed, transformed and constructed in many ways before they are actually evaluated. * Q uses dynamic typing. This has become a rare feature in contemporary functional languages, which usually employ a Hindley/Milner type system which offers more safety at the expense of restricting polymorphism. Q gives you back the flexibility of good old Lisp-style ad-hoc polymorphism and even allows you to extend the definition of existing operations (including built-in functions and operators) to your own data types. Moreover, Q has a Smalltalk-like object-oriented type system which supports data encapsulation and (single) inheritance. This makes it possible to manage complex, polymorphic data with ease. * Q takes the pragmatic route in that it provides (monad-free) imperative programming features such as imperative I/O and mutable data cells, similar to the corresponding facilities in ML. While one may argue about these, they certainly make life easier when programming complex I/O stuff such as graphical user interfaces. * Last but not least, the Q programming system comes with batteries included. There are quite a few add-on modules interfacing to third-party libraries which, while not as comprehensive as the facilities provided by traditional scripting languages like Perl and Python, allow you to tackle most practical programming problems with ease. In particular, multimedia and computer music is an area where Q shines, providing facilities to handle graphics, digital audio and MIDI in a convenient and efficient manner (efficient enough for soft realtime applications), which go well beyond what is currently being offered for other functional languages. Some of Q's flexibility comes at a price. In particular, Q's symbolic evaluation capabilities as a term rewriting language dictate that the language is essentially exception-free. This means that an "ill-formed" expression (such as "division by zero" or, more generally, the application of a function to data for which there is no corresponding definition) does not, by default, raise an exception, but instead the expression is already in "normal form", i.e., it evaluates to itself. As a remedy, Q provides facilities to add explicit error rules which raise exceptions, and to handle exceptions in a suitable manner. Another limitation is that Q does not allow you to have arbitrary local definitions in the style of Haskell and ML's "let" and "where" clauses. In Q, "where" clauses are limited to variable definitions (similar to Haskell's pattern bindings), but local rewriting rules are not supported as they would wreak havoc on the term rewriting semantics. You will also notice that Q lacks most of the syntactic sugar found in Haskell. This is partly due to my laziness, but it also keeps the language and the core system simple. Using Q's symbolic processing capabilities, the usual bits like lambda abstractions, pattern matching conditionals and list comprehensions can easily be written in Q itself (although this does not offer quite the same performance as when they are provided as builtins, of course). John From hancock at anansispaceworks.com Wed Jun 1 14:02:02 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 1 Jun 2005 13:02:02 -0500 Subject: Newbie learning OOP In-Reply-To: <429a2379@news.eftel.com> References: <1117374143.284962.3080@z14g2000cwz.googlegroups.com> <429a2379@news.eftel.com> Message-ID: <200506011302.03349.hancock@anansispaceworks.com> On Sunday 29 May 2005 03:18 pm, John Machin wrote: > LenS wrote: > > Trying to learn OOP concepts and decided to use Python for this > > purpose. I have coded the following CLASS and it seems to work fine. > > Any comments on the code or suggestions would be appreciated. > A practical problem: not everbody's name can be shoe-horned into the > first/initial/last model. You face catastrophic loss of information. > > Some examples, with "last" name in capitals: > > J. Edgar HOOVER -> J E HOOVER > Rip J. VAN WINKLE -> Rip J VAN > Jean Paul DE LA SALLE -> Jean P DE > DE LA SALLE, Jean Paul -> LA S DE > MAO Tse Tung -> Tse T MAO # or MAO T Tung > MAO Tse-tung -> Tse-tung M # or an IndexError > MAO Zedong -> Zedong M # or an IndexError > Vigdis ERIKSDOTTIR -> Vigdis E # and lost the gender, too > Gunnlaug ILLUGASON Ormstunga -> Gunnlaug I Ormstunga # nickname > "Snakestongue" > Ivan Denisovich SHUKHOV -> Ivan D SHUKHOV # and lost father's "first" > name, too > Friedrich Heinrich Karl VON UND ZU HOHENLOHE -> Friedrich H Karl > NGUYEN Thi Thanh Van -> Thi T NGUYEN > # "Thi" means "female" and "Nguyen" is the "last" name of about 50% of > the Vietnamese population ... While I might say something snide about unnecessarily crucifying a piece of "toy" code for learning OOP, this is *really* nice set of test cases! Thank you, I'm saving this for reference. :-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ironfroggy at gmail.com Wed Jun 1 13:45:36 2005 From: ironfroggy at gmail.com (ironfroggy) Date: 1 Jun 2005 10:45:36 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117646486.821360.128400@g47g2000cwa.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> Message-ID: <1117647935.916469.164160@g47g2000cwa.googlegroups.com> because i need the representations of the other systems types to themselves be python classes, and so i need a metaclass to make sure they follow certain rules. This metaclass is for that system what type is for python, and type is an object, which is a type. same thing, no? From steve at REMOVEMEcyber.com.au Thu Jun 9 01:21:21 2005 From: steve at REMOVEMEcyber.com.au (Steven D'Aprano) Date: Thu, 09 Jun 2005 15:21:21 +1000 Subject: Incorrect number of arguments References: <42A7CDB0.4030703@REMOVEMEcyber.com.au> Message-ID: <42A7D1D1.7040704@REMOVEMEcyber.com.au> Steven D'Aprano wrote: > I worked around this problem by predicting what error message to expect > given N expected arguments and M supplied arguments. Yuck: this is a > messy, inelegant, ugly hack :-( Thank goodness that functions are first > class objects that support introspection :-) *eureka moment* I can use introspection on the function directly to see how many arguments it accepts, instead of actually calling the function and trapping the exception. > So, I'm wondering if there is a good reason why TypeError is generated > instead of (say) ArgumentError, or if it is just a wart of the language > for historical reasons? Still a good question though. Why is it TypeError? -- Steven. From dalke at dalkescientific.com Mon Jun 13 22:18:40 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Tue, 14 Jun 2005 02:18:40 GMT Subject: "also" to balance "else" ? References: Message-ID: Ron Adam wrote: > It occurred to me (a few weeks ago while trying to find the best way to > form a if-elif-else block, that on a very general level, an 'also' > statement might be useful. So I was wondering what others would think > of it. > for x in : > BLOCK1 > if : break # do else block > also: > BLOCK2 > else: > BLOCK3 For this specific case you could rewrite the code in current Python as for x in : BLOCK1 if : BLOCK3 break else: BLOCK2 In order for your proposal to be useful you would need an example more like the following in current Python for x in : ... if : BLOCK3 break ... if : BLOCK3 break else: BLOCK2 That is, where "BLOCK3;break" occurs multiple times in the loop. My intuition is that that doesn't occur often enough to need a new syntax to simplify it. Can you point to some existing code that would be improved with your also/else? > while : > BLOCK1 > if : break # jump to else > also: > BLOCK2 > else: > BLOCK3 > > Here if the while loop ends at the while , the BLOCK2 > executes, or if the break is executed, BLOCK3 executes. which is the same (in current Python) as while : BLOCK1 if : BLOCK3 break else: BLOCK2 > In and if statement... > > if : > BLOCK1 > elif : > BLOCK2 > elif : > BLOCK3 > also: > BLOCK4 > else: > BLOCK5 > > Here, the also block would execute if any previous condition is true, > else the else block would execute. That is ... funky. When is it useful? One perhaps hackish solution I've done for the rare cases when I think your proposal is useful is while 1: if : BLOCK1 elif : BLOCK2 elif : BLOCK3 else: # couldn't do anything break BLOCK4 break > I think this gives Pythons general flow control some nice symmetrical > and consistent characteristics that seem very appealing to me. Anyone > agree? No. Having more ways to do control flow doesn't make for code that's easy to read. My usual next step after thinking (or hearing) about a new Python language change is to look at existing code and see if there's existing code which would be easier to read/understand and get an idea if it's a common or rare problem. Perhaps you could point out a few examples along those lines? Andrew dalke at dalkescientific.com From philippe at philippecmartin.com Tue Jun 21 16:01:59 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 21 Jun 2005 20:01:59 GMT Subject: Python choice of database References: Message-ID: I guess I use databases to store .... data ;-) and I do not wish to worry about the type of data I'm storing. That's why I love to pickle. I understand that during an optimization phase, decisions might be taken to handle data otherwise. Regards, Philippe GMane Python wrote: > For my database, I have a table of user information with a unique > identifier, and then I save to the filesystem my bitmap files, placing the > unique identifier, date and time information into the filename. Why stick > a photo into a database? > > For instance: > > User Table: > uniqueID: 0001 > lNane: Rose > fName: Dave > > Then save the bitmap with filename: > 0001_13:00:00_06-21-2005.bmp > > To make things faster, I also have a table of filenames saved, so I can > know exactly which files I want to read in. > > -Dave From future_retro at yahoo.co.uk Fri Jun 10 06:58:56 2005 From: future_retro at yahoo.co.uk (Marc Wyburn) Date: 10 Jun 2005 03:58:56 -0700 Subject: python create WMI instances Message-ID: <4c26f60c.0506100258.21c78fea@posting.google.com> Hi all, I am struggling with a vb - python code conversion. I'm using WMI to create printers on remote machines using (in VB); set oPrinter = oService.Get("Win32_Printer").SpawnInstance_ oPrinter.DriverName = strDriver oPrinter.PortName = strPort oPrinter.DeviceID = strPrinter oPrinter.Put_(kFlagCreateOnly) In python I have logged onto the WMI service on the remote machine and I can run things like c.new.AddPrinterConnection so I know that I am connected and working OK. I don't get any errors when I create a new object with SpawnInstance_ but when I try to set the value of oPrinter.Drivername I get an error saying that the Drivername object doesn't exist. Does anyone know how to set the values of the object using either the method above or with the WMI module? I think the WMI module only allows access to modify methods such ADDPrinterConnection or Create (from Win32_Service). Thanks,MW. From __peter__ at web.de Thu Jun 2 02:25:50 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Jun 2005 08:25:50 +0200 Subject: Performance Issues please help References: <1117668847.964682.92390@o13g2000cwo.googlegroups.com> Message-ID: PyPK wrote: > I was testing this piece of code and it takes about 24-30 seconds to do > a look up on a list(m) of size 1000x1000 > m -> list of size 1000x1000 > import time > print time.ctime() > box = {} > for r,row in enumerate(m): > for c,e in enumerate(row): > if box.has_key(e): > params = box[e] > box[e] = ( min(c, params[0]), min(r, params[1]), > max(c, params[2]), max(r, params[3] ) ) > else: > box[e] = [c, r, c, r] > print time.ctime() > > Can some one tell me what exactly is taking more time here. Is it > because I am using dictionaries or what is the problem. Can some one > help me improve this .Is there a better way to write this. AFAICT the row index 'r' can only grow. Therefore one min() and one max() should be superfluous (untested): def make_box(m): box = {} for r, row in enumerate(m): for c, e in enumerate(row): if e in box: left, top, right, bottom = box[e] box[e] = (min(c, left), top, max(c, right), r) else: box[e] = (c, r, c, r) return box Peter From tjreedy at udel.edu Sun Jun 5 03:34:37 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Jun 2005 03:34:37 -0400 Subject: method = Klass.othermethod considered PITA References: <87oeallp44.fsf@pobox.com> <6qmdnR7ry4wF0D_fRVn-hA@speakeasy.net> Message-ID: > Steven Bethard wrote: > >> John J. Lee wrote: >> >>> It seems nice to do this >>> >>> class Klass: >>> >>> def _makeLoudNoise(self, *blah): >>> ... >>> >>> woof = _makeLoudNoise >> >> Out of curiosity, why do you want to do this? I have occasionally seen this usage where it made sense. I vaguely remember cases where the same function/method met two demands that required two different names. An example would be a __special__ method also exposed publicly as 'special' ( something) without the underscores. Or some other interface required a different name. A related usage is a true specialization in which one or more parameters is given a default or constant value. Terry J. Reedy From mfranklin1 at gatwick.westerngeco.slb.com Fri Jun 3 07:30:10 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 03 Jun 2005 12:30:10 +0100 Subject: SFTP In-Reply-To: <5C1296A3D8CC9C4EB1EB9DDC08D746F6060D7FBC@njrarsvr039a.us.ups.com> References: <5C1296A3D8CC9C4EB1EB9DDC08D746F6060D7FBC@njrarsvr039a.us.ups.com> Message-ID: Kornfeld Rick (sys1rak) wrote: > Good Morning > > I have scoured the internet looking for an Python SFTP API. So far, I > have been unable to find a suitable answer. Our needs are pretty basic. > FTP & TELNET are being removed from our environment and I need to > utilize SFTP for file transfers. > > As is probably said often, I am new to Python (love it) and need a > solution that provides adequate examples and documentation. I am hoping > for an open source answer, however, I am not ruling out having to > purchase something. > > Can anyone shed some light on this for me ? > Strange the second hit on a google for python sftp was this:- http://www.lag.net/paramiko/ I also implemented (using pexpect) a very basic 'interface' to command line sftp) http://pexpect.sourceforge.net/ pexpect is *nix only (as far as I know) both of these come with simple to follow examples... Martin. From sub1ime_uk at yahoo.com Mon Jun 20 12:24:41 2005 From: sub1ime_uk at yahoo.com (sub1ime_uk at yahoo.com) Date: 20 Jun 2005 09:24:41 -0700 Subject: sudoku dictionary attack Message-ID: <1119284681.053888.65470@z14g2000cwz.googlegroups.com> Thought I'd offer a method for solving all possible 9x9 sudoku puzzles in one go. It'll takes a bit of time to run however (and 9x9 seems to be about as big as is reasonably possible before combinatorial explosion completely scuppers this type of program)... Basic idea:- Start with a grid initialised with: 123456789 234567891 345678912 456789123 567891234 678912345 789123456 891234567 912345678 Note that all rows and columns contain all 9 digits (but that the sub-tiles aren't correct for a sudoku solution). Next write a program which permutes all 9 columns, and then for each of those permutations permutes the last 8 rows. This will, I believe, generate all possible grids with no digit repetitions in any row or column. It will generate 14,631,321,600 (9!*8!) possible sudoku candidates. Finally, check each candidate to see if any 3x3 subtile has a repeated digit in it and discard as soon as a repeat is found (sooner the better). Any that come through unscathed get written as a 82 (81 + lf) char string to an output file. I've written a short program (in Python; see below) that tries out this idea. Indications are that my HP nc6000 laptop can check around 30,000 candidates/sec and that c.0.15% of them are valid sudoku solutions. That means it would take around 6.5 days to generate the between 20-30 million possible sudoku solutions it will find. That would require around 2GB in uncompressed disk storage. Gzip does a VERY good job of compressing files containing this type of data -- so I'd expect well over 80% compression (might even fit on a CD then). Once you've generated the solution data then comes the fun of searching it efficiently which I leave as an exercise for the reader :-) Regards, sub1ime_uk (at) yahoo (dot) com ================================================================== #!python # # sudoku.py - generate all valid sudoku solutions # # Usage: sudoku # eg: sudoku 9 3 # Whare:- # N is the grid size (ie 9 for 9x9) # S is the sub-tile size (3 for 3x3) # # (c) 2005 sub1ime_uk (at) yahoo (dot) com # import sys from gzip import GzipFile from time import time def permute(s): if len(s)==0: return if len(s)==1: yield s return for i in range(len(s)): for t in permute(s[:i]+s[i+1:]): yield s[i:i+1]+t return def populate(sz, ini): tile = [] for i in range(sz): tile.append([]) for j in range(sz): x = chr((i+j)%sz+ord(ini)) tile[i].append(x) return tile def subtilesok(t, c, r, n, s): for x in range(0, n, s): for y in range(0, n, s): d = {} for i in range(s): cn = c[x+i] for j in range(s): rn = r[y+j] d[t[cn][rn]] = 1 if len(d.keys())!=n: return 0 return 1 def displaytile(t, c, r, lf): lfstr='' print for i in r: row = [] for j in c: row.append(t[j][i]) r=''.join(row) lfstr += r print " ",r print lf.write(lfstr+"\n") def fact(n): if n<2: return 1 return n*fact(n-1) if __name__ == '__main__': st = time() logf = GzipFile("c:\\temp\\sudoku.gz", "w") N=int(sys.argv[1]) S=int(sys.argv[2]) estimate = fact(N)*fact(N-1) if N!=S*S: print "Subtile size", S, "not sqrt of tile size", N sys.exit(1) cols = [x for x in range(N)] rows = [x for x in range(1, N)] primarytile = populate(N, '1') count = 0 answc = 0 for colp in permute(cols): for rowp in permute(rows): count += 1 if subtilesok(primarytile, colp, [0]+rowp, N, S): answc += 1 ct = time() et=ct-st if et>0.0: print "Found: %d out of %d (%.2f%%) checked" % (answc, count, (answc*100./count)) print "Progress: %.2f%%" % ((count*100./estimate)) print "Elapsed time: %.2f secs, checked: %d/s, found %d/s." % (et, (count/et), (answc/et)) print "Estimate time to go: %.2f hours" % ((estimate-count)*et/(count*3600.)) else: print "%d / %d (%5.2f%%)" % (answc, count, (answc*100./count)) displaytile(primarytile, colp, [0]+rowp, logf) print print "Checked", count,"tiles. Found", answc,"answers." logf.close() sys.exit() =================================================================== From petr at tpc.cz Mon Jun 13 03:50:50 2005 From: petr at tpc.cz (McBooCzech) Date: 13 Jun 2005 00:50:50 -0700 Subject: how to operate the excel by python? In-Reply-To: References: Message-ID: <1118649050.843794.234280@g14g2000cwa.googlegroups.com> > i want to compare the content in excel,but i don't know whick module to use! > can you help me? Read "Python programming on Win32" book, use win32api module. According to Chad's advices about Excel (VBA) constants, you can find following link usefull as well. http://fox.wikis.com/wc.dll?Wiki~ExcelConstants~VFP HTH Petr From tiissa at nonfree.fr Sat Jun 11 13:51:48 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 11 Jun 2005 19:51:48 +0200 Subject: Dynamic Lists, or...? In-Reply-To: <1118511053.455332.231570@g44g2000cwa.googlegroups.com> References: <1118511053.455332.231570@g44g2000cwa.googlegroups.com> Message-ID: <42ab24b0$0$28776$626a14ce@news.free.fr> Lorn wrote: > I'm trying to figure out a way to create dynamic lists or possibly > antother solution for the following problem. I have multiple lines in a > text file (every line is the same format) that are iterated over and > which need to be compared to previous lines in the file in order to > perform some simple math. Each line contains 3 fileds: a descriptor and > two integers. Here is an example: > > rose, 1, 500 > lilac, 1, 300 > lilly, 1, 400 > rose, 0, 100 Do you have to maintain a list or just the current value? Also I did not find it clear why you have to compare with previous line? Anyway, I think dictionnary may be useful there: >>> input = """rose, 1, 500 ... lilac, 1, 300 ... lilly, 1, 400 ... rose, 0, 100""" >>> >>> entries = [l.split(',') for l in input.split('\n')] >>> >>> d = {} >>> for k, op, n in entries: ... if int(op) == 1: ... d[k] = d.get(k, 0) + int(n) ... else: ... d[k] = d.get(k, 0) - int(n) ... >>> print d {'rose': 400, 'lilly': 400, 'lilac': 300} >>> That may not be what you want but there may be some things for you to use. And you can of course keep the full list of operation in d. From guy.lateur at pandora.be Fri Jun 24 15:49:05 2005 From: guy.lateur at pandora.be (guy lateur) Date: 24 Jun 2005 12:49:05 -0700 Subject: Office COM automatisation - calling python from VBA Message-ID: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Hi all, I am trying to write some code (macro's, if you like) to glue together our Office applications (mainly Word, Excel and Outlook). We have a lot of different projects going on simultaneously. The idea is to develop a centralized framework (starting point, common interface) for my users to view/control their documents/correspondence, on a per project basis. As an example, I'd like to have a control (button, menu entry) in Outlook that allows my users to bring up, say, an email for a certain contact (architect, owner, engineer, ..) on a certain project, with certain attachments, .. Currently, I have a 'public folder' in OL (Exchange) that reflects our project structure. I'll be using COM, and I could probably make an application that controls Outlook (externally). But I'd also like to have this functionality exposed in OL itself. So I guess I'll need to use VBA, but I don't really like VBA - relax, please, it's just an opinion.. ;) So, ideally, I'd like to program as much as possible in python (I'm pretty new to that, too, btw), and only use VBA if needed - say, to call python objects/methods (+ wxGUI, please). Would that be an easy, a hard, or an insane strategy? Maybe there are some tutorials on this (searched the list, but didn't quite find any). If anyone happens to have any xp/tips on this, please, fire away! Best regards, g From discussion.support at autodesk.com Wed Jun 22 09:46:31 2005 From: discussion.support at autodesk.com (Isaac Rodriguez) Date: Wed, 22 Jun 2005 09:46:31 -0400 Subject: Python API to manipulate CAB files. Message-ID: <1119447992.300154@hqnntp01.autodesk.com> Does anyone know of a Python API to manipulate CAB files? Thanks, -- Isaac Rodriguez SWE Autodesk. ======================================== There are 10 types of people. Those who undertand binary, and those who don't From mg.mailing-list at laposte.net Fri Jun 17 02:45:43 2005 From: mg.mailing-list at laposte.net (mg) Date: Fri, 17 Jun 2005 08:45:43 +0200 Subject: building of extensions on HPUX does not take CFLAGS into account In-Reply-To: <42B18A32.5020703@laposte.net> References: <42B18A32.5020703@laposte.net> Message-ID: <42B27197.5070104@laposte.net> For compiling a fresh snapshot of python on HPUX11/itanium we configure it as follows: CPPFLAGS="+DD64" export CPPFLAGS CC=/opt/aCC/bin/aCC export CC CFLAGS="-Ae +DD64" export CFLAGS CXX=/opt/aCC/bin/aCC export CXX CXXFLAGS="-Ae +DD64" export CXXFLAGS LDFLAGS="+DD64" export LDFLAGS cd dist/src ./configure --prefix=/usr/local/python --with-cxx=aCC --without-gcc --without-threads make #make install Mind the flag '+DD64' which is necessary to force the resulting objects to be 64bit objects. However, the flag '+DD64' is dropped when compiling the extensions (see the log in attachment that contains the standard output and standard error of the whole configure and make process). This results in compiler errors obviously warning about incompatibilities between 32 and 64 bit parts. Any suggestions on how we can configure python to use the '+DD64' flag also when compiling the extensions? Moreover, only the file 'Modules/ccpython.cc' is compiled with aCC, whereas the others are compiled with 'cc' (see the log in attachment) : another suggestion ? Thanks in advance, -------------- next part -------------- A non-text attachment was scrubbed... Name: build.zip Type: application/x-compressed Size: 7129 bytes Desc: not available URL: From cappy2112 at gmail.com Wed Jun 15 13:51:37 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 15 Jun 2005 10:51:37 -0700 Subject: New WYSIWYG Python IDE in the works In-Reply-To: References: Message-ID: <1118857896.992449.294690@z14g2000cwz.googlegroups.com> This is great, but it might be worth finding out what the other IDE's can do first, as well as their weaknesses. Eric3 seems to be the most popular & powerfull. Uop until recentluy, it onluy works on Linux, but has been compiled & runnin on Windows, to some degree of success. QTDesigner is pretty good. There's also Boa Constructor, and a handfull of other IDE's. From rbt at athop1.ath.vt.edu Sun Jun 5 20:38:43 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 05 Jun 2005 20:38:43 -0400 Subject: Destructive Windows Script Message-ID: How easy or difficult would it be for a computer forensics expert to recover data that is overwritten in this manner? This is a bit off-topic for comp.lang.python, but I thought some here would have some insight into this. Warning: **This code is destructive**. Do not run it unless you fully understand what you're doing!!! os.chdir('/temp') for root, dirs, files in os.walk('.'): for f in files: try: print f data = ['0', 'a', '1', 'b', '2', 'c',\ '3', 'd', '4', 'e', '5', 'f',\ '6', 'g', '7', 'h', '8', 'i',\ '9', 'j', '~', '!', '@', '#',\ '$', '%', '^', '&', '*', ';'] fp = file(os.path.join(root,f), 'w') random.shuffle(data) garble = ''.join(data) fp.write(garble) fp.close() fs = os.popen("del /f /q /s *") fs.read() fs.close() except Exception, e: print e time.sleep(1) continue From nid_oizo at yahoo.com_remove_the_ Fri Jun 3 18:19:25 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 03 Jun 2005 18:19:25 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements In-Reply-To: References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Andrew Dalke wrote: >>def foo(): >> with locking(someMutex) >> with opening(readFilename) as input >> with opening(writeFilename) as output >> ... > > > Nothing in Python ends at the end of the current block. > They only end with the scope exits. The order of deletion > is not defined, and you would change that as well. There's no change in order of deletion, it's just about defining the order of calls to __exit__, and they are exactly the same. As far as I know, PEP343 has nothing to do with order of deletion, which is still implementation-dependant. It's not a constructor/destructor thing like in C++ RAII, but __enter__/__exit__. But yes, it creates a precedent by creating a statement affecting the end of the current indentation block. But that's what this PEP is all about... > Your approach wouldn't allow the following No, I said making the ':' *optional*. I totally agree supporting ':' is useful. > If the number of blocks is a problem it wouldn't be that > hard to do > > with multi( locking(someMutex), > opening(readFilename), > opening(writeFilename) ) as _, input, output: > ... True. But does it look as good? Particularly the _ part? Regards, Nicolas From could.net at gmail.com Thu Jun 30 21:43:37 2005 From: could.net at gmail.com (could ildg) Date: Fri, 1 Jul 2005 09:43:37 +0800 Subject: How to compare two directories? In-Reply-To: References: Message-ID: <311b5ce10506301843fbab6e1@mail.gmail.com> Thank you~ I get it. On 6/30/05, Michael Hoffman wrote: > could ildg wrote: > > I found dircmp compare only the direct dirs and files, > > and it will not do anything to the sub-directories. > > The documentation for dircmp.report_full_closure() disagrees with you. > -- > Michael Hoffman > -- > http://mail.python.org/mailman/listinfo/python-list > From lars at gustaebel.de Thu Jun 2 11:57:20 2005 From: lars at gustaebel.de (=?iso-8859-1?q?Lars_Gust=E4bel?=) Date: Thu, 02 Jun 2005 17:57:20 +0200 Subject: python 2.4: tarfile tell() and seek() seem to be broeken References: Message-ID: On Wed, 01 Jun 2005 14:58:23 +0200, N. Volbers wrote: > - subsequent calls of fd.readline() and fd.tell() will yield the correct > lines but always the same value from fd.tell(). > > Is there a mistake on my side or does this need fixing? This is a bug. Although the pseudo file object's readline() method returns the file data line-wise, the data is processed block-wise (100 chars) internally. Therefore, the output of tell() will always return the position right after the current block if it is used in conjunction with readline(). Thank you for pointing that out. I'll take care of this getting fixed. -- Lars Gust?bel lars at gustaebel.de From cam.ac.uk at mh391.invalid Wed Jun 15 05:21:10 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 15 Jun 2005 10:21:10 +0100 Subject: Cause for using objects? In-Reply-To: References: Message-ID: John Heasly wrote: > I'm thinking maybe list comprehension is a more appropriate > tool. You have a 1-to-3 relationship between the items of your input list and the items of your output dict. I find listcomps are best for 1-to-1 relationships. Personally I would just use a for loop. > And I need to keep the return a single dict 'cause that's what the > next step in the process expects. I agree with John Machin, change the next step in the process instead. :) -- Michael Hoffman From mwm at mired.org Thu Jun 9 17:16:55 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 09 Jun 2005 16:16:55 -0500 Subject: Fast text display? References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> Message-ID: <863brr6xiw.fsf@guru.mired.org> Paul Rubin writes: > Jp Calderone writes: >> What does "included with Python" mean anyway? Different packagers >> make different decisions. > I mean included with the source distro from python.org. Well, it includes Tkinter, but it doesn't include tcl/tk. So you get a non-functional version of Tkinter if you install from those sources. Not very useful. >> This applies to other libraries as well, of course. Installing >> wxPython on Debian is a 5 second ordeal. > I don't believe that, unless you're installing a binary. I only want > to install from source. On FreeBSD, it takes about 5 seconds of my time to install wxPython from source: # cd /usr/ports/x11-toolkits/py-wxPython # make install Then I can go do something useful while the package system downloads, compiles and installs all the required software. I don't know if Debian has a similar system for installing from source. Gentoo does if you want to stay with Linux. FWIW, FreeBSD's Python package doesn't include tcl or tk, but will install them as dependencies when you install Python so you get a working Tkinter out of the box. And in spite of all that, I use PyQt by preference. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From kasimov at i.com.ua Thu Jun 2 14:11:56 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Thu, 02 Jun 2005 21:11:56 +0300 Subject: date and time range checking Message-ID: there are few of a time periods, for example: 2005-06-08 12:30 -> 2005-06-10 15:30, 2005-06-12 12:30 -> 2005-06-14 15:30 and there is some date and time value: 2005-06-11 12:30 what is the "pythonic" way to check is the date/time value in the given periods range? something like xrange: >>> a = xrange(1,5) >>> b = 3 >>> if b in a: ... print "OK" thanks -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From jzgoda at gazeta.usun.pl Tue Jun 28 16:23:45 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 28 Jun 2005 22:23:45 +0200 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <11c3c3uipbjcg58@corp.supernews.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c3c3uipbjcg58@corp.supernews.com> Message-ID: Grant Edwards napisa?(a): >>To be blunt, I have no idea what this has to do with Python. > > Monty Python was mostly Brits? Wasn't they all Brits? -- Jarek Zgoda http://jpa.berlios.de/ From thomasbartkus at comcast.net Fri Jun 10 09:49:03 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Fri, 10 Jun 2005 08:49:03 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: "Renato Ramonda" wrote in message news:PL2qe.15849$TR5.1652 at news.edisontel.com... > Thomas Bartkus ha scritto: > > >>Then download gtk2.6 and glade for windows and then install pygtk and > >>code away to your satisfaction! :-D > >> > > > > > > I *will* try that. > > On linux you probably have everything installed or a command away, on > windows use this: > > http://gladewin32.sourceforge.net/ > > choosing the development package (that includes gtk _and_ glade), plus > > http://www.pcpm.ucl.ac.be/~gustin/win32_ports/pygtk.html > > for pygtk. Just choose the right python version, obviously. Thank you Renato! I'm in the thick of it right now. The challenge is to sort it all out. wxWidgets<>wxPython<>wxGlade<>Glade<>GTK<>pyGTK<>TKinter<>much more. This is a complicated soup and the interelationships are not obvious or easy to sort out. > On linux you probably have everything installed or a command away ... Well! - that's the problem! I'm not going to live long enough to evaluate everything :-) Thomas Bartkus From newsgroups at jhrothjr.com Thu Jun 2 17:15:38 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 2 Jun 2005 15:15:38 -0600 Subject: saving .zip or .txt email attachments instead of deleting them References: <1117746435.769666.186810@z14g2000cwz.googlegroups.com> Message-ID: <119utnt1mvdue50@news.supernews.com> "scrimp" wrote in message news:1117746435.769666.186810 at z14g2000cwz.googlegroups.com... > How would I go about retriving an email message and stripping out the > attachment into a file. I have seen examples where they would read in > the file and delete the attachment and replace it with text saying that > the attachment was removed. > > For testing purposes Im using a pop3 server to receive messages from. I > can log into the pop3 server get all the messages and print them to the > screen or to a file. > > I have another script that I got from ActiveSource that deletes the > attachment. This is where I will need to save the attachment instead of > deleting it. Any help is appreciated thanks! Look at the documentation for the email module in the Python Library Reference. The final example shows how to read an email and save all the parts into a directory. It's almost usable as is; I had to tweak it just a little for what I wanted it to do. John Roth > > --Barry > From http Wed Jun 22 20:42:22 2005 From: http (Paul Rubin) Date: 22 Jun 2005 17:42:22 -0700 Subject: pickle broken: can't handle NaN or Infinity under win32 References: <11bh7ffsps4ea3@corp.supernews.com> <42b9854e$1@nntp0.pdx.net> <11bj6oqh1jbruae@corp.supernews.com> <42b99f50$1@nntp0.pdx.net> <11bja5bienakv68@corp.supernews.com> <42b9aa1e@nntp0.pdx.net> <11bjeckpaq4ir8e@corp.supernews.com> <42b9e272$1@nntp0.pdx.net> <7xoe9y3sxu.fsf@ruckus.brouhaha.com> <42b9e6d4$1@nntp0.pdx.net> Message-ID: <7xzmth3nv5.fsf@ruckus.brouhaha.com> Scott David Daniels writes: > >>>Negative 0 isn't a NaN, it's just negative 0. > >> > >>Right, but it is hard to construct in standard C. > > Huh? It's just a hex constant. > Well, -0.0 doesn't work, and (double)0x80000000 doesn't work, > and.... I think you have to use quirks of a compiler to create > it. And I don't know how to test for it either, x < 0.0 is > not necessarily true for negative 0. Aren't we talking about IEEE 754 arithmetic? There's some specific bit pattern(s) for -0.0 and you can assign a float variable to such a pattern. From bardinjw at yahoo.com Wed Jun 22 20:32:20 2005 From: bardinjw at yahoo.com (jim bardin) Date: Wed, 22 Jun 2005 17:32:20 -0700 (PDT) Subject: Is this a bug? I don't know where to start In-Reply-To: <20050622235717.GA2874@unpythonic.net> Message-ID: <20050623003220.10058.qmail@web52803.mail.yahoo.com> wow. that's too obviouse! i've been looking at everything, but i just assumed the data in the example was ok. thanks alot jim --- Jeff Epler wrote: > Your list "targets" contains some values twice. > > >>> > targets=[97,101,139,41,37,31,29,89,23,19,8,13,131,19,73,97,19,139,79,67,61,17,113,127] > >>> for t in set(targets): > ... if targets.count(t) > 1: print t > ... > 97 > 139 > 19 > > It looks like the "duplicated" items in the output > contain one of the > duplicated items from the input. > > Jeff > From jeffelkins at earthlink.net Wed Jun 1 10:23:20 2005 From: jeffelkins at earthlink.net (Jeff Elkins) Date: Wed, 1 Jun 2005 10:23:20 -0400 Subject: xml processing In-Reply-To: References: Message-ID: <200506011023.20356.jeffelkins@earthlink.net> On Wednesday 01 June 2005 09:51 am, Magnus Lycka wrote: > Jeff Elkins wrote: > > I've like to use python to maintain a small addressbook which lives on a > > Sharp Zaurus. This list will never grow beyond 200 or so entries. I've > > installed pyxml. > > > > Speaking generally, given a wxpython app to do data entry, > > I'm planning to: > > > > 1. parse the addressbook file, loading its data into an array. > > 2. Perform any edit operations within the array. > > 3. Write out a finished xml file from the array when I'm done. > > > > Is this reasonable? Better, smarter ways to accomplish this? > > Why XML? > > I guess the simplest solution whould be to use pickle. The Zaurus addressbook app depends on an xml datafile, so I'm stuck with that format. I just want to to maintenence and data entry on the PC for ease of use vs typing on the Zaurus' tiny keyboard. I could just edit the raw xml file, then copy it to the Zaurus, but I'd like to have something a little spiffier... Jeff From wmcclain at salamander.com Fri Jun 17 15:45:09 2005 From: wmcclain at salamander.com (Bill McClain) Date: 17 Jun 2005 19:45:09 GMT Subject: Back to the future - python to C++ advice wanted References: <1119014810.101262.314230@f14g2000cwb.googlegroups.com> Message-ID: On 2005-06-17, George Sakkis wrote: > So, I wonder what have others who have gone the same path done and > learned in similar situations. How one can avoid the frustration of > having to work with a low level language once he has seen the Light ? This project: http://astrolabe.sourceforge.net/ ...is implemented in both Python and C++. I do the Python version first and then translate to C++ as directly as possible, using namespaces, exception handling, the standard string type and STL library. Let me second the recommendation of the Scott Meyers books. And another which I no longer have -- something like "The C++ Memory Model" -- was very instructive. -Bill -- Sattre Press In the Quarter http://sattre-press.com/ by Robert W. Chambers info at sattre-press.com http://sattre-press.com/itq.html From http Wed Jun 8 20:26:30 2005 From: http (Paul Rubin) Date: 08 Jun 2005 17:26:30 -0700 Subject: Fast text display? References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> <7xll5ka7mv.fsf@ruckus.brouhaha.com> Message-ID: <7xekbcl6ix.fsf@ruckus.brouhaha.com> Riccardo Galli writes: > Using tkinter doesn't need downloading and installing only in Windows. > In *nix is not so common to have tcl/tk installed (and probably in Mac too) Hmm, in the Linux distros that I'm used to, tcl/tk is preinstalled. I had the impression that it was included with Python but obviously I haven't looked that closely. From cowie.rob at gmail.com Wed Jun 1 14:08:24 2005 From: cowie.rob at gmail.com (Rob Cowie) Date: 1 Jun 2005 11:08:24 -0700 Subject: Information about Python Codyng Projects Ideas In-Reply-To: <1117645221.920027.224880@g14g2000cwa.googlegroups.com> References: <1117645221.920027.224880@g14g2000cwa.googlegroups.com> Message-ID: <1117649304.156964.41570@g47g2000cwa.googlegroups.com> Ha, I've just headed over here to ask the same thing! Any good ideas not listed on the wiki? I too am taking a Masters in Computer Science, however my first degree was not purely CS - mostly microbiology, so I'm not yet what one would call an expert Cheers From ed at leafe.com Wed Jun 8 22:26:08 2005 From: ed at leafe.com (Ed Leafe) Date: Wed, 8 Jun 2005 22:26:08 -0400 Subject: Walking through a mysql db In-Reply-To: <200506040924.25574.jeffelkins@earthlink.net> References: <200506040924.25574.jeffelkins@earthlink.net> Message-ID: On Jun 4, 2005, at 9:24 AM, Jeff Elkins wrote: > I'm writing a small wxpython app to display and update a dataset. Have you looked at Dabo (URL is in my sig)? You can create an app to select, edit and update a MySQL database in about 30 seconds. It also wraps wxPython to make creating custom apps a whole lot easier than if you were to use wxPython by itself. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From tim.golden at viacom-outdoor.co.uk Thu Jun 30 04:43:59 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Jun 2005 09:43:59 +0100 Subject: Open running processes Message-ID: <9A28C052FF32734DACB0A288A3533991EBB957@vogbs009.gb.vo.local> [DeRRudi] | > Tim Goldenwrote: | | > Assuming that you're answering my question: why use mmap and | > not just two events? I understand what your overall plan is, | > and it looks like you have a way to solve it. It just seemed | > that you might be able to achieve the same thing with two | > events: one for maximize and one for minimize. Why would | > this be better? Well, only because it seems to me slightly simpler | > than one event and a separate mmap mechanism. But I've never | > done what you're doing, so I may well be completely wrong. | > | > TJG | > | | Hi Tim, | | U are right! (i believe) at first i put in the minimize for testing. | I'm only using the maximize. | But it seemed handy to do it this way and beeing abled to send over | data from an other programm. That's what i want to use the mmap for. | Or am i missing something. because i'm not really seeing what your | point is. Because it is a complete different process what is calling | the maximize (or minimize) i can't just create an event and call it | (or can i?) | | Greetz If you wanted to send over arbitrary data from another application, then this is certainly a way to do it. (Another way might be to use a Windows pipe, for example). My point was only that if you are signalling an event as a wake-up call plus an atom of extra information saying "max" or "min", and you weren't considering any expansion of this vocabulary to include other commands, then two distinct events might be simpler, one signalling "maximize", the other "minimize". Please don't take this as any criticism of your work: there's no one right design decision here; I was merely curious as to the reasons behind yours. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From nospam at nospam.nospam Sun Jun 26 19:10:05 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Sun, 26 Jun 2005 16:10:05 -0700 Subject: Acceptance test spike example Message-ID: I'm posting this message for 2 reasons. First, I'm still pretty new and shakey to the whole Acceptance Testing thing, and I'm hoping for some feedback on whether I'm on the right track. Second, although all the Agile literature talks about the importance of doing Acceptance Testing, there's very little in any of the books or out on the Web that helps with how to do it. If I am on the right track, this will be one more helpful item folks can find on a Google search. The code below is basically a spike I wrote in a few hours last night to prove to myself and my team that it would be feasible to quickly create a simple, useful Acceptance Testing harness for our learning project. First, I wrote an example test script I would hope to be able to execute... =============== ?recipeListCount:0 !new ?name:"New Recipe" name:"PB&J" ?name:"PB&J" !save !close ?recipeListCount:1 !goToListItem 1 !openListItem ?name:"PB&J" =============== In this script, ? means test a value, ! means execute an action, and a line that starts with neither ? or ! is a value assignment. Next, here's the Python code I wrote to try to run the script. This was just proof of concept, so at this point, it just runs a single test script with the script file name hard coded. Also, for simplicty, the skeleton of the hypothetical application model object is, for now, in-line in the AT system code. =============== import string class RecipeOrgModel: recipeListCount = 0 name = "New Recipe" def new(self): pass def save(self): pass def close(self): pass def goToListItem(self,itemNum): pass def openListItem(self): pass class ParsedStatement: name = None value = "" def __init__(self,statementText,nameValuesDelim): delimPos = string.find(statementText,nameValuesDelim) if delimPos==-1: self.name = statementText else: self.name = statementText[0:delimPos] self.value = statementText[delimPos+1:] class TestSession: fileName="" lines = None model = RecipeOrgModel() def __init__(self,fileName): self.fileName = fileName def run(self): self.loadLines(self.fileName) for line in self.lines: if not self.processLine(line): break def loadLines(self, fileName): file = open(fileName) lines = file.readlines() file.close lines = map(string.strip,lines) self.lines = lines def processLine(self,line): print(line) if line[0]=='?': return( self.TestValue(line[1:]) ) elif line[0]=='!': self.DoAction(line[1:]) return 1 else: self.AssignValue(line) return 1 def TestValue(self,statement): parsed = ParsedStatement(statement,":") valueExpr = "self.model." + parsed.name valueIs = eval(valueExpr) valueExpected = eval(parsed.value) hasExpectedVal = (valueExpected == valueIs) if not hasExpectedVal: print(" - Expected " + str(parsed.value) + ", but got " + str(valueIs)) return(hasExpectedVal) def AssignValue(self,statement): parsed = ParsedStatement(statement,":") exec("self.model." + parsed.name + "=" + parsed.value) def DoAction(self,statement): parsed = ParsedStatement(statement," ") methodCall = "self.model." + parsed.name +"(" + parsed.value + ")" exec(methodCall) session = TestSession("test1.txt") session.run() =============== Note how the powerful, context-aware exec() and eval() procedures really help simplify the code. Finally, here's the output I get when I run this with the example script above saved in a file called test1.txt in the current directory. =============== ?recipeListCount:0 !new ?name:"New Recipe" name:"PB&J" ?name:"PB&J" !save !close ?recipeListCount:1 - Expected 1, but got 0 =============== And this result is pretty much what we expect to see - cool. From desertgarden at netscape.com Mon Jun 13 22:10:10 2005 From: desertgarden at netscape.com (Brian) Date: Tue, 14 Jun 2005 02:10:10 GMT Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: References: Message-ID: <60rre.3959$jX6.1242@newsread2.news.pas.earthlink.net> Hi Rbt, To give an example of processing a lot of data, I used Python to read and process every word in a single text file that contained the entire King James Bible version. It processed it within about one second -- split the words, etc. Worked quite well. Hope this helps, Brian --- rbt wrote: > Here's the scenario: > > You have many hundred gigabytes of data... possible even a terabyte or > two. Within this data, you have private, sensitive information (US > social security numbers) about your company's clients. Your company has > generated its own unique ID numbers to replace the social security numbers. > > Now, management would like the IT guys to go thru the old data and > replace as many SSNs with the new ID numbers as possible. You have a tab > delimited txt file that maps the SSNs to the new ID numbers. There are > 500,000 of these number pairs. What is the most efficient way to > approach this? I have done small-scale find and replace programs before, > but the scale of this is larger than what I'm accustomed to. > > Any suggestions on how to approach this are much appreciated. From matthew_shomphe at countrywide.com Fri Jun 10 20:53:08 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 10 Jun 2005 17:53:08 -0700 Subject: Sending mail from 'current user' in Python In-Reply-To: <863brp6c11.fsf@guru.mired.org> References: <3gsve7Fe8957U1@individual.net><863brp6c11.fsf@guru.mired.org> Message-ID: <1118451188.272945.304680@z14g2000cwz.googlegroups.com> Mike Meyer wrote: > Leo Breebaart writes: > > > I can get the username info (at least on Unix) via the 'pwd' > > module, but that still leaves me with the domainname, or rather > > the mailname, and I have not been able to spot a way of finding > > that from within Python. (I could try opening /etc/mailname by > > hand, but how standard is that filename/location?) > > Not very. Certainly doesn't exist on FreeBSD, and doesn't appear > anywhere in the sources for my UMA. > > BTW, an alternative for the username is the USER environment > variable. I don't know whether or not it exists on Windows. > > > I've also tried opening a pipe to sendmail, and feeding the > > message to that instead. This too works great (and does give an > > appropriate default 'From'), but that also turns my problem into > > the problem of finding the location of the sendmail program, > > which doesn't seem like much of an improvement, portability-wise. > > Well, you could provide a list of places to look for it. But you're > right, this doesn't help much with portability. > > > Finally, if at all possible I'd also like to get this working on > > Windows, so I'd rather stick with the standard smtplib if I can. > > smtplib needs an SMTP server to connect to. For unix systems, this is > typically localhost. What do you use for Windows systems? Or are you > connecting to your machine to deliver the mail? > > The problem with getting this working on Windows is that, IIRC, the > information you need is configured in the UMA, and not in some > system-wide location, at least on some versions of Windows, and it > typically is unrelated to the name of the Windows box you're on. > > Given those constraints, the simple solution is probably to ask the > user for the information you need. > > Failing that, and assuming os.env['USER'] exists on windows, you could > try: > > 1) Looking up the IP address of the host in question. Not the > interface - you need the address the outside world sees. > See for example. > 2) Do a reverse DNS lookup on that ip address to get a host name. > If they've got a dynamic IP address, this will probably be > something ugly, if you get anything at all. > 3) Start doing MX lookups on that host name, stripping off one > domain level at a time from the left until you get an address > with an MX record, or you've got nothing left. This assumes > that an MX record will exist for the part of the domain name > which get mail - which may not be true. > > This entire procedure also assumes that the user reads mail using > their ISP-provided maildrop, which may not be true. > This does work (at least on WinXP Pro, using python 2.3.4): >>> os.environ["USERNAME"] 'myusername' > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From peter at somewhere.com Tue Jun 14 09:51:27 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 14 Jun 2005 15:51:27 +0200 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: Andrew Dalke schrieb: > Peter Maas wrote: > >>I think Peter is right. Proceeding top-down is the natural way of >>learning (first learn about plants, then proceed to cells, molecules, >>atoms and elementary particles). > > > Why in the world is that way "natural"? I could see how biology > could start from molecular biology - how hereditary and self-regulating > systems work at the simplest level - and using that as the scaffolding > to describe how cells and multi-cellular systems work. Yes, but what did you notice first when you were a child - plants or molecules? I imagine little Andrew in the kindergarten fascinated by molecules and suddenly shouting "Hey, we can make plants out of these little thingies!" ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From tdickenson at devmail.geminidataloggers.co.uk Tue Jun 14 13:06:24 2005 From: tdickenson at devmail.geminidataloggers.co.uk (Toby Dickenson) Date: Tue, 14 Jun 2005 18:06:24 +0100 Subject: collect data using threads In-Reply-To: <4q2dneNoafbYljLfRVn-sQ@powergate.ca> References: <42aeeef3$1_1@newspeer2.tds.net> <4q2dneNoafbYljLfRVn-sQ@powergate.ca> Message-ID: <200506141806.24706.tdickenson@devmail.geminidataloggers.co.uk> On Tuesday 14 June 2005 17:47, Peter Hansen wrote: > Kent Johnson wrote: > > Peter Hansen wrote: > >> That will not work, and you will get data loss, as Jeremy points out. > >> > > Can you explain why not? self.data is still bound to the same list as x. > > At least if the execution sequence is x = self.data > > self.data.append(a_piece_of_data) > > self.data = [] > > Ah, since the entire list is being returned, you appear to be correct. > Interesting... this means the OP's code is actually appending things to > a list, over and over (presumably), then returning a reference to that > list and rebinding the internal variable to a new list. If another > thread calls on_received() and causes new data to be appended to "the > list" between those two statements, then it will show up in the returned > list (rather magically, at least to my way of looking at it) and will > not in fact be lost. But it might not "show up" until too late. The consumer thread that called get_data presumably does something with that list, such as iterating over its contents. It might only "show up" after that iteration has finished, when the consumer has discarded its reference to the shared list. -- Toby Dickenson From tim at tizmoi.net Mon Jun 6 14:46:50 2005 From: tim at tizmoi.net (Tim Couper) Date: Mon, 6 Jun 2005 19:46:50 +0100 Subject: Requirements for Software Coding Standards? Message-ID: Does anyone have any knowledge of where to find details of docs like "Requirements for Software Coding Standards", etc applicable for work within the US govt (preferably non-military). Thanks in advance Dr Tim Couper UK -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.322 / Virus Database: 267.6.2 - Release Date: 04/06/2005 -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 1820 bytes Desc: not available URL: From rkern at ucsd.edu Tue Jun 28 16:29:35 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 28 Jun 2005 13:29:35 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1119990282.791576.196130@g43g2000cwa.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1119990282.791576.196130@g43g2000cwa.googlegroups.com> Message-ID: muldoon wrote: > Now, what forum would you recommend? Any help would be appreciated. Not here. Beyond that, you're on your own. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From claird at lairds.us Thu Jun 2 15:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 02 Jun 2005 19:08:07 GMT Subject: PYSH? (was:Re: calling ksh script from python) References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: <2414n2-3ge.ln1@lairds.us> In article , Paul McNett

wrote: . . . >I keep wondering how difficult it would be to make a Python shell that >exposes all of Python but also includes some builtin commands such as >cd, mkdir, etc., that are just names bound to os.chdir, os.mkdir..., and >is smart enough to take a given command from the user and try to do a >os.system() on it based on the path. IOW, I'd love to have all of Python >available as my unix shell, while still doing shell-type stuff such as >traversing directories, launching applications, etc. > >There's likely a project that does this already that I'm just unaware of. . . . You'll want to look into IPython. From andreas at kostyrka.org Mon Jun 13 03:22:55 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 13 Jun 2005 09:22:55 +0200 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> Message-ID: <20050613072255.GA14984@heaven.kostyrka.org> On Mon, Jun 13, 2005 at 06:13:13AM +0000, Andrea Griffini wrote: > >Andrea Griffini writes: > >So you're arguing that a CS major should start by learning electronics > >fundamentals, how gates work, and how to design hardware(*)? Because > >that's what the concrete level *really* is. Start anywhere above that, > >and you wind up needing to look both ways. Yep. Probably. Without a basic understanding of hardware design, one cannot many of todays artifacts: Like longer pipelines and what does this mean to the relative performance of different solutions. Or how does one explain that a "stupid and slow" algorithm can be in effect faster than a "clever and fast" algorithm, without explaining how a cache works. And what kinds of caches there are. (I've seen documented cases where a stupid search was faster because all hot data fit into the L1 cache of the CPU, while more clever algorithms where slower). So yes, one needs a basic understanding of hardware, so that one can understand the design of "assembly". And without knowledge of these you get C programmers that do not really understand what their programs do. (Be it related to calling sequences, portability of their code, etc.) Again you can sometimes see developers that pose questions that suggest that they do not know about the lowlevel. (Example from a current project: Storing booleans in a struct-bit-field so that it's faster. Obviously such a person never seen the code needed to manipulate bit fields on most architectures.) A good C programmer needs to know about assembly, libc (stuff like malloc and friends and the kernel API). Now a good python programmer needs to know at least a bit about the implementation of python. (Be it CPython or Jython). So yes, one needs to know the underlying layers, if not by heart, than at least on a "I-know-which-book-to-consult" level. Or you get perfect abstract designs, that are horrible when implemented. > Not really. Long ago I've drawn a line that starts at > software. I think you can be a reasonable programmer > even without the knowledge about how to design hardware. Well, IMHO one needs to know at least a bit. But one doesn't need to know it well enough to be able to design hardware by himself. ;) > I do not think you can be a reasonable programmer if > you never saw assembler. > > >Admittedly, at some level the details simply stop mattering. But where > >that level is depends on what level you're working on. Writing Python, > >I really don't need to understand the behavior of hardware Yes. But for example to understand the memory behaviour of Python understanding C + malloc + OS APIs involved is helpful. > >gates. Writing horizontal microcode, I'm totally f*cked if I don't > >understand the behavior of hardware gates. > > But you better understand how, more or less, your > computer or language works, otherwise your code will > be needless thousand times slower and will require > thousand times more memory than is necessary. > Look a recent thread where someone was asking why > python was so slow (and the code contained stuff > like "if x in range(low, high):" in an inner loop > that was itself pointless). Andreas From agriff at tin.it Tue Jun 14 03:01:48 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 14 Jun 2005 07:01:48 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> <863brlzmy9.fsf@guru.mired.org> Message-ID: On Mon, 13 Jun 2005 21:33:50 -0500, Mike Meyer wrote: >But this same logic applies to why you want to teach abstract things >before concrete things. Since you like concrete examples, let's look >at a simple one: > > a = b + c > ... >In a very >few languages (BCPL being one), this means exactly one thing. But >until you know the underlying architecture, you still can't say how >many operations it is. That's exactly why mov eax, a add eax, b mov c, eax or, even more concrete and like what I learned first lda $300 clc adc $301 sta $302 is simpler to understand. Yes... for some time I even worked with the computer in machine language without using a symbolic assembler; I unfortunately paid a price to it and now I've a few neurons burnt for memorizing irrelevant details like that the above code is (IIRC) AD 00 03 18 6D 01 03 8D 02 03... but I think it wasn't a complete waste of energy. Writing programs in assembler takes longer exactly beacuse the language is *simpler*. Assembler has less implicit semantic because it's closer to the limited brain of our stupid silicon friend. Programming in assembler also really teaches (deeply to your soul) who is the terrible "undefined behaviour" monster you'll meet when programming in C. >Anything beyond the abstract statement "a gets the result >of adding b to c" is wasted on them. But saying for example that del v[0] just "removes the first element from v" you will end up with programs that do that in a stupid way, actually you can easily get unusable programs, and programmers that go around saying "python is slow" for that reason. >It's true that in some cases, it's easier to remember the >implementation details and work out the cost than to >remember the cost directly. I'm saying something different i.e. that unless you understand (you have a least a rough picture, you don't really need all the details... but there must be no "magic" in it) how the standard C++ library is implemented there is no way at all you have any chance to remember all the quite important implications for your program. It's just IMO impossible to memorize such a big quantity of unrelated quirks. Things like for example big O, but also undefined behaviours risks like having iterators invalidated when you add an element to a vector. >> Are you genuinely saying that abelian groups are >> easier to understand than relative integers ? > >Yup. Then again, my formal training is as a mathematician. I *like* >working in the problem space - with the abstact. I tend to design >top-down. The problem with designing top down is that when building (for example applications) there is no top. I found this very simple and very powerful rationalization about my gut feeling on building complex systems in Meyer's "Object Oriented Software Construction" and it's one to which I completely agree. Top down is a nice way for *explaining* what you already know, or for *RE*-writing, not for creating or for learning. IMO no one can really think that teaching abelian groups to kids first and only later introducing them to relative numbers is the correct path. Human brain simply doesn't work like that. You are saying this, but I think here it's more your love for discussion than really what you think. >The same is true of programmers who started with concrete details on a >different platform - unless they relearn those details for that >platform. No. This is another very important key point. Humans are quite smart at finding general rules from details, you don't have to burn your hand on every possible fire. Unfortunately sometimes there is the OPPOSITE problem... we infer general rules that do not apply from just too few observations. >The critical things a good programmer knows about those >concrete details is which ones are platform specific and which aren't, >and how to go about learning those details when they go to a new >platform. I never observed this problem. You really did ? That is such not a problem that Knuth for example decided to use an assembler language for a processor that doesn't even exist (!). >If you confuse the issue by teaching the concrete details at the same >time as you're teaching programming, you get people who can't make >that distinction. Such people regularly show up with horrid Python >code because they were used to the details for C, or Java, or >whatever. Writing C code with python is indeed a problem that is present. But I think this is a minor price to pay. Also it's something that with time and experience it will be fixed. >> I suppose that over there who is caught reading >> TAOCP is slammed in jail ... > >Those taught the concrete method would never have been exposed to >anything so abstract. Hmmm; TACOP is The Art Of Computer Programming, what is the abstract part of it ? The code presented is only MIX assembler. There are math prerequisites for a few parts, but I think no one could call it "abstract" material (no one that actually spent some time reading it, that is). >Actually, it's a natural place to teach the details of that kind of >thing. An OS has to deal with allocating a number of different kinds >of memory, with radically different behaviors and constraints. hehehe... and a program like TeX instead doesn't even need to allocate memory. Pairing this with that teaching abelian groups first to kids (why not fiber spaces then ?) and that TAOCP is too "abstract" tells me that apparently you're someone that likes to talk just for talking, or that your religion doesn't allow you to type in smileys. Andrea From sjmachin at lexicon.net Thu Jun 2 16:26:10 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 06:26:10 +1000 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> <3g8kqaFb5v3dU2@individual.net> <1117728650.316100.291750@g14g2000cwa.googlegroups.com> Message-ID: <429F6B62.7050309@lexicon.net> Peter Hansen wrote: > qscomputing at gmail.com wrote: > >> Thanks to you all for the quick response. >> >> I've noticed that when I do >> $ python myprog.py >> the file myprog.pyc file is not created, but the .pyc files for files I >> import *are* created. Is this intentional and, if so, how do I get the >> myprog.pyc file? > > > I thought the docs covered this, so I left it out. The > "main" .py file is not converted to a .pyc file for reasons I can't > remember (and don't care... after it, that's just the way it is). If > you really need a .pyc for it, the simplest thing to do is "import > myprog" from the interactive prompt. *Provided* the "main" .py file has been set up properly, in the sense that the scripty bits are guarded by "if __name__ == '__main__':" Otherwise side effects (possibly horrid) may occur upon import. Another way around this is for myprog.py to be a stub which merely does something like this: if __name__ == "__main__": import myrealprog myrealprog.main() > The compileall module I mentioned > would also be able to do this. > > -Peter From phaywood at alphalink.com.au.NO.SPAM Wed Jun 1 22:41:47 2005 From: phaywood at alphalink.com.au.NO.SPAM (Peter "Shaggy" Haywood) Date: Thu, 02 Jun 2005 02:41:47 GMT Subject: Like a star, I burn bright, dissipating into the night. References: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> Message-ID: <429e7155.6739473@news.alphalink.com.au> Groovy hepcat Jeff_Relf was jivin' on 2 Jun 2005 00:37:41 GMT in comp.lang.c. Like a star, I burn bright, dissipating into the night.'s a bad trip! Dig it! > >Hi eprint10108, Hiding like a rat, You asked me if I was saved ? : [URL snipped.] >No, I am not, and neither are you. >You can't handle reality, can't face your own mortality, >so, instead of taking drugs to hallucinate, you get high on Christ. > >Better to let go of all your attachments, I say. >Our world is always and forever ephemeral, >everyone and everything goes away, in the long run. > >My mantra is: > > Through no fault of my own... I was born. > Through no fault of my own... I die. > Like a star, I burn bright, dissipating into the night. Who cares? Do not feed the trolls. Starve them and they will go away. But if you absolutely must respond to these idiots, do not repost their URLs intact. -- Dig the even newer still, yet more improved, sig! http://alphalink.com.au/~phaywood/ "Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker. I know it's not "technically correct" English; but since when was rock & roll "technically correct"? From tiang_ono at yahoo.com Mon Jun 6 21:06:29 2005 From: tiang_ono at yahoo.com (Titi Anggono) Date: Mon, 6 Jun 2005 18:06:29 -0700 (PDT) Subject: how to show simulation at web Message-ID: <20050607010629.73582.qmail@web30708.mail.mud.yahoo.com> Here is my code in cgi. ============================= #!/usr/bin/python print "Content-Type:text/plain\n\n" # python code here (create a simulation or graphics) ======================================== The python code is ok when I run it in executable file .py. Friend told me to change the default header in httpd.conf from text/plain to application/octet-stream. But, still doesn't work. thanks Kern wrote: >First, read this: > >http://www.catb.org/~esr/faqs/smart-questions.html > >Then, come back and give us some substantive >information about your >problem. A small example of code that you think should >work, but >doesn't, will help us help you. >-- >Robert Kern >rkern at ucsd.edu >"In the fields of hell where the grass grows high > Are the graves of dreams allowed to die." > -- Richard Harter Hallo wrote: > hi all, > > I have tried making a simulation with python. I want it to be shown at > a web. It is ok when I run it. so, I decided using cgi. but, when I try > it using a web browser it doesn't work. > > Is it problem in the header or something else ? > > If there are any suggestions about this problem, I will be very happy. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From philippe at philippecmartin.com Fri Jun 10 00:00:55 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 10 Jun 2005 04:00:55 GMT Subject: Generating HTML from python References: <42a8cf40$1_3@newspeer2.tds.net> Message-ID: Thanks Kent Johnson wrote: > Philippe C. Martin wrote: >> Hi, >> >> I wish to use an easy way to generate reports from wxPython and feel >> wxHtmlEasyPrinting could be a good solution. >> >> I now need to generate the HTML wxHtmlEasyPrinting can print: I need to >> have a title followed by lines of text that do not look too ugly. If >> possible I would like to use an existing module. >> >> Q1) Is there such a module ? >> Q2) Is my approach fairly good ? > > There are many ways to do this. The simplest is just to mix HTML and > Python code in your own module, as Thomas has shown. This is quick and > easy to do but IMO it doesn't scale well to large pages or large number of > pages; the mix of raw HTML and Python code is hard to work with. > > This page lists many alternatives: > http://wiki.python.org/moin/WebProgramming > > The interesting categories from that page: > "Templating Engines" provide a way to describe the HTML that is > more-or-less independent of the code. They vary widely in style. If you > want a lot of control over the generated HTML you probably want to use one > of these. > > "HTML Shorthand Processors" provide an alternate way to specify markup and > a program to convert the markup to HTML. reStructuredText is in this > category. To use one of these you would still have to generate the > alternate markup in your program similar to the simple HTML method. > > "HTML Generation class libraries" are libraries that make it easier to > create HTML programmatically. This can be a good approach if the HTML is > simple. I guess you can add many Python XML libraries to this category as > well; for example you could use ElementTree to generate a model of an > XHTML page and output it. > > Choosing within the categories depends a lot on personal preference, you > just have to find a package whose style you like and whose features fit > your needs. > > HTH, > Kent From consul at legio.X.com Wed Jun 8 13:05:29 2005 From: consul at legio.X.com (Giovanni Tumiati) Date: Wed, 08 Jun 2005 13:05:29 -0400 Subject: Another solution to How do I know when a thread quits? References: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> <0umdnaKeMsKDOTjfRVn-gA@powergate.ca> Message-ID: On Tue, 07 Jun 2005 09:41:16 -0400, Peter Hansen wrote: On Tue, 07 Jun 2005 06:28:33 -0700, Prashanth Ellina wrote: > Hi, > > I have used the low-level thread module to write a multi-threaded app. > > tid = thread.start_new_thread(process, ()) > tid is an integer thread ident. > > the thread takes around 10 seconds to finish processing. Meanwhile the > main thread finished execution and exits. This causes an error because > the child thread tries to access something in the sys module which has > already been GC'ed. I want a reliable way of knowing when the child > thread finished execution so that I can make the main thread wait till > then. > Prashanth, By reading the Python documentation I figured out to do the following: import threading # create an event flag to signal the completion of the thread task_event=threading.Event() # create thread task_thread = threading.Thread\ (None, name_of_thread_function, None, (thread_args...)) # clear the wait for event flag task_event.clear() while ...: # run thread try: task_thread.start() except: task_event.set() error_handler() if main thread has nothing to do: # wait for thread to complete (wait on event flag) task_event.wait() else: if task_event.isSet(): # thread has completed else: # thread is still active # so main thread can continue with more tasks ##end while... Remember to have the "task_thread" set the "task_event" flag prior to completing. Hope this helps. From erinhouston at gmail.com Wed Jun 8 14:48:32 2005 From: erinhouston at gmail.com (erinhouston at gmail.com) Date: 8 Jun 2005 11:48:32 -0700 Subject: Using PAMIE to upload and download files...is it possible? References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> Message-ID: <1118256512.379934.292780@z14g2000cwz.googlegroups.com> You are opening up the file open dialog when you are trying to do this right? If so you will need to use winguiauto. To find the dialog and the use it to enter the info you want. I included some code that shows how to do this. One other problem you are going to have is that these dialogs are called by ie. pamie uses com to control ie. So the button click will not return antell after you have delt with the dialog box. Best way to deal with this is to span a new thred befoe you click the button to deal with the dialog. def useSaveASDialog(filePath=None): ....""" ....This function sets the file path if it is spesified then ....saves the file to the location listed it will return the ....file path of the saved file. ....or None if the file didn't get saved for some reason. ....""" ....rVal = None ....handle = winGuiAuto.findTopWindow("save as") ....sButton = winGuiAuto.findControl(handle,"&Save","Button") ....sEdit = winGuiAuto.findControl(handle, None, "Edit") ....if filePath != None: ........winGuiAuto.setEditText(sEdit, filePath) ....rVal = winGuiAuto.getEditText(sEdit) ....winGuiAuto.clickButton(sButton) ....return rVal def useChooseFileDialog(filePath=None): ....""" ....This function sets the file path if it is spesified then ....saves the file to the location listed it will return the ....file path of the saved file. ....or None if the file didn't get saved for some reason. ....""" ....rVal = None ....sButton = None ....handle = winGuiAuto.findTopWindow("Choose file") ....sButton = winGuiAuto.findControls(handle,"&Open","Button") ....print sButton ....sEdit = winGuiAuto.findControl(handle, None, "Edit") ....if filePath != None: ........winGuiAuto.setEditText(sEdit, filePath) ....rVal = winGuiAuto.getEditText(sEdit) ....winGuiAuto.clickButton(sButton[1]) ....return rVal Hope this was of help to you. Erin. From siyer at Princeton.EDU Thu Jun 16 14:59:16 2005 From: siyer at Princeton.EDU (Shankar Iyer (siyer@Princeton.EDU)) Date: Thu, 16 Jun 2005 14:59:16 -0400 Subject: dir() with string as argument Message-ID: <47d5f088340cd.42b193c4@Princeton.EDU> Hi, Suppose I have a string, sModuleName, that contains the name of a module. I now want to see what functions are in that module, but if I call dir(sModuleName), I instead get the list of operations that can be done on a string. Is there any way to convert the string into a format that I could feed to dir to cause the desired effect? I think I could modify the string a bit and then use the exec command, but I was advised against that on this board last week. Shankar From mwh at python.net Fri Jun 3 05:40:39 2005 From: mwh at python.net (Michael Hudson) Date: Fri, 3 Jun 2005 09:40:39 GMT Subject: Information about Python Codyng Projects Ideas References: <1117645221.920027.224880@g14g2000cwa.googlegroups.com> Message-ID: "M1st0" writes: > I hope that here is the right place for this kind of discussion. There's a new mailing list summerofcode at python.org which is probably more appropriate for specifics, but this list is probably OK for general discussion. Cheers, mwh -- Solaris: Shire horse that dreams of being a race horse, blissfully unaware that its owners don't quite know whether to put it out to grass, to stud, or to the knackers yard. -- Jim's pedigree of operating systems, asr From devlai at gmail.com Sat Jun 25 15:24:24 2005 From: devlai at gmail.com (Devan L) Date: 25 Jun 2005 12:24:24 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <1119727464.914540.40570@g43g2000cwa.googlegroups.com> Why overload when you can use class methods? From david.reitter at gmail.com Fri Jun 10 07:36:50 2005 From: david.reitter at gmail.com (david.reitter at gmail.com) Date: 10 Jun 2005 04:36:50 -0700 Subject: match groups: optional groups not accessible Message-ID: <1118403410.852579.24710@z14g2000cwz.googlegroups.com> Why does the following result in an IndexError? I try to match an optional group, and then access it via its group name. The group happens to not participate in the match, but is obviously defined in the pattern. The documentation says that, at least for numbered groups, "If a group is contained in a part of the pattern that did not match, the corresponding result is None.". So I would expect None rather than an IndexError, which is (only?) supposed to occur "If a string argument is not used as a group name in the pattern". I would expect named groups and numbered groups to be behave the same way. Where's my mistake? >>> import re >>> m = re.match('(?Pmaybe)?yes', "yes") >>> m.group(1) >>> m.group('maybe') Traceback (most recent call last): File "", line 1, in ? IndexError: no such group PS.: Please cc your reply to my e-mail address. From mast_nospam at complement.xxx.at Fri Jun 10 05:44:32 2005 From: mast_nospam at complement.xxx.at (Martin Stettner) Date: Fri, 10 Jun 2005 11:44:32 +0200 Subject: Problem in generated files with makepy and Microsoft ADO Message-ID: Hi, when trying to generate the wrapper classes for Microsofts ADO Library (Version 2.8) with makepy, I run into the following problem. Here's what I do (I use ActiveState Python 2.4.1.245) 1.) Running makepy, selecting "Microsoft ActiveX Data Object 2.8" 2.) Starting PythonWin IDE 3.) When I type the following import win32com.client.Dispatch rs = win32com.client.Dispatch("ADODB.Recordset") I get this error Traceback (most recent call last): File "", line 1, in ? File "C:\Programme\Python24\Lib\site-packages\win32com\client\__init__.py", line 96, in Dispatch return __WrapDispatch(dispatch, userName, resultCLSID, typeinfo, UnicodeToString, clsctx) File "C:\Programme\Python24\Lib\site-packages\win32com\client\__init__.py", line 38, in __WrapDispatch klass = gencache.GetClassForCLSID(resultCLSID) File "C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", line 184, in GetClassForCLSID mod = GetModuleForCLSID(clsid) File "C:\Programme\Python24\Lib\site-packages\win32com\client\gencache.py", line 245, in GetModuleForCLSID makepy.GenerateChildFromTypeLibSpec(sub_mod, info) File "C:\Programme\Python24\lib\site-packages\win32com\client\makepy.py", line 307, in GenerateChildFromTypeLibSpec __import__("win32com.gen_py." + dir_name + "." + child) File "C:\Programme\Python24\lib\site-packages\win32com\gen_py\2A75196C-D9EB-4129-B803-931327F72D5Cx0x2x8\_Recordset.py", line 55 def Collect(self, Index=defaultNamedNotOptArg): return self._ApplyTypes_(-8, 2, (12, 0), ((12, 1),), 'Collect', None,Index) ^ SyntaxError: invalid syntax The Line containing the error reads as follows (in the generated _Recordset.py file) # The method Collect is actually a property, but must be used as a method to correctly pass the arguments def Collect(self, Index=defaultNamedNotOptArg): return self._ApplyTypes_(-8, 2, (12, 0), ((12, 1),), 'Collect', None,Index) Strangely, if I delete the comment line, everything runs fine! I've noticed a similar problem with the Properties.py file when I was using the adodbapi module: There I had to delete the generated line from win32com.client import Dispatch which also seems perfectly correct to me. I cannot see any error in the code. As I would like to deploy my application without having my customer to edit this line manually I would appreciate any hint (compiler bug? Bug in the ADO type library?)! Thanks in advance Martin From ivanlan at pauahtun.org Thu Jun 23 11:21:55 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Thu, 23 Jun 2005 09:21:55 -0600 Subject: PEP ? os.listdir enhancement References: Message-ID: <42BAD393.C8B2EF4D@pauahtun.org> Hi All-- Thomas Guettler wrote: > > I like it. But as you noticed, too, "join" would be better than "abs". > > Example: > > # mylistdir.py > import os > import sys > > def mylistdir(dir, join=False): > for file in os.listdir(dir): > yield os.path.join(dir, file) > > print list(mylistdir(sys.argv[1])) > Mmmm, how about: # mylistdir.py import os, os.path import sys def mylistdir(dir, join=False): for file in os.listdir(dir): if join: yield join(dir, file) else: yield file print list(mylistdir(sys.argv[1])) or print list(mylistdir(sys.argv[1],os.path.join)) That way I could def my own join and call it as print list(mylistdir(sys.argv[1],myjoin)) (Note that in your version the join argument isn't used at all.) Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From pinard at iro.umontreal.ca Sat Jun 4 22:01:39 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Sat, 4 Jun 2005 22:01:39 -0400 Subject: Sorted List (binary tree) why no built-in/module? In-Reply-To: <7AA3576E-AE6E-4C0D-AF69-253B28968646@advfn.com> References: <7AA3576E-AE6E-4C0D-AF69-253B28968646@advfn.com> Message-ID: <20050605020139.GA18947@phenix.progiciels-bpi.ca> [Alex Stapleton] > Unless I've totally missed it, there isn't a binary tree/sorted list > type arrangement in Python. Sometimes it might be preferable over > using a list and calling list.sort() all the time ;) Well, after `some_list.sort()', `some_list' is indeed a sorted list. :-) You can use the `bisect' module after that for sorted insertion. Lists can also be used for representing binary trees, and with a bit of imagination, the `heapq' module might help you at keeping a binary tree "half-sorted". This is sometimes sufficient for some applications. Or else, you have to resort to "avl" tree modules, available separately! > On a somewhat unrelated note, does anyone know how python searches > lists when you do things list list.index(n), is it a binary search, or > does it just scan the list? As Python does not know if a list is sorted or not, it cannot binary search them by default. But you, as a programmer, know. Then, the `bisect' module might be helpful for binary searches. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From tiissa at nonfree.fr Sun Jun 12 06:20:29 2005 From: tiissa at nonfree.fr (tiissa) Date: Sun, 12 Jun 2005 12:20:29 +0200 Subject: How to get/set class attributes in Python In-Reply-To: References: Message-ID: <42ac0c6d$0$10102$626a14ce@news.free.fr> Kalle Anke wrote: > I'm coming to Python from other programming languages. I like to > hide all attributes of a class and to only provide access to them > via methods. Some of these languages allows me to write something > similar to this > > int age( ) > { > return theAge > } > > void age( x : int ) > { > theAge = x > } > > (I usually do more than this in the methods). You can 'hide' you getsetters using a property attribute[1]: >>> class person(object): ... def __init__(self): ... self.age = 0 ... def set_age(self, age): ... print 'set %d' % age ... self.__age = age ... def get_age(self): ... print 'get' ... return self.__age ... age = property(get_age, set_age) ... >>> joe = person() set 0 >>> joe.age = 20 set 20 >>> print joe.age get 20 >>> [1]http://docs.python.org/lib/built-in-funcs.html From kay.schluehr at gmx.net Sun Jun 5 04:23:42 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 5 Jun 2005 01:23:42 -0700 Subject: Q: functional/equational language, smells a little of Python In-Reply-To: <871x7hn5za.fsf@pobox.com> References: <871x7hn5za.fsf@pobox.com> Message-ID: <1117959822.889652.257290@g44g2000cwa.googlegroups.com> John J. Lee wrote: > Saw this on LWN: > > http://q-lang.sourceforge.net/ > > > Looks interesting, and reminiscent of symbolic algebra systems like > Mathematica. Also, the website mentions dynamic typing and "Batteries > Included", which made me think of Python. Damned silly name, though > (perhaps pre-Google?). > > Anybody here used it? > > Snippet from the FAQ: > > > 2. Yet another "Haskell for the poor"? > > Not quite. Even though the syntax and some of the stuff in the > standard library looks superficially similar, Q is different in a > number of ways: > > * First and foremost, Q is an equational rather than just a > functional language, meaning that it is based on general term > rewriting instead of the lambda calculus (which is just one, and > very special, rewriting system). In particular, Q has no a > priori distinction between "constructors" and "defined" function > symbols, and argument patterns are not restricted to > "constructor terms". This allows you to have symbolic evaluation > rules like the following distributivity rule: X*(Y+Z) = > X*Y+X*Z. Such rules are not allowed in ML and Haskell because > they violate the "constructor discipline". Moreover, the Q > interpreter also happily reduces expressions involving > variables, so that you can try your definitions with symbolic > inputs (e.g., map F [X,Y] will evaluate to [F X,F Y]), which is > quite useful for debugging purposes. > > * While other functional languages are either "eager" or "lazy", Q > tries to give you the best of both worlds: It uses eager > (call-by-value) evaluation by default (which lends itself to an > efficient implementation), but also allows you to define your > own special forms, which can be used to implement both > call-by-name functions and lazy data constructors. Using special > forms you can also define your own "meta functions" which > manipulate arbitrary (not necessarily irreducible) expressions > as literal terms. This gives you full control over the reduction > strategy, where this is desired, as well as a kind of "macros" > and "self-modifying programs", since constructs like lambda > abstractions can be analyzed, transformed and constructed in > many ways before they are actually evaluated. > > * Q uses dynamic typing. This has become a rare feature in > contemporary functional languages, which usually employ a > Hindley/Milner type system which offers more safety at the > expense of restricting polymorphism. Q gives you back the > flexibility of good old Lisp-style ad-hoc polymorphism and even > allows you to extend the definition of existing operations > (including built-in functions and operators) to your own data > types. Moreover, Q has a Smalltalk-like object-oriented type > system which supports data encapsulation and (single) > inheritance. This makes it possible to manage complex, > polymorphic data with ease. > > * Q takes the pragmatic route in that it provides (monad-free) > imperative programming features such as imperative I/O and > mutable data cells, similar to the corresponding facilities in > ML. While one may argue about these, they certainly make life > easier when programming complex I/O stuff such as graphical user > interfaces. > > * Last but not least, the Q programming system comes with > batteries included. There are quite a few add-on modules > interfacing to third-party libraries which, while not as > comprehensive as the facilities provided by traditional > scripting languages like Perl and Python, allow you to tackle > most practical programming problems with ease. In particular, > multimedia and computer music is an area where Q shines, > providing facilities to handle graphics, digital audio and MIDI > in a convenient and efficient manner (efficient enough for soft > realtime applications), which go well beyond what is currently > being offered for other functional languages. > > > Some of Q's flexibility comes at a price. In particular, Q's symbolic > evaluation capabilities as a term rewriting language dictate that the > language is essentially exception-free. This means that an > "ill-formed" expression (such as "division by zero" or, more > generally, the application of a function to data for which there is no > corresponding definition) does not, by default, raise an exception, > but instead the expression is already in "normal form", i.e., it > evaluates to itself. As a remedy, Q provides facilities to add > explicit error rules which raise exceptions, and to handle exceptions > in a suitable manner. Another limitation is that Q does not allow you > to have arbitrary local definitions in the style of Haskell and ML's > "let" and "where" clauses. In Q, "where" clauses are limited to > variable definitions (similar to Haskell's pattern bindings), but > local rewriting rules are not supported as they would wreak havoc on > the term rewriting semantics. > > You will also notice that Q lacks most of the syntactic sugar found in > Haskell. This is partly due to my laziness, but it also keeps the > language and the core system simple. Using Q's symbolic processing > capabilities, the usual bits like lambda abstractions, pattern > matching conditionals and list comprehensions can easily be written in > Q itself (although this does not offer quite the same performance as > when they are provided as builtins, of course). > > > John I'm curious why do you think that it "smells like Python"? Because of "batteries included"? Are dotNET and Java Python-like because they come up with a fast object library? Personally I think that time has passed for functional languages except for academic studies. Features like term rewriting are interesting per se but I believe that they can be implemented on top of dynamic OO languages like Python with some effort too. My expectation of future Computer Algebra Systems ( CAS ) is that they provide models of mathematical objects like algebras, sets, spaces, manifolds, number-fields etc. that can be refined using inheritance and can be adapted dynamically. Despite the majority of people working in CA I think that OO is much more the way contemporary mathematicians think about their stuff than the FP toolbox approach. What I'm missing is a kind of domain specific syntax, e.g. a syntax for working with states in quantum mechanics. But that's out of the scope of current Python. Regards, Kay From EP at zomething.com Mon Jun 6 02:42:00 2005 From: EP at zomething.com (EP) Date: Sun, 5 Jun 2005 22:42:00 -0800 Subject: urllib2 pinger : insight as to use, cause of hang-up? In-Reply-To: <1118027105.196810.127490@o13g2000cwo.googlegroups.com> References: <1118027105.196810.127490@o13g2000cwo.googlegroups.com> Message-ID: <20050605224200.1978095963.EP@zomething.com> "Mahesh" advised: > > Timing it out will probably solve it. > Thanks. Follow-on question regarding implementing a timeout for use by urllib2. I am guessing the simplest way to do this is via socket.setdefaulttimeout(), but I am not sure if this sets a global parameter, and if so, whether it might be reset via instantiations of urllib, urllib2, httplib, etc. I assume socket and the timeout parameter is in the global namespace and that I can just reset it at will for application to all the socket module 'users'. Is that right? (TIA) [experimenting] >>> import urllib2plus >>> urllib2plus.setSocketTimeOut(1) >>> urllib2plus.urlopen('http://zomething.com') Traceback (most recent call last): File "", line 1, in -toplevel- urllib2plus.urlopen('http://zomething.com') File "C:\Python24\lib\urllib2plus.py", line 130, in urlopen return _opener.open(url, data) File "C:\Python24\lib\urllib2plus.py", line 361, in open response = self._open(req, data) File "C:\Python24\lib\urllib2plus.py", line 379, in _open '_open', req) File "C:\Python24\lib\urllib2plus.py", line 340, in _call_chain result = func(*args) File "C:\Python24\lib\urllib2plus.py", line 1024, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python24\lib\urllib2plus.py", line 999, in do_open raise URLError(err) URLError: >>> urllib2plus.setSocketTimeOut(10) >>> urllib2plus.urlopen('http://zomething.com') > >>> import socket >>> socket.setdefaulttimeout(0) >>> urllib2plus.urlopen('http://zomething.com') Traceback (most recent call last): File "", line 1, in -toplevel- urllib2plus.urlopen('http://zomething.com') File "C:\Python24\lib\urllib2plus.py", line 130, in urlopen return _opener.open(url, data) File "C:\Python24\lib\urllib2plus.py", line 361, in open response = self._open(req, data) File "C:\Python24\lib\urllib2plus.py", line 379, in _open '_open', req) File "C:\Python24\lib\urllib2plus.py", line 340, in _call_chain result = func(*args) File "C:\Python24\lib\urllib2plus.py", line 1024, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python24\lib\urllib2plus.py", line 999, in do_open raise URLError(err) URLError: >>> socket.setdefaulttimeout(1) >>> urllib2plus.urlopen('http://zomething.com') > From dave at pythonapocrypha.com Sun Jun 5 12:02:33 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 05 Jun 2005 10:02:33 -0600 Subject: Socket Speed In-Reply-To: <1117979261.996245.143810@g14g2000cwa.googlegroups.com> References: <1117979261.996245.143810@g14g2000cwa.googlegroups.com> Message-ID: <42A32219.2040809@pythonapocrypha.com> mvanaswegen at gmail.com wrote: > Hi All > > I'm busy writing a python p2p program and would like some advice. > > I'm pushing about 300k/s and would like to know if there are any python > tricks I could pull to speed things up. I'm thinking about unrolling > some of the loops and recuding calls to my custom socket class and > just calling recv and send directly. What is the overhead for using > try and exception blocks ? any recomendations for recv/send sizes ? > On the server side I'm using SocketServer. I was planning to use > twisted > but I don't have the time just get to get into it, SocketServer does > the job. > > I'll post some code soon. Yeah - do post some code as 300k/s is probably *way* below the potential. In one project I'm working on, I do simple file transfers over a single socket with Python on both ends and I routinely get above 500Mbps (often into the high 700's/low 800's - pretty close to what I could hope for for gig over copper with TCP/IP) and the CPU utilization is way low - I assume disk on one end or the other of the connection is a bottleneck now. I use 64k send/receive buffers - above that it doesn't seem to help much for what I'm doing. In any case, before you make any local optimizations (loop unrolling, etc.), I'd do some more investigation to find the problem because something major is broken, and fixing it will probably do way more to improve performance than any optimization "tricks". -Dave From CousinStanley at HotMail.Com Sat Jun 18 09:17:25 2005 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Sat, 18 Jun 2005 06:17:25 -0700 Subject: pysqlite - Checking the existance of a table In-Reply-To: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> References: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> Message-ID: <42b41fd6$1_1@spool9-west.superfeed.net> | I am starting to play with pysqlite, | and would like to know if there is a function | to determine if a table exists or not. rh0dium .... One way to get at a list of table names in an SQLite data base is to query the sqlite_master table .... import sys import sqlite this_db = sys.argv[ 1 ] list_sql = [ "select tbl_name" , "from sqlite_master" ] str_sql = '\n'.join( list_sql ) dbc = sqlite.connect( db = "%s" % this_db ) curs = dbc.cursor() curs.execute( str_sql ) list_tables = curs.fetchall() print '\n Table Names in SQLite DB .... %s \n' % ( this_db ) for table_name in list_tables : print " %s " % ( table_name ) print dbc.close() -- Stanley C. Kitching Human Being Phoenix, Arizona ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From vibtrip at yahoo.com Thu Jun 16 14:39:16 2005 From: vibtrip at yahoo.com (Vibha Tripathi) Date: Thu, 16 Jun 2005 11:39:16 -0700 (PDT) Subject: Set of Dictionary In-Reply-To: <4660fe3005061611217a1b612f@mail.gmail.com> Message-ID: <20050616183916.2253.qmail@web53902.mail.yahoo.com> Thanks for the responses! I tried using list - the real question now is how do I remove duplicate dictionaries? I will try things to work around it...suggestions are welcome. peace. --- Konstantin Veretennicov wrote: > On 6/16/05, Vibha Tripathi > wrote: > > I need sets as sets in mathematics: > > That's tough. First of all, mathematical sets can be > infinite. It's > just too much memory :) > Software implementations can't fully match > mathematical abstractions. > > > sets of any unique type of objects including > those > > of dictionaries, I should then be able to do: > > a_set.__contains__(a_dictionary) and things like > that. > > Maybe you can use a list for that: > > >>> d1 = {1: 2} > >>> d2 = {3: 4} > >>> s = [d1, d2] > >>> {1: 2} in s > True > >>> {5: 6} in s > False > > > Can sets in Python 2.4.1, be reimplemented from > > scratch to not have it work on top of dict? > > Sure, why not? > > - kv > ======= "Things are only impossible until they are not." __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From gsakkis at rutgers.edu Thu Jun 23 02:10:44 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 22 Jun 2005 23:10:44 -0700 Subject: Profiling extension modules Message-ID: <1119507044.832005.90110@g47g2000cwa.googlegroups.com> Is there a (relatively) simple way to profile an extension module, preferably without static linking ? It compiles with 'gcc -pg' but there are a bunch of undefined references at linking (_mcount, _monstartup, __mcleanup); googling for them didn't bring back anything particularly useful. Any ideas ? George From rrr at ronadam.com Fri Jun 3 18:36:14 2005 From: rrr at ronadam.com (Ron Adam) Date: Fri, 03 Jun 2005 22:36:14 GMT Subject: The need to put "self" in every method In-Reply-To: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: Fernando M. wrote: > Hi, > > i was just wondering about the need to put "self" as the first > parameter in every method a class has because, if it's always needed, > why the obligation to write it? couldn't it be implicit? > > Or is it a special reason for this being this way? > > Thanks. Here's how I view it... (It may not be strictly correct, so corrections are welcome.) It helps to think of new style class's as code patterns or templates to create class-instance objects. Since you don't know what the name of the instance object is going to be when you write the class, a way to refer to the contents of the not yet created object is needed. Passing the class-instance reference as the first argument is how Python gets a reference to the local name space of the method. You can then use that name to access the other objects in the class-instance or to create new objects in the class-instance from within the method without knowing what the class-instance name is before hand. Python doesn't pass the 'self' reference when a locally defined function is called inside a class or method. By having to *explicitly* receive the 'self' reference in the argument list, it is clear when the 'self' reference is available for use and when it's not. Cheers, _Ron_Adam From rbt at athop1.ath.vt.edu Sun Jun 5 16:45:45 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 05 Jun 2005 16:45:45 -0400 Subject: mix up a string Message-ID: What's the best way to take a string such as 'dog' and mix it up? You know, like the word jumble in the papers? ODG. I thought something like mix = random.shuffle('dog') would do it, but it won't. Any tips? Thanks, rbt From mwm at mired.org Thu Jun 9 21:17:07 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 09 Jun 2005 20:17:07 -0500 Subject: Fast text display? References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> <863brr6xiw.fsf@guru.mired.org> <7xzmtzm9vi.fsf@ruckus.brouhaha.com> Message-ID: <86is0n57u4.fsf@guru.mired.org> Paul Rubin writes: > Mike Meyer writes: >> > I mean included with the source distro from python.org. >> Well, it includes Tkinter, but it doesn't include tcl/tk. So you get a >> non-functional version of Tkinter if you install from those >> sources. Not very useful. > OK. But I found on RH9 and FC3, as well as on Windows, that tcl/tk > was preinstalled (or included with Python). I didn't find wxwidgets > preinstalled on any of those systems. I think posts are getting crossed here. The python sources you get from www.python.org don't include tcl or tk, which is how the poster I was replying to specified things. >> On FreeBSD, it takes about 5 seconds of my time to install >> wxPython from source: >> >> # cd /usr/ports/x11-toolkits/py-wxPython >> # make install > > What about wxwidgets, which wxpython requires? If the package needs something and it's not installed, the package system will get it and install it. That's the *point* of a package system. >> Then I can go do something useful while the package system downloads, >> compiles and installs all the required software. > > The installer is going to download more stuff? Yuccch, I'd rather not > need a network connection to do an install. The package system can be configured in a number of different ways. My configuration - with a broadband network connection - is to check the local disk cache, then download anything that's missing. You can preload the disk cache by doing "make fetch-recursive" if you want. You can preload the cache by hand if you want, but the package system is very picky about the version numbers of things it's trying to build, so that'd be a pain. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From kveretennicov at gmail.com Tue Jun 21 05:23:50 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Tue, 21 Jun 2005 12:23:50 +0300 Subject: after transfer of data from MS-outlook(mail ids) to application, mail ids are consisting of strange characters In-Reply-To: <1119331449.803907.285750@z14g2000cwz.googlegroups.com> References: <1119331449.803907.285750@z14g2000cwz.googlegroups.com> Message-ID: <4660fe300506210223118b1741@mail.gmail.com> On 20 Jun 2005 22:24:09 -0700, vamsikrishna_b at coolgoose.com wrote: > > Hello all, ... > I hope somebody will help > me in this regard to unfold this mystery.Bye. I hope you will explain how this is related to Python. - kv From bdesth.quelquechose at free.quelquepart.fr Mon Jun 13 16:57:41 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 13 Jun 2005 22:57:41 +0200 Subject: Controlling assignation In-Reply-To: References: Message-ID: <42aded8f$0$31916$636a15ce@news.free.fr> Xavier D?coret a ?crit : (snip) > What I wanted to do is something like this: > > def change(x,v): > x = v > > class A(object): > def __init__(self,v): > self.x = v > > a = A(3) > print a.x # displays 3 > change(a.x,4) > print a.x # still displays 3 > > > It may seem weird, It does > but I ensure there is a reason for doing this. I really wonder what it can be ??? > In C++ > (the language I am mot familiar with), I could define f to take a > pointer to member function of a class, a pointer and a value and achieve > what I want. In python, I cannot that way becauswe when change(a.x,4) is > executed, a.x is "replaced" by ist value (returned by __getattribute__). > > Finally, here is how I hold the situation: > > > class Handle: > def __init__(self,v): > self.__v = v > def __call__(self): > x = self.__v > while callable(x): x=x() > return x > def set(self,v): > self.__v = v > > class HandledProperty(object): > def __init__(self,name=""): > self.name = name > def __get__(self,o,t): > return o.__dict__[self] > def __set__(self,o,v): > o.__dict__[self] = Handle(v) > > class A(object): > x = HandledProperty("x") > def __init__(self,v): > self.x = v > > def change(x,v): > x.set(v) > > > a = A(3) > print a.x() # displays 3 (notice the () in the call) > change(a.x,4) > print a.x() # still displays 4 You could achieve the same effect with: class A( object): def __init__(self, value): self.value = value a = A(3) a.value = 4 a.value => 4 And it's *much* more simple/readable/efficient. Ever googled for "evolution of a programmer" ?-) From onurb at xiludom.gro Thu Jun 30 06:35:59 2005 From: onurb at xiludom.gro (bruno modulix) Date: Thu, 30 Jun 2005 12:35:59 +0200 Subject: script fichiers binaires lecture =?ISO-8859-1?Q?=E9criture?= In-Reply-To: <1120122593.162554.71410@g14g2000cwa.googlegroups.com> References: <1120122593.162554.71410@g14g2000cwa.googlegroups.com> Message-ID: <42c3cb10$0$9315$626a14ce@news.free.fr> Statesman wrote in comp.lang.python: Hi Statesman comp.lang.python is the english-speaking Python forum. You may want to try the french-speaking one at fr.comp.lang.python (xpost and fu2 set) > Je connais mal python et n'est pas trop le temps de m'y plonger bien > que cela semble ?tre assez puissant... > > import sys > import ixio > import os > > M = ixio.getMAC("eth0") > S = "%08X %08X" % (M[0] | M[1]<<8 | M[2]<<16 | M[3]<<24, M[4] | > M[5]<<8) > K = "Errorin:" > if len(sys.argv) <> 3: > print "Usage %s " % sys.argv[0] > else: > I = open(sys.argv[1],"rb")#ouverture de tpsd.pre avec le flag rb > pour read in binary mode > O = open(sys.argv[2],"wb") > while 1: > blk = I.read(1<<13) > try: > i = blk.index(K) > blk = "%sErrorin:%s%s" \ > % (blk[:i],S,blk[i+len(K)+len(S):]) > O.write(blk) > except ValueError: > O.write(blk) > if len(blk)<1<<13: > break > O.close() > I.close() > > Voici l'erreur que j'obtiens en essayant d'ex?cuter ce script: > > AttributeError: 'string' object has no attribute 'index' > > D'apr?s moi, index est une m?thode de la classe string et non un > attribut...Je ne comprend donc pas... En Python, les fonctions sont des objets comme les autres. Donc les methodes sont effectivement des attributs... (bon, dans le d?tail c'est un poil plus compliqu? que ?a, mais l? je te laisse consulter la doc... si tu tiens vraiment ? comprendre tous les d?tails d'impl?mentation) > Enfin, je pr?cise que je suis > malheureusement en version 1.5 de python... :( Euh... la derni?re est la 2.4.1, il serait peut-?tre temps d'envisager une mise ? jour. En attendant, dans la 1.5.x, tu peux utiliser le module String: import String s = "allo" String.index(s, "a") (de m?moire, pas test?). > Autre question: 1<<13 est cens? ?tre une taille en octet: comment > cela se lit-t-il? op?rateur de d?calage de bits... 1 << 13 == 8192 > Merci d'avance de m'aclairer sur cette erreur et cette question. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mkluwe at gmail.com Fri Jun 17 15:15:36 2005 From: mkluwe at gmail.com (Matthias Kluwe) Date: 17 Jun 2005 12:15:36 -0700 Subject: pysqlite - Checking the existance of a table In-Reply-To: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> References: <1119028252.605777.153340@g49g2000cwa.googlegroups.com> Message-ID: <1119035735.976427.172080@g43g2000cwa.googlegroups.com> Simply use the internal table SQLite_Master: select name from SQLite_Master will return all existing tables. Regards, Matthias From tjreedy at udel.edu Sun Jun 26 22:42:40 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 26 Jun 2005 22:42:40 -0400 Subject: Acceptance test spike example References: Message-ID: "Steve Jorgensen" wrote in message news:mhcub1p3mlcbnsf0dqk9akdrm5ut347rd0 at 4ax.com... > Note how the powerful, context-aware exec() and eval() procedures really > help > simplify the code. A stylistic note: I believe that most or all of your eval/exec uses could be done with getattr and setattr instead, which are in the language for precisely those situations in which the name of an attribute is in a runtime string. To my mind, this would be simpler and better style. > valueExpr = "self.model." + parsed.name > valueIs = eval(valueExpr) I believe this is valueIs = getattr(self.model, parsed.name) > methodCall = "self.model." + parsed.name +"(" + parsed.value + ")" > exec(methodCall) I believe this is getattr(self.model, parsed.name)(parsed.value). > exec("self.model." + parsed.name + "=" + parsed.value) I believe this is setattr(self.model, parsed.name, parsed.value). and so on. Terry J. Reedy From mandus at gmail.com Sat Jun 25 16:10:21 2005 From: mandus at gmail.com (Mandus) Date: Sat, 25 Jun 2005 20:10:21 +0000 (UTC) Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Sat, 25 Jun 2005 21:30:26 +0200 skrev Peter Otten: > Mandus wrote: > >> By using the builtin reduce, I >> move the for-loop into the c-code which performs better. > > No. There is no hope of ever writing fast code when you do not actually > measure its performance. I do. -- Mandus - the only mandus around. From eurleif at ecritters.biz Sat Jun 4 19:37:21 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 04 Jun 2005 23:37:21 GMT Subject: method = Klass.othermethod considered PITA In-Reply-To: <87oeallp44.fsf@pobox.com> References: <87oeallp44.fsf@pobox.com> Message-ID: John J. Lee wrote: > class Klass: > > def _makeLoudNoise(self, *blah): > ... > > woof = _makeLoudNoise > > [...] > > At least in 2.3 (and 2.4, AFAIK), you can't pickle classes that do > this. Works for me: Python 2.3.5 (#2, May 4 2005, 08:51:39) [GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> class Foo: ... def foo(self): ... print "Hello, world!" ... bar = foo ... >>> pickle.dumps(Foo) 'c__main__\nFoo\np0\n.' >>> pickle.dumps(Foo()) '(i__main__\nFoo\np0\n(dp1\nb.' From wirtz at dfn.de Tue Jun 21 10:21:40 2005 From: wirtz at dfn.de (Holger Wirtz) Date: Tue, 21 Jun 2005 16:21:40 +0200 Subject: How do I access avariable named "return"? References: <1119363472.631871.173590@g47g2000cwa.googlegroups.com> Message-ID: Brian Beck wrote: >> I think this seems to be a problem due to the use of a forbidden word. >> But I have no chance to change the WSDL definition, so: How can I get the >> variable resp.return? Any suggestions? > > To get it: getattr(resp, 'return') > To set it: setattr(resp, 'return', value) > > -- > Brian Beck > Adventurer of the First Order Ahhh! That's it! Thanks a lot!!! Holger From python at rcn.com Tue Jun 7 03:07:16 2005 From: python at rcn.com (Raymond Hettinger) Date: 7 Jun 2005 00:07:16 -0700 Subject: random module question References: <1118079065.795771.248640@g49g2000cwa.googlegroups.com> <7x1x7f70xq.fsf@ruckus.brouhaha.com> Message-ID: <1118128036.661484.272760@g14g2000cwa.googlegroups.com> >> Is Mersenne Twister currently available at all in Jython, for example? Googling for "java mersenne twister" provides multiple hits including: http://www.axlradius.com/freestuff/Free.htm#MT Raymond From peter at engcorp.com Mon Jun 13 12:56:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Jun 2005 12:56:56 -0400 Subject: Controlling assignation In-Reply-To: References: Message-ID: Xavier D?coret wrote: > What I wanted to do is something like this: > > def change(x,v): > x = v > > class A(object): > def __init__(self,v): > self.x = v > > a = A(3) > print a.x # displays 3 > change(a.x,4) > print a.x # still displays 3 How about this? def change(x, v): x.x = v Then call it with change(a, 4) And print a.x will return 4 as you wish. > It may seem weird, but I ensure there is a reason for doing this. In C++ > (the language I am mot familiar with), I could define f to take a > pointer to member function of a class, a pointer and a value and achieve > what I want. In Python the closest match to this might be to pass the reference to the object, plus the *name* of the attribute, as a string. def change(obj, attr, v): setattr(obj, attr, v) This, of course, is now a useless function since that's what "setattr" already does... So: a = A(3) print a.x # displays 3 setattr(a, 'x', 4) print a.x # displays 4 -Peter From willie at macleod-group.com Sat Jun 18 09:09:40 2005 From: willie at macleod-group.com (willie at macleod-group.com) Date: 18 Jun 2005 06:09:40 -0700 Subject: Threading and serial port access Message-ID: <1119100180.442972.244100@g14g2000cwa.googlegroups.com> Hi, I'm writing a program which requires the use of three serial ports and one parallel port. My application has a scanning devices on each port, which I can access fine with pyserial. However, I'm unsure of how exactly I should be designing the program, I thought I could use threading to start class: class scanner(Thread): def __init__(self,port): Thread.__init__(self) self.port = port def scan(self): ser = serial.Serial(port) print ser.portstr id = ser.read(12) ser.close But this doesn't work as I thought when I call it like: for port in range(0,totalserialports): # loop through all serial ports print "starting thread for port %d" %(port) NewThread = scanner(port) NewThread.scan() NewThread.start() I get: starting thread for port 0 /dev/ttyS0 Now, I know that I haven't specified any port timeouts, but I don't want it to timeout, I want to open each port and keep it open indefinately. Threading seems to block waiting for the read from the serial port. How can I open every serial port at the same time, read from it, do an action and then go back to it? Anyone got any good documentation sources for threading that explain things clearly and gives examples? (I'm running python 2.3.4) What's the most python like way of achieving my end goal? Thanks Regards William MacLeod From giovanni at poseidon.home.net Fri Jun 24 21:08:51 2005 From: giovanni at poseidon.home.net (Giovanni Tumiati) Date: Fri, 24 Jun 2005 21:08:51 -0400 Subject: Newbie question: SOLVED (how to keep a socket listening), but still some questions Message-ID: To all those that replied - thank you. I solved the problem I posted earlier. I'm embarrassed to admit that it was caused by the following: ... while 1: ## wait for a connection try: #...waiting for connection (client, address)=sa.accept() except sa.timeout: <--------------there is no such exception for a socket! #...waiting for connection timeout continue except: continue ## for now ignore this! ... There is no "timeout exception" on a socket so the exception was failing. I don't remember where I read about it, but now I cannot find such an exception...I guess I dreamt it up :-) However some of my questions still remain from earlier post: (1) What is the difference between / how should they be used? - setdefaulttimeout(timeout) - settimeout(value) (2)Does one have to do a socket.shutdown() before one does a socket.close?? Again thanks! pete From kveretennicov at gmail.com Wed Jun 15 05:28:58 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Wed, 15 Jun 2005 12:28:58 +0300 Subject: Single test for a class and all its subclasses? In-Reply-To: <007c01c57180$d6619880$0201a8c0@mcuf7> References: <007c01c57180$d6619880$0201a8c0@mcuf7> Message-ID: <4660fe3005061502283c37d7a8@mail.gmail.com> On 6/15/05, Anthra Norell wrote: > > class C: ... > class C2 (C): ... > > # What I want to do: > > if x.__class__ in (C, C2): > do_something_with (x) If you have an instance, you can use isinstance() built-in. - kv From kent37 at tds.net Mon Jun 20 13:31:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Jun 2005 13:31:39 -0400 Subject: utf8 and ftplib In-Reply-To: References: <1119267462.32655.236736750@webmail.messagingengine.com> Message-ID: <42b6fcee_1@newspeer2.tds.net> Richard Lewis wrote: > My code now works without generating any errors but Konqueror's KHTML > and Embedded Advanced Text Viewer and IE5 on the Mac still show > capital-A-with-a-tilde in all the files that have been > generated/altered. Whereas my text editor and Mozilla show them > correctly. How are you viewing the files? You have to tell the browser that they are UTF-8. If you just double-click the file, the browser will use its default encoding. If you are server the files from a web server then you should set the Content-Type header correctly. Or you can tell the browser directly (try View / Encoding in IE). Kent From d at e.f Mon Jun 13 22:46:03 2005 From: d at e.f (D H) Date: Mon, 13 Jun 2005 21:46:03 -0500 Subject: The need to put "self" in every method In-Reply-To: References: <1117554344.938440.54700@g14g2000cwa.googlegroups.com> Message-ID: <-a-dnTlOx41t2TPfRVn-2Q@comcast.com> Steve Holden wrote: > Fernando M. wrote: > >> Hi, >> >> i was just wondering about the need to put "self" as the first >> parameter in every method a class has because, if it's always needed, >> why the obligation to write it? couldn't it be implicit? >> >> Or is it a special reason for this being this way? >> >> Thanks. One reason is because of the dynamic nature of Python classes. You can attach new methods to a class after it is instantiated, or remove methods. The language boo (http://boo.codehaus.org/) has classes defined at compile time, and there "self" is not needed at all. If you want to use the duck typing features in boo, however, and re-implement python-like dynamic classes that can have methods removed or added at any time, then your methods need some kind of "self" parameter so they can access the context of their class instance, because really there is no special relationship between the methods and the class unless you explicitly specify it. > The reason can be found in the output from the python statement "import > this". Explicit is better than implicit. Like those invisible yet explicit scope indicators, tabs and spaces. From irmen.NOSPAM at xs4all.nl Sat Jun 11 09:58:26 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 11 Jun 2005 15:58:26 +0200 Subject: Sending mail from 'current user' in Python In-Reply-To: <1118461971.461936.327550@g14g2000cwa.googlegroups.com> References: <3gsve7Fe8957U1@individual.net> <1118461971.461936.327550@g14g2000cwa.googlegroups.com> Message-ID: <42aaee03$0$71235$e4fe514c@news.xs4all.nl> Grig Gheorghiu wrote: > I use this function as a platform-independent way of finding out the > current user name: > > def get_username(): > if sys.platform == 'win32': > return win32api.GetUserName() > else: > return getpass.getuser() > [e:\]python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import getpass >>> getpass.getuser() 'idj' So why bother with the win32api?? --Irmen From be_veronic at yahoo.com Mon Jun 6 09:48:39 2005 From: be_veronic at yahoo.com (Veronica Tomescu) Date: Mon, 6 Jun 2005 06:48:39 -0700 (PDT) Subject: killing process in windows Message-ID: <20050606134839.36485.qmail@web32510.mail.mud.yahoo.com> Hi, I am using Trent's process.py but I have a problem with killing the processes in windows. For example : import process,time p=process.ProcessOpen('C:\Program Files\Windows Media Player\wmplayer') time.sleep(3) p.kill() will start Media Player without terminating it. Any suggestions? Thanks in advance. Veronica --------------------------------- Discover Yahoo! Get on-the-go sports scores, stock quotes, news & more. Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: From chinook.nr at tds.net Sat Jun 18 04:39:54 2005 From: chinook.nr at tds.net (Chinook) Date: Sat, 18 Jun 2005 04:39:54 -0400 Subject: OO approach to decision sequence? References: <0001HW.BED934BC000AAFCAF00FF3B0@smtp.tds.net> <42B3D2BC.3050406@po-box.mcgill.ca> Message-ID: <0001HW.BED9561A00128216F0407550@news.gmane.org> On Sat, 18 Jun 2005 03:52:28 -0400, Brian van den Broek wrote (in article <42B3D2BC.3050406 at po-box.mcgill.ca>): > Chinook said unto the world upon 18/06/2005 02:17: >> OO approach to decision sequence? >> --------------------------------- >> >> In a recent thread (Cause for using objects?), Chris Smith replied with (in >> part): >> >> >>> If your table of photo data has several types of photos, and you find >>> yourself saying >>> >>> if is_mugshot: >>> #something >>> elif is_freehand: >>> #something >>> else: >>> #something >>> >>> then OOP will help organize your code. >> >> >> This struck a chord because I'm trying to refactor a top-down approach to >> an >> OO approach. The reason I am doing such is to try and get my mind wrapped >> around OO design, not because the particular module will benefit from an OO >> approach (it's a simple top-down recursive tree utility). In fact it's >> probably ill suited for OO and that is why I chose it. >> >> I've used an OO approach where I built up record (instance) content in a >> variable record file, but here I'm trying to come at it from the opposite >> direction as variable record mapping (deconstructing) would be to such. >> >> Anyway, a tree node can be any of seven types where: >> >> if node_type_1: >> # recurse >> elif node_type_2: >> # terminus - do something >> elif node_type_3: >> # terminus - do something else >> ... >> else: >> # terminus - catch all, do yet something else >> return #to parent >> >> So, where is the magic :~) Seriously, how might OO help me organize this >> type of problem (alleviate the conventional lengthy if structure)? I've >> looked at the cookbook, class interface techniques, factory functions and >> metaclasses till my head is swimming. Am I missing a bolt in the machinery >> somewhere, or simply trying to find magic that doesn't exist for a >> straightforward decision sequence? >> >> Thank you, >> Lee C > > > Hi Lee, > > I'm a hobbyist who came to grok the OO approach in the last 6 months > or so ago. So, take the comments with that in mind. > > A simple toy example with the "if type" test approach: > > >>> class A(object): > ... pass > ... > >>> class B(object): > ... pass > ... > >>> a = A() > >>> b = B() > >>> for item in (a, b): > ... if type(item) == A: > ... ident = "an A" > ... if type(item) == B: > ... ident = "a B" > ... print "Found %s" %ident > ... > Found an A > Found a B > >>> > > > Now, the same sort of behaviour where the "if type" testing has been > replaced with code more in keeping with the OOP approach: > > >>> class C(object): > ... def report(self): > ... print "Found a C" > ... > >>> class D(object): > ... def report(self): > ... print "Found a D" > ... > >>> c = C() > >>> d = D() > >>> for item in (c, d): > ... item.report() > ... > Found a C > Found a D > >>> > > > A metaphorical explanation that is a bit handwavy, but that I find useful: > > In both approaches, there is a common behaviour you want the various > types of objects to exhibit. (In a less 'toy' example the behaviour > would be more complicated.) > > In the "if type" style, you are asking each object what kind of object > it is, and then setting an aspect of the behaviour as a function of > the answer. > > In the more OOP approach, you rely on the fact that each object knows > what kind of object it is. So, you don't need to ask it, and adjust > the behaviour accordingly. You just tell it to behave, and, knowing > what kind of thing it is, it knows how to behave as befits that kind > of thing. > > Two big benefits in the context are that if you need to exhibit the > same behaviour in multiple places, you don't have multiple "if type" > chains, and, if you want to add a type, with its own specific > behaviour, you just add a class, and there is no worry about hunting > down the "if type" chains to update them. > > There was a thread on the tutor list around mid-Feb. which really > helped me come to understand the idea. Actually, from Dec. to Feb. or > so, there are several long tutor threads where people gave me much > useful help coming to see how to employ OOP. Might be worth a trip > through the archive. > > HTH, > > Brian vdB > > > Thanks for the reply Brian. I understand what you are saying. The point I'm messing up my head with though, is when the entity (tree node in my case or variable record content deconstructing in the aspect example I noted) is not an instance of a class already - it is obtained from an external source and only decipherable by its content. In practical terms that leaves me with some decision sequence regardless and I was wondering (from what Chris Smith said) how that might be done in OOP. The whole problem may be that I'm reading too much into what Chris said :~) I will dig back through the Tutor archives as you suggested. Thanks again, Lee C From hancock at anansispaceworks.com Tue Jun 21 02:34:54 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 21 Jun 2005 01:34:54 -0500 Subject: Extensions on Linux: import without underscore? In-Reply-To: <42b6aa49$1_3@newspeer2.tds.net> References: <42b6aa49$1_3@newspeer2.tds.net> Message-ID: <200506210134.54677.hancock@anansispaceworks.com> On Monday 20 June 2005 06:39 am, Kent Johnson wrote: > Terry Hancock wrote: > > Okay, you may want a more elegant way to do this and other people > > have already responded to that point, but you do at least know you > > can just give it a new name: > > > > import _bright > > bright = _bright > > or more idiomatically and without adding _bright to the namespace: > import _bright as bright Um, yeah, I knew that. Really I did. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From merkosh at hadiko.de Thu Jun 23 11:53:50 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Thu, 23 Jun 2005 17:53:50 +0200 Subject: don't understand MRO Message-ID: Hi, I have a subclassed PyQt class: class Node(object): def move(self, x,y): pass class CRhomb(QCanvasPolygon, Node): pass $ python v2.4.1 >>> CRhomb.mro() [, , , , , , , ] >>> a = CRhomb() >>> a.move(1,2) This executes also Node.move(a, 1,2) Why? Because even QCanvasItem.move delegates the call to the derived object? But qt.Qt does not have a move() method... how does it get passed on to Node? Thanks in advance, Ciao Uwe From codedivine at gmail.com Wed Jun 8 08:29:26 2005 From: codedivine at gmail.com (Rahul) Date: 8 Jun 2005 05:29:26 -0700 Subject: computer algebra packages In-Reply-To: <1118209749.248567.168700@g49g2000cwa.googlegroups.com> References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <1118209749.248567.168700@g49g2000cwa.googlegroups.com> Message-ID: <1118233766.928467.261650@z14g2000cwz.googlegroups.com> Hi. The reason is simple enough. I plan to do some academic research related to computer algebra for which i need some package which i can call as a library. Since i am not going to use the package myself..(rather my program will)..it will be helpful to have a python package since i wanted to write the thing in python. if none is available then probably i will need to work on an interface to some package written in some other language or work in that language itself. rahul Kay Schluehr wrote: > Rahul wrote: > > Hi. > > Well is there an open source computer algebra system written in python > > or at least having a python interface? > > I know of 2 efforts: pythonica and pyginac...are there any others? > > > > rahul > > Not in the moment. But I have a question to you: why do you seek for a > CAS in Python? I ask this because I'm interested in such kind of stuff > and secretly working on one, but this is highly experimental, a proof > of the concept work and will probably not provide the amount of > features/packages of a commercial CAS like Mathematica and Maple in a > dozend years. There are also a couple of free CAS like Octave or Yacas, > that do their job. Why do people ask periodically for a CAS in Python > in this place? I'm just curious about it. > > Kay From agriff at tin.it Mon Jun 13 20:50:17 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 14 Jun 2005 00:50:17 GMT Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> Message-ID: <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> On Mon, 13 Jun 2005 01:54:53 -0500, Mike Meyer wrote: >Andrea Griffini writes: >>>In short, you're going to start in the middle. >> >> I've got "bad" news for you. You're always in the >> middle :-D. > >That's what I just said. Yeah. I should stop replying before breakfast. >I disagree. If you're going to make competent programmers of them, >they need to know the *cost* of those details, but not necessarily the >actual details themselves. It's enough to know that malloc may lead to >a context switch; you don't need to know how malloc actually works. Unless those words have a real meaning for you then you'll forget them... I've seen this a jillion times with C++. Unless you really understand how an std::vector is implemented you'll end up doing stupid things like looping erasing the first element. Actually I cannot blame someone for forgetting that insert at the beginning is O(n) and at the end is amortized O(1) if s/he never understood how a vector is implemented and was told to just learn those two little facts. Those little facts are obvious and can easily be remembered only if you've a conceptual model where they fit. If they're just random notions then the very day after the C++ exam you'll forget everything. >That's the way *your* brain works. I'd not agree that mine works that >way. Then again, proving either statement is an interesting >proposition. Are you genuinely saying that abelian groups are easier to understand than relative integers ? >The explanation has been stated a number of times: because you're >letting them worry about learning how to program, before they worry >about learning how to evaluate the cost of a particular >construct. Especially since the latter depends on implementation >details, which are liable to have to be relearned for every different >platform. You'll get programmers that do not understand how their programs work. This unavoidably will be a show stopper when their programs will not work (and it's when, not if...). >I don't normally ask how people learned to program, but I will observe >that most of the CS courses I've been involved with put aside concrete >issues - like memory management - until later in the course, when it >was taught as part of an OS internals course. The exception would be >those who were learning programming as part of an engineering (but not >software engineering) curriculum. The least readable code examples >almost uniformly came from the latter group. I suppose that over there who is caught reading TAOCP is slammed in jail ... Placing memory allocation in the "OS internals" course is very funny. Let's hope you're just joking. Andrea From jgrahn-nntq at algonet.se Sun Jun 12 06:14:50 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jun 2005 10:14:50 GMT Subject: unittest: collecting tests from many modules? Message-ID: I have a set of tests in different modules: test_foo.py, test_bar.py and so on. All of these use the simplest possible internal layout: a number of classes containing test*() methods, and the good old lines at the end: if __name__ == "__main__": unittest.main() This is great, because each of the modules are runnable, and I can select classes or tests to run on the commandline if I want to. However, running all the tests from e.g. a Makefile is not that fun; I don't get a single pass/fail summary across the modules. What's the best way of creating a test.py which - aggregates the tests from all the test_*.py modules? - doesn't require me to enumerate all the test classes in test.py (forcing each module to define test_foo.theSuite or someting would be OK though) - retains the ability to select tests and verbosity (-q, -v) from the command line? Something like: import unittest import test_foo import test_bar if __name__ == "__main__": unittest.main(modules = ['test_foo', 'test_bar']) Seems to me this should be possible, since all the logic for doing it /is/ there for the local module; I'd assume there would be a way to make unittest search additional modules for test classes. But my head starts spinning when I read the source code ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From cookedm+news at physics.mcmaster.ca Fri Jun 10 13:59:39 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 10 Jun 2005 13:59:39 -0400 Subject: without shell References: <11aj9d3fga9or8b@corp.supernews.com> Message-ID: Donn Cave writes: > In article <11aj9d3fga9or8b at corp.supernews.com>, > Grant Edwards wrote: > >> On 2005-06-10, Mage wrote: >> >> >>py> file_list = os.popen("ls").read() >> >> >> >>Stores the output of ls into file_list. >> >> >> > These commands invoke shell indeed. >> >> Under Unix, popen will not invoke a shell if it's passed a >> sequence rather than a single string. > > I suspect you're thinking of the popen2 functions. > On UNIX, os.popen is posix.popen, is a simple wrapper > around the C library popen. It always invokes the > shell. > > The no-shell alternatives are spawnv (instead of > system) and the popen2 family (given a sequence > of strings.) Don't forget the one module to rule them all, subprocess: file_list = subprocess.Popen(['ls'], stdout=subprocess.PIPE).communicate()[0] which by default won't use the shell (unless you pass shell=True to it). -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From abo at minkirri.apana.org.au Thu Jun 30 16:05:43 2005 From: abo at minkirri.apana.org.au (ABO) Date: 30 Jun 2005 13:05:43 -0700 Subject: Life of Python References: Message-ID: <1120161943.546614.111390@o13g2000cwo.googlegroups.com> > Okay. This makes sense if the software is: > > 1) Designed by one institution. > 2) Designed almost entirely before deployment. > 3) Not designed to be worked on by users and > semi-trained developers. > > In other words --- proprietary software. In my experience, it doesn't work well even in these cases. Investing a huge amount of effort designing in detail well in advance is nearly always a mistake, unless the requirements are fully understood and static... ie never. Mostly the requirements are unknown until the (possibly internal) customer has something. Nothing identifies requirements better than deployment. Particularly with large projects that have long development times, even if the requirements are well understood at the start, they will have changed by the time it is deployed. The biggest and most common mistake with software development is believing that it finishes. Software has a lifecycle, and development is like food; it is constantly required, otherwise the software dies. -- Donovan Baarda From chad.hughes at pnl.gov Fri Jun 10 13:12:08 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Fri, 10 Jun 2005 10:12:08 -0700 Subject: how to operate the excel by python? Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B615E@pnlmse27.pnl.gov> Sorry, I meant to spell check but I did not somehow. Chad -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of Hughes, Chad O Sent: Friday, June 10, 2005 10:01 AM To: python-list at python.org Subject: RE: how to operate the excel by python? Here are two scripts that I have had to build for a class that I teach. You will either need to write the constants explicitly, or I can email neet the constans module that I have built, for the second one to work. I will copy it to the very end. If you have any questions, just let me know. Here is a simple one that allows me to interface with my grade book spreadsheet though the command line for taking attendance: from win32com.client import Dispatch import time xl = Dispatch('Excel.Application') wb = xl.Workbooks.Open('C:\\Documents and Settings\\My Documents\\discrete\\GradeBook.xls') ws = wb.Worksheets.Item(1) ws.Activate() i = 1 while True: if ws.Cells(1,i).Text == '': break i += 1 t = time.localtime() d = '%s/%s/%s'%(t.tm_mon,t.tm_mday,t.tm_year) ws.Cells(1,i).FormulaR1C1 = d ws.Cells(2,i).Select() j = 2 while True: name = ws.Cells(j,1).Text if name == '': break name = name.split()[1] here = int(raw_input('%s here? '%name)) ws.Cells(j,i).FormulaR1C1 = here j += 1 wb.Save() The next one is a kluge (spaghetti code), sorry but it is complete. It builds a truth table for evalutating logic expressions: from win32com.client import Dispatch >From officecon.xlcon import * xl = Dispatch('Excel.Application') binary = False # set this to true to use 0 and 1 instead of False and True vars = raw_input("Comma seperate the variables:") headers = raw_input("What other headers do you want, comma seperated?") headers = headers.split(',') vars = vars.split(',') numToAlpha = 'abcdefghijklmnopqrstuvwxyz' if not xl.Visible: xl.Workbooks.Add() xl.Worksheets.Add() for i in range(3): sheet = xl.Worksheets.Item(2) sheet.Delete() xl.ActiveWindow.SelectedSheets.Delete else: xl.Worksheets.Add() sheet = xl.Worksheets.Item(1) if len(headers[-1]) > 30: sheet.name = headers[-1][:27]+'...' elif headers[-1] == '': sheet.name = 'Example' else: sheet.name = headers[-1] xl.Visible = True for i in range(len(vars)): sheet.Range(numToAlpha[i]+'1').FormulaR1C1 = vars[i] sheet.Rows("1:1").Select() xlBottom = -4107 xlCenter = -4108 xl.Selection.NumberFormat = "General" xl.Selection.HorizontalAlignment = xlCenter xl.Selection.VerticalAlignment = xlBottom xl.Selection.Font.name = "Areial" xl.Selection.Font.FontStyle = "Bold" xl.Selection.Font.Size = 12 rows = [] number = 2**len(vars) for i in range(number): row = [] for j in range(len(vars)): row.append((i%(2**(len(vars)-j)))/(2**(len(vars)-j-1))) rows.append(row) for row in range(len(rows)): for column in range(len(rows[row])): if not rows[row][column]: if binary: value = 0 else: value = 'TRUE' else: if binary: value = 1 else: value = 'FALSE' sheet.Range(numToAlpha[column]+`row+2`).FormulaR1C1 = value for i in range(len(headers)): sheet.Range(numToAlpha[i+len(vars)]+'1').FormulaR1C1 = headers[i] sheet.Range(numToAlpha[i+len(vars)]+'1').Select() sheet.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+`number+1`).Select() xl.Selection.Borders(xlDiagonalDown).LineStyle = xlNone xl.Selection.Borders(xlDiagonalUp).LineStyle = xlNone xl.Selection.Borders(xlEdgeLeft).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeLeft).Weight = xlThick xl.Selection.Borders(xlEdgeLeft).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeTop).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeTop).Weight = xlThick xl.Selection.Borders(xlEdgeTop).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeBottom).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeBottom).Weight = xlThick xl.Selection.Borders(xlEdgeBottom).ColorIndex = xlAutomatic xl.Selection.Borders(xlEdgeRight).LineStyle = xlContinuous xl.Selection.Borders(xlEdgeRight).Weight = xlThick xl.Selection.Borders(xlEdgeRight).ColorIndex = xlAutomatic xl.Selection.Borders(xlInsideVertical).LineStyle = xlContinuous xl.Selection.Borders(xlInsideVertical).Weight = xlThin xl.Selection.Borders(xlInsideVertical).ColorIndex = xlAutomatic xl.Selection.Borders(xlInsideHorizontal).LineStyle = xlContinuous xl.Selection.Borders(xlInsideHorizontal).Weight = xlThin xl.Selection.Borders(xlInsideHorizontal).ColorIndex = xlAutomatic xl.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+'2').Select() xl.Selection.Borders(xlInsideHorizontal).Weight = xlThick xl.Range(numToAlpha[len(vars)-1]+'1:'+numToAlpha[len(vars)]+`number+1`).Select() xl.Selection.Borders(xlInsideVertical).LineStyle = xlDouble xl.Range(numToAlpha[len(vars)+len(headers)-1]+'1:'+numToAlpha[len(vars)+len(headers)-1]+`number+1`).Select() xl.Selection.Borders(xlEdgeLeft).LineStyle = xlDashDotDot xl.Selection.Interior.ColorIndex = 20 xl.Selection.Interior.Pattern = xlSolid #xl.Selection.Borders(xlEdgeLeft).Weight = xlThick #xl.Selection.Borders(xlEdgeTop).Weight = xlThick #xl.Selection.Borders(xlEdgeBottom).Weight = xlThick xl.Selection.Borders(xlEdgeRight).Weight = xlThick #xl.Selection.Borders(xlInsideVertical).Weight = xlThin #xl.Selection.Borders(xlInsideHorizontal).Weight = xlThin xl.Range("A1:"+numToAlpha[len(vars)+len(headers)-1]+'2').Select() xl.Selection.Borders(xlInsideHorizontal).Weight = xlThick xl.Range("A2:"+numToAlpha[len(vars)-1]+`number+1`).Select() xl.Selection.Interior.ColorIndex = 35 xl.Selection.Interior.Pattern = xlSolid xl.Selection.Interior.PatternColorIndex = xlAutomatic #gray every other row for i in range(number): if i%2: xl.Range('A'+`i+1`+':'+numToAlpha[len(vars)+len(headers)-2]+`i+1`).Select() xl.Selection.Interior.ColorIndex = 2 xl.Selection.Interior.Pattern = xlLightUp xl.Selection.Interior.PatternColorIndex = xlAutomatic #gray every other row of answers only dark grey for i in range(number): if i%2: xl.Range(numToAlpha[len(vars)+len(headers)-1]+`i+1`+':'+numToAlpha[len(vars)+len(headers)-1]+`i+1`).Select() xl.Selection.Interior.ColorIndex = 20 xl.Selection.Interior.Pattern = xlLightUp xl.Selection.Interior.PatternColorIndex = xlAutomatic #gray every other row of vars only dark grey for i in range(number): if i%2: xl.Range('A'+`i+1`+':'+numToAlpha[len(vars)-1]+`i+1`).Select() xl.Selection.Interior.ColorIndex = 35 xl.Selection.Interior.Pattern = xlLightUp xl.Selection.Interior.PatternColorIndex = xlAutomatic xl.Range(numToAlpha[len(vars)]+'2').Select() xl.Columns("A:ZZ").EntireColumn.AutoFit() xl.ActiveWindow.Zoom = 200 xl.WindowState = xlMaximized xl.Visible = True -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of alex23 Sent: Friday, June 10, 2005 12:04 AM To: python-list at python.org Subject: Re: how to operate the excel by python? ???????? wrote: > i want to compare the content in excel,but i don't know whick module > to use! can you help me? I noticed a package on PyPi today that might be useful to you: http://www.python.org/pypi/xlrd/0.3a1 The homepage is a little brief, so I clipped their example from the README: import xlrd book = xlrd.open_workbook("myfile.xls") print "The number of worksheets is", book.nsheets print "Worksheet name(s):", book.sheet_names() sh = book.sheet_by_index(0) print sh.name, sh.nrows, sh.ncols print "Cell D30 is", sh.cell_value(rowx=29, colx=3) for rx in range(sh.nrows): print sh.row(rx) I haven't had cause to use it myself, however. -alex23 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list From jrastrick at student.usyd.edu.au Mon Jun 20 18:32:46 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 20 Jun 2005 15:32:46 -0700 Subject: reading a list from a file In-Reply-To: <1119305164.006906.133590@z14g2000cwz.googlegroups.com> References: <223874235.UzX6FoQtyG@teancum> <1119305164.006906.133590@z14g2000cwz.googlegroups.com> Message-ID: <1119306766.673306.220350@z14g2000cwz.googlegroups.com> If you decide to steer clear of eval, the following comes close to what you want, and is somewhat Pythonic (I feel): def back_to_list(str): return str.strip("[]").split(", ") >>> s = "[1, 2, 3, 4, 5, 6]" >>> back_to_list(s) ['1', '2', '3', '4', '5', '6'] So parsing the list structure is pretty easy. The problem is the list elements are still in string form. If they're only integers like in this example, you're fine. If they're arbitrary objects, on the other hand, well then you may need eval after all. Question is, how did they get printed to a file in this form in the first place? From devlai at gmail.com Thu Jun 30 17:09:37 2005 From: devlai at gmail.com (Devan L) Date: 30 Jun 2005 14:09:37 -0700 Subject: class attribute to instance attribute In-Reply-To: References: Message-ID: <1120165777.941654.13390@f14g2000cwb.googlegroups.com> Why make it an instance attribute? Couldn't you just look at the class attribute? If its something that depends on each instance's value assigned to the attribute, why not make it an instance attribute to start with? From news at NOwillmcguganSPAM.com Sun Jun 12 11:46:44 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Sun, 12 Jun 2005 16:46:44 +0100 Subject: how to startup the default web browser to open a url? In-Reply-To: References: Message-ID: <42ac58e4$0$16465$db0fefd9@news.zen.co.uk> flyaflya wrote: > I want to startup the default web browser(ie...) to open a url, "execl" > can open a process, but when the process exit, the other process will > exit too, has any why to deal this problem? You want the 'webbrowser' module. http://docs.python.org/lib/module-webbrowser.html Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From tjreedy at udel.edu Sun Jun 12 14:03:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 12 Jun 2005 14:03:24 -0400 Subject: Controlling a generator the pythonic way References: <863bro4o9h.fsf@guru.mired.org> Message-ID: "news:863bro4o9h.fsf at guru.mired.org... > Thomas Lotze writes: >> A related problem is skipping whitespace. Sometimes you don't care about >> whitespace tokens, sometimes you do. Using generators, you can either >> set >> a state variable, say on the object the generator is an attribute of, >> before each call that requires a deviation from the default, or you can >> have a second generator for filtering the output of the first. Again, >> both >> solutions are ugly (the second more so than the first). Given an application that *only* wanted non-white tokens, or tokens meeting any other condition, filtering is, to me, exactly the right thing to do and not ugly at all. See itertools or roll your own. Given an application that intermittently wanted to skip over non-white tokens, I would use a *function*, not a second generator, that filtered the first when, and only when, that was wanted. Given next_tok, the next method of a token generator, this is simply def next_nonwhite(): ret = next_tok() while not iswhte(ret): ret = next_tok() return ret A generic method of sending data to a generator on the fly, without making it an attribute of a class, is to give the generator function a mutable parameter, a list, dict, or instance, which you mutate from outside as desired to change the operation of the generator. The pair of statements val = gen.next() can, of course, be wrapped in various possible gennext(args) functions at the cost of an additional function call. Terry J. Reedy From daniel.dittmar at sap.corp Tue Jun 28 05:24:31 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 28 Jun 2005 11:24:31 +0200 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: BORT wrote: > I told my son, who wants to learn how to compute probabilities, that we > have to start with some boring stuff so we can learn how to do the cool > stuff. Adding and subtracting aren't really fun, but figuring odds on > rolling dice IS fun. Learning to program will be kind of like that. > He accepted that explantion. I'm not sure that you actually have to start with the boring stuff. Imagine that you have a small, but complete program that executes some random function a thousand times and plots the distribution. Your son could probably * start to change parameters to the function * try out the different distributions in the library * combine them to form new distributions (e.g. roll two n-sided dice) * build more complex simulations (pit two Dungeons&Dragons fighters against each other by rolling simulated dice) It's a bit more work for you as you'll have to decide on each step how much of the infrastructure you implement without taking away all the challenges. Python vs. FORTH: what you learn from Python is more easily transferred to other programming languages. And if you happend to speak German, there is "Python f?r Kids" Daniel From walter at livinglogic.de Fri Jun 10 06:48:05 2005 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Fri, 10 Jun 2005 12:48:05 +0200 Subject: Generating HTML from python In-Reply-To: <1118342111.655843.85940@o13g2000cwo.googlegroups.com> References: <1118342111.655843.85940@o13g2000cwo.googlegroups.com> Message-ID: <42A96FE5.2070505@livinglogic.de> Cappy2112 wrote: > I looked at HTMLGen a while ago- I didn't see what the advantage was. > I wrote soem code similar to the example above, to generate a page.. > It worked out fine. > > However, I want to add HTML ouput to many of my other python programs, > and I don't want to re-write this for each program. So some higher > level of abastraction is needed, but I don't know how just yet. > > HTMLGen is no longer maintained, so I don't know what the best choice > is. If you want an alternative to HTMLGen that is still maintained, you might want to try XIST (http://www.livinglogic.de/Python/xist) A few simple examples can be found here: http://www.livinglogic.de/Python/xist/Examples.html Bye, Walter D?rwald From steven.bethard at gmail.com Mon Jun 6 14:13:05 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 06 Jun 2005 12:13:05 -0600 Subject: maybe a bug in python In-Reply-To: References: Message-ID: venkata subramanian wrote: > If you have any doubts, > try to remeber this when creating tuples, > > if a tuple is to have 0 elements, > then it must be given as a=() > in other words, the ( and the ) are essential > > if it has one element, > then a comma after that element is essential > a=1, > or alternatively > a=(1,) > in other words, an end comma is essential but the parentheses are not > > if it has more than one element, comma between the elements is only essential > a=1,2 > or alternatively > a=1,2, > or alternatively > a=(1,2) That actually looks like a pretty good summary. I've posted it, with a few elaborations at: http://wiki.python.org/moin/TupleSyntax STeVe From zanesdad at bellsouth.net Tue Jun 14 07:25:53 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Tue, 14 Jun 2005 07:25:53 -0400 Subject: collect data using threads In-Reply-To: <42AEA603.5030903@gmail.com> References: <42AEA603.5030903@gmail.com> Message-ID: <42AEBEC1.6050803@bellsouth.net> Qiangning Hong wrote: >A class Collector, it spawns several threads to read from serial port. >Collector.get_data() will get all the data they have read since last >call. Who can tell me whether my implementation correct? > >class Collector(object): > def __init__(self): > self.data = [] > spawn_work_bees(callback=self.on_received) > > def on_received(self, a_piece_of_data): > """This callback is executed in work bee threads!""" > self.data.append(a_piece_of_data) > > def get_data(self): > x = self.data > self.data = [] > return x > >I am not very sure about the get_data() method. Will it cause data lose >if there is a thread is appending data to self.data at the same time? > >Is there a more pythonic/standard recipe to collect thread data? > > > This looks a little scary. If a thread is putting something in self.data (in the on_received() method) when someone else is getting something out (in the get_data() method), the data that is put into self.data could conceivably be lost because you are pointing self.data to an empty list each time get_data() is called and the list that self.data was pointing to when on_received() was called may just be dangling. Why not use the Queue from the Queue module? You can push stuff in from one side and (have as many threads pushing stuff onto it as you like) and pull stuff off from the other side (again, you can have as many consumers as you'd like as well) in a thread safe manner. HTH, Jeremy Jones From fairwinds at eastlink.ca Sun Jun 5 14:05:54 2005 From: fairwinds at eastlink.ca (David Pratt) Date: Sun, 05 Jun 2005 15:05:54 -0300 Subject: Iterate through a list calling functions In-Reply-To: <1117993793.371018.200280@g47g2000cwa.googlegroups.com> Message-ID: <7566774E-D5EC-11D9-BFBC-000A27B3B070@eastlink.ca> Cool! Many thanks George. Yes this is the way to go - objects. Much better :-) On Sunday, June 5, 2005, at 02:49 PM, George Sakkis wrote: > David Pratt wrote: >> Hi. I am creating methods for form validation. Each validator has its >> own method and there quite a number of these. For each field, I want >> to evaluate errors using one or more validators so I want to execute >> the appropriate validator methods from those available. I am >> iterating >> over each validator using validateField method to gather my results. >> It >> works but it ugly and inefficient. Can someone advise whether there >> is >> a better way of doing this. I realize that the validator variable in >> my iteration is only a string so question is how can I make the >> validator string reference a function so I may be able to shorten >> validateField to something similar to this (instead of my long list of >> ifs which I am not very happy with): >> >> for validator in validators_list: >> result = validator(name, value) >> if type (result) in StringTypes: >> results[name] = result >> >> Many thanks >> David >> >> My current situation below: >> >> # A large list of validators >> def isDecimal(name, value): >> """ Test whether numeric value is a decimal """ >> result = validateRegex(name, >> value, >> r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', >> errmsg='is not a decimal number.', >> ignore=None) >> return result >> >> def isZipCode(name, value): >> """ Tests if field value is a US Zip Code """ >> result = validateRegex(name, >> value, >> r'^(\d{5}|\d{9})$', >> errmsg='is not a valid zip code.', >> ignore=None) >> return result >> >> ... more validators >> >> # Iterating over validators to gather field errors >> def validateField(name, value, validators_list, range=None, >> valid_values=None): >> """ Validates field input """ >> results={} >> for validator in validators_list: >> if validator == 'isContainedIn': >> result = isContainedIn(name, value) >> if type (result) in StringTypes: >> more... >> if validator == 'isDate': >> result = isDate(name, value) >> if type (result) in StringTypes: >> more... >> if validator == 'isDecimal': >> result = isDecimal(name, value) >> if type (result) in StringTypes: >> more... >> >> more validators ... > > > That's a typical case for using an OO approach; just make a class for > each validator and have a single polymorphic validate method (I would > make validators __call__able instead of naming the method 'validate'): > > # Abstract Validator class; not strictly necessary but good for > documentation > class Validator(object): > def __call__(self,field,value): > '''Validate a value for this field. > Return a string representation of value on success, or None on > failure. > ''' > raise NotImplementedError("Abstract method") > > > class DecimalValidator(Validator): > def __call__(self,name,value): > '''Test whether numeric value is a decimal.''' > > class ZipCodeValidator(Validator): > def __call__(self,name,value): > '''Test if value is a US Zip Code.''' > > > def validateField(name, value, validators): > """ Validates field input """ > results = {} > for validate in validators: > result = validate(name,value) > if result is not None: > results[name] = result > # XXX: if more than one validators succeed, > # all but the last result will be overwritten > return results > > # test > validators = [DecimalValidator(), ZipCodeValidator()] > print validateField("home ZIP", "94303", validators) > > Regards, > George > > -- > http://mail.python.org/mailman/listinfo/python-list > From kveretennicov at gmail.com Sat Jun 25 11:16:41 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 25 Jun 2005 17:16:41 +0200 Subject: super problem In-Reply-To: References: Message-ID: <4660fe300506250816216f7360@mail.gmail.com> On 6/25/05, Uwe Mayer wrote: > AFAIK super only works with new-style classes, so I checked: > > >>> from qtcanvas import * > >>> isinstance(QCanvasItem, object) > True AFAIK, this is not the right way to check for new-styledness: >>> class X: "i'm an old-styler" >>> isinstance(X(), object) True But this is: >>> isinstance(X, type) False - kv From onurb at xiludom.gro Wed Jun 29 04:46:05 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 29 Jun 2005 10:46:05 +0200 Subject: Newbie: Help Figger Out My Problem In-Reply-To: <1120017061.447691.255360@f14g2000cwb.googlegroups.com> References: <1119943410.818198.296170@o13g2000cwo.googlegroups.com> <42c174ab$1@nntp0.pdx.net> <1119987053.884256.211190@g49g2000cwa.googlegroups.com> <1120017061.447691.255360@f14g2000cwb.googlegroups.com> Message-ID: <42c25fd0$0$11514$626a14ce@news.free.fr> ChuckDubya at gmail.com wrote: > Thanks to all who replied. I did not ask for other iterations of my > program. I asked what was wrong with it. Please understand that usenet is not a commercial support service. Everyone is free to answer how he likes. Or not to answer at all... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gsakkis at rutgers.edu Fri Jun 24 13:34:30 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 24 Jun 2005 10:34:30 -0700 Subject: Favorite non-python language trick? References: Message-ID: <1119634470.180697.212260@f14g2000cwb.googlegroups.com> "Joseph Garvin" wrote: > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? Although it's an optimization rather than language trick, I like the inline functions/methods in C++. There has been a thread on that in the past (http://tinyurl.com/8ljv5) and most consider it as useless and/or very hard to implement in python without major changes in the language (mainly because it would introduce 'compile-time' lookup of callables instead of runtime, as it is now). Still it might be useful to have for time-critical situations, assuming that other optimization solutions (psyco, pyrex, weave) are not applicable. George From steve at REMOVETHIScyber.com.au Sat Jun 25 14:08:49 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 04:08:49 +1000 Subject: Favorite non-python language trick? References: <1119648577.754818.119530@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 24 Jun 2005 14:29:37 -0700, James wrote: > Interesting thread ... > > 1.) Language support for ranges as in Ada/Pascal/Ruby > 1..10 rather than range(1, 10) What advantages do Pascal-like for loops give over Python for loops? The only two I can think of are trivial: (1) the Pascal-like for loop is six characters shorter to type: for i = 1 to 10: # 16 chars for i in range(1, 10): # 22 chars (2) for very large ranges, you don't have to hold the entire list of integers in memory. But you can use xrange() instead of range(), which also doesn't hold the entire list in memory. > 2.) Contracts Explain please. > 3.) With Explain please. -- Steven. From david.bear at asu.edu Fri Jun 24 18:11:14 2005 From: david.bear at asu.edu (David Bear) Date: Fri, 24 Jun 2005 15:11:14 -0700 Subject: a dictionary from a list Message-ID: <2133494.bAtaJnSUkF@teancum> I know there must be a better way to phrase this so google understands, but I don't know how.. So I'll ask people. Assume I have a list object called 'alist'. Is there an easy way to create a dictionary object with the members of 'alist' being the keys in the dictionary, and the value of the keys set to null? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From grante at visi.com Wed Jun 1 00:16:01 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 01 Jun 2005 04:16:01 -0000 Subject: Rss lib in python? References: Message-ID: <119qdk1cmtmi70@corp.supernews.com> On 2005-06-01, Owen wrote: > i want to know some rss library in python.For example, some > for rss readers, and some for generator. http://www.learnwebskills.com/search/main.html http://www.learnwebskills.com/search/google.html Googling for "python rss library" generate a whole page full of useful looking stuff: http://www.google.com/search?q=python+rss+library Here's an RSS aggregator written in Python: http://offog.org/code/rawdog.html -- Grant Edwards grante Yow! HOW could a GLASS at be YELLING?? visi.com From grante at visi.com Tue Jun 28 23:18:25 2005 From: grante at visi.com (Grant Edwards) Date: Wed, 29 Jun 2005 03:18:25 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> Message-ID: <11c44o1cmmmr791@corp.supernews.com> On 2005-06-29, Erik Max Francis wrote: >> The problem which a lot of fairly-midstream American accent users face >> is that it's the same sort of thing which Brits try and imitate when >> they want to suggest a snake-oil salesman. > > And due to overcorrection, typically do a really bad job of it :-). That reminds me of a character in one of the old Dr. Who series. I thought this character had some sort of speach impediment. After a few episodes I caught a few cultural allusions made by the character and it finally dawned on me the the character was supposed to be an _American_. I assume that when I try to speak with a British accent I sound just as bad to a Brit. -- Grant Edwards grante Yow! Why is everything at made of Lycra Spandex? visi.com From jabel at plus.net Thu Jun 9 09:53:32 2005 From: jabel at plus.net (John Abel) Date: Thu, 09 Jun 2005 14:53:32 +0100 Subject: Simple SMTP server In-Reply-To: <4222a8490506090644442aa67d@mail.gmail.com> References: <4222a8490506090644442aa67d@mail.gmail.com> Message-ID: <42A849DC.9060003@plus.net> Jesse Noller wrote: >Hello - > >I am looking at implementing a simple SMTP server in python - I know >about the smtpd module, but I am looking for code examples/snippets as >the documentation is sparse. > >The server I am looking at writing is really simple - it just needs to >fork/thread appropriately for handling large batches of email, and all >it has to do is write the incoming emails to the disk (no >relaying/proxying/etc). > >If anyone has any good examples/recipes I'd greatly appreciate it. > >Thanks > >-jesse > > twisted.mail for a starting point, or Quotient which is an SMTP Server based on twisted.mail. J From steven.bethard at gmail.com Wed Jun 29 20:02:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Jun 2005 18:02:06 -0600 Subject: Inheriting from object In-Reply-To: <1120081591.319266.10200@z14g2000cwz.googlegroups.com> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> <42c30ea5$0$31301$636a15ce@news.free.fr> <1120081591.319266.10200@z14g2000cwz.googlegroups.com> Message-ID: Fuzzyman wrote: > Surely when they are removed : > > class foo: > pass > > won't become invalid syntax, it will just automatically inherit from > object ? Well, Guido views this particular syntax as an "oopsie"[1]. It should actually look like: class C(): pass Guido also suggests that the explicit: class C(object): pass is "much preferred"[2] over: __metaclass__ = type class C: pass when creating new-style classes. It's not exactly clear where Guido comes down on your particular issue, but if I had to guess, I would guess that he prefers the explicit reference to "object". STeVe [1]http://mail.python.org/pipermail/python-dev/2005-February/051706.html [2]http://mail.python.org/pipermail/python-dev/2005-February/051711.html From robin at reportlab.com Tue Jun 14 05:59:01 2005 From: robin at reportlab.com (Robin Becker) Date: Tue, 14 Jun 2005 10:59:01 +0100 Subject: subprocess module and blocking In-Reply-To: References: <42ABFEEC.3010505@jessikat.fsnet.co.uk> Message-ID: <42AEAA65.3020608@chamonix.reportlab.co.uk> Dieter Maurer wrote: ..... > > You just found out that this is not the case. thanks I suppose I was being a moron. > > The warning attached to "communicate"s docstring might have > you averted: "Note: the data read is buffered in memory... > do not use for large size". > > If subprocess would do what you expect, it would need to > buffer the output (to make room in the pipes again). > But, for large data, this could have dramatic consequences. > > Thus, you should use "select" on the pipes to find out > when to read data. > Unfortunately select isn't an option for windows (I think that's only for sockets). I guess I need to read repeatedly from the stdout etc to get the output. Clearly the poll call can't return a status until we've finished reading. > > Dieter -- Robin Becker From support.services.complaints at gmail.com Sun Jun 12 04:02:16 2005 From: support.services.complaints at gmail.com (MyHaz) Date: 12 Jun 2005 01:02:16 -0700 Subject: Streaming Data Error in .read() (HTTP/ICY) Possible Bug? Message-ID: <1118563336.633159.38290@z14g2000cwz.googlegroups.com> I playing around with streaming shoutcast mp3s. Here is some sample code: ----------------------- import httplib ############ # Put together the headers headers = {"Icy-MetaData":"1"} con = httplib.HTTPConnection('64.142.8.154', 8000) con.request("GET", "/") stream = con.getresponse() print stream.status,stream.reason print stream.read() ----------------------- For which i get error: bash-2.05b$ ./woxy_saver.py 200 Traceback (most recent call last): File "./woxy_saver.py", line 21, in ? print stream.read() File "C:\python24\lib\httplib.py", line 463, in read s = self._safe_read(self.length) File "C:\python24\lib\httplib.py", line 545, in _safe_read chunk = self.fp.read(amt) File "C:\python24\lib\httplib.py", line 1273, in read return s + self._file.read(amt - len(s)) TypeError: unsupported operand type(s) for -: 'str' and 'int' bash-2.05b$ It seems somehow amt is turning into a str. Is this a bug in httplib.py or there something wrong with my code? Cheers - Haz From sarir.khamsi at raytheon.com Thu Jun 9 16:53:59 2005 From: sarir.khamsi at raytheon.com (Sarir Khamsi) Date: Thu, 09 Jun 2005 13:53:59 -0700 Subject: Interpreter-like help in cmd.Cmd Message-ID: Is there a way to get help the way you get it from the Python interpreter (eg, 'help(dir)' gives help on the 'dir' command) in the module cmd.Cmd? I know how to add commands and help text to cmd.Cmd but I would also like to get the man-page-like help for classes and functions. Does anyone know how to do that? Thanks. Sarir From nephish at xit.net Sat Jun 11 18:47:03 2005 From: nephish at xit.net (nephish at xit.net) Date: 11 Jun 2005 15:47:03 -0700 Subject: cgi script runs under Opera, but not firefox In-Reply-To: <867jh04pe6.fsf@guru.mired.org> References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> <1118501642.065924.83560@z14g2000cwz.googlegroups.com> <1118505371.230328.231880@o13g2000cwo.googlegroups.com> <6d8ma1lvfer5itr6ukomg095uprnp30ujd@4ax.com> <1118516629.651991.134730@g47g2000cwa.googlegroups.com> <867jh04pe6.fsf@guru.mired.org> Message-ID: <1118530023.093249.184150@g43g2000cwa.googlegroups.com> Great Advice, can see that saving me a few headaches thanks From mwm at mired.org Wed Jun 29 21:51:47 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 29 Jun 2005 21:51:47 -0400 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: <86br5opq6k.fsf@bhuda.mired.org> Rocco Moretti writes: > Except that (please correct me if I'm wrong) there is somewhat of a > policy for not including interface code for third party programs which > are not part of the operating system. (I.e. the modules in the > standard libary should all be usable for anyone with a default OS + > Python install.) > > A notable exception is the dbm modules, but I seem to recall hearing > that the official position is that it was a mistake. (Now only kept > for backward compatability.) Um - dbm is bundled with both os's I use (FreeBSD and OS X). I'd be surprised if some variant or another didn't come standard on most Linux systems as well. Not all builtin functions are available on all os's. And the source tree certainly includes modules that are specific to a single operating systems (just look in the PC and Mac directories). I'm pretty sure there are other modules that aren't supported on various oddball systems - like termios. Why should a module that's usable out-of-the-box on a fair variety of systems be excluded just because it's not usable on all platforms? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Fri Jun 3 05:24:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Jun 2005 05:24:40 -0400 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117649990.028395.116640@f14g2000cwb.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> <1117649990.028395.116640@f14g2000cwb.googlegroups.com> Message-ID: infidel wrote: > Ok, forget everything I've said. The more I think about this the less > I understand it. I'm way out of my league here. > > sitting-down-and-shutting-up-ly y'rs, > > Well, that's a sign of maturity right there ;-) some-people-just-don't-know-when-to-ly y'rs - steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From benedict.verheyen at sjki.be Fri Jun 24 09:35:52 2005 From: benedict.verheyen at sjki.be (Benedict Verheyen) Date: Fri, 24 Jun 2005 13:35:52 GMT Subject: webserver application (via Twisted?) In-Reply-To: References: Message-ID: flupke wrote: Thanks Peter & Radovan for the answers Regards, Benedict -- Benedict Verheyen Debian User http://www.heimdallitservices.be Public Key 0x712CBB8D From cpu.crazy at gmail.com Mon Jun 6 16:09:10 2005 From: cpu.crazy at gmail.com (CPUFreak91) Date: 6 Jun 2005 13:09:10 -0700 Subject: Looking for Image, Audio and Internet/Web HOTWO's or tutorials In-Reply-To: <1117766483.074108.140200@g47g2000cwa.googlegroups.com> References: <1117735244.363447.10340@f14g2000cwb.googlegroups.com> <1117766483.074108.140200@g47g2000cwa.googlegroups.com> Message-ID: <1118088550.358105.71380@g49g2000cwa.googlegroups.com> thanks. It's a huuuge list From kay.schluehr at gmx.net Sat Jun 11 00:27:11 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 Jun 2005 21:27:11 -0700 Subject: Abstract and concrete syntax In-Reply-To: References: <1118411839.922816.94730@g43g2000cwa.googlegroups.com> Message-ID: <1118464031.005618.147230@g43g2000cwa.googlegroups.com> Terry Reedy wrote: > > lambda x: {True:2,False:3}.get(bool(a)) > > This is limited by the requirement that both branches be computable > regardless of the value of the condition. > > > which is both beautiful and pythonic. > > Beauty is in the eye of the beholder. It seems that relative pythonicity > sometimes is also ;-). That's what is really regrettable! Otherwise a creation of a "lazy dict" that creates the value part of an item on demand would have been reasonable to solve both the computational issue you mentioned and the performance issue George worried about ( you are both right except for the little example above :) Kay From qscomputing at gmail.com Thu Jun 2 12:10:50 2005 From: qscomputing at gmail.com (qscomputing at gmail.com) Date: 2 Jun 2005 09:10:50 -0700 Subject: Two questions In-Reply-To: <3g8kqaFb5v3dU2@individual.net> References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> <3g8kqaFb5v3dU2@individual.net> Message-ID: <1117728650.316100.291750@g14g2000cwa.googlegroups.com> Thanks to you all for the quick response. I've noticed that when I do $ python myprog.py the file myprog.pyc file is not created, but the .pyc files for files I import *are* created. Is this intentional and, if so, how do I get the myprog.pyc file? Thanks, - QS Computing. From mrmaple at gmail.com Sat Jun 18 23:35:34 2005 From: mrmaple at gmail.com (James Carroll) Date: Sat, 18 Jun 2005 23:35:34 -0400 Subject: Extensions on Linux: import without underscore? Message-ID: Hi, I'm creating an extension called _bright.so on linux. I can import it with import _bright, but how can I import bright and get the package? On windows, I've been able to import bright instead of import _bright, but on Linux it seems to need the underscore. I'm tempted to create a bright.py with from _bright import *, but I'm wondering if there's a more direct way. Also, I'm using scons to generate my lib, and it insists on prepending the characters lib to my library name, so if I tell it to generate _bright.so it gives me lib_bright.so. Is there a way of turning this off so I don't have to rename it back to _bright.so? Thanks, -Jim From ledruker at rogers.com Tue Jun 14 14:31:42 2005 From: ledruker at rogers.com (Eugene Druker) Date: Tue, 14 Jun 2005 14:31:42 -0400 Subject: Tough Scrolling question with Tkinter References: <1118764727.767060.189130@o13g2000cwo.googlegroups.com> Message-ID: <2ZmdnawksP1xvzLfRVn-rQ@rogers.com> Hi Saqib, AFAIU, you want to change the scrollregion, not the size. So try: def _b1PressEvt(event): x0,y0,x1,y1 = canvas.config('scrollregion')[4] print x0,y0,x1,y1 canvas.config(scrollregion=(int(x0),int(y0),int(x1)+100,int(y1))) First click will show nothing, because first change keeps the scrollregion entirely in the window. Eugene wrote in message news:1118764727.767060.189130 at o13g2000cwo.googlegroups.com... > Please take a look at and run the code snippet shown below. > > It creates a canvas with vertical & Horizontal scroll-bars. > If you shrink the window to smaller than the area of the canvas, the > scroll-bars work as advertised. That's great. > > However, if you click the Left Mouse button, it calls code which > expands the width of the canvas by 100 pixels. The area being viewed > expands correspondingly..... BUT I DON'T WANT IT TO!! > > I want to know how to expand the size of a canvas without changing the > area/size of what is currently shown by the scroll bars. I would like > to find code that expands the width of the canvas and simply adjusts > the H-Scrollbar without changing what is shown on in the area of the > canvas being displayed. > > I have tried seemingly every combination of messing with the > canvas.config and scrollregion parameters to no avail. Can someone out > there show me how its done?? > > -Saqib > > ----------------------------------------- > import Tkinter > > def _b1PressEvt(event): > print "B1" > _canvas.config(width=300) > > tkRoot = Tkinter.Tk() > _canvas = Tkinter.Canvas(tkRoot, background="white", width=200, > height=200,) > > # Scroll Bars > vScrollbar = Tkinter.Scrollbar(tkRoot) > vScrollbar.pack(side=Tkinter.RIGHT, expand=True, fill=Tkinter.Y) > > hScrollbar = Tkinter.Scrollbar(tkRoot) > hScrollbar.pack(side=Tkinter.BOTTOM, expand=True, fill=Tkinter.X) > > _canvas.config( > width=200, > height=200, > scrollregion=(0,0,100,100), > yscrollcommand=vScrollbar.set, > xscrollcommand=hScrollbar.set, > ) > > vScrollbar.config(orient=Tkinter.VERTICAL, command=_canvas.yview) > hScrollbar.config(orient=Tkinter.HORIZONTAL, command=_canvas.xview) > > #tkRoot.pack() > _canvas.pack(expand=Tkinter.NO) > vScrollbar.pack(side=Tkinter.RIGHT, expand=True, fill=Tkinter.Y) > hScrollbar.pack(side=Tkinter.BOTTOM, expand=True, fill=Tkinter.X) > > # Function Bindings > _canvas.bind("", _b1PressEvt) > > tkRoot.mainloop() > From d at e.f Sun Jun 19 22:10:16 2005 From: d at e.f (D H) Date: Sun, 19 Jun 2005 21:10:16 -0500 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > D H wrote: >> So you say he "has done relatively little serious development" and >> that he may not even know about Python. I didn't see any evidence >> from those pages to draw either conclusion. In fact the 4th paragraph >> quite contradicts them both. > > > Clearly this is a matter of opinion. You're kidding right? Did you even read the about page you cited? The guy has been doing C++ development for decades, he wrote a book on it, and yet you say he has done "little serious development"??? That's absurd. And he was the president of ACCU, which if you look on the ACCU page at the very top is a mention of Python. And yet you suggested that he hasn't even heard of Python before. Again, absurd. From listserver at tdw.net Fri Jun 10 08:53:35 2005 From: listserver at tdw.net (Tim Williams) Date: Fri, 10 Jun 2005 13:53:35 +0100 Subject: howto send html mails using smtplib Message-ID: <004101c56dbb$6a2cf3d0$ccbefea9@twilliams> "Philippe C. Martin" wrote in message news:sD3qe.2270$751.1207 at newssvr30.news.prodigy.com... > I have the following problem: > 1) I can use smtplib to send text messages > 2) I can generate html > 3) I want to email the html and want it to be seen by the email client as > html. > > However, when I receive the message, the email client displays it as text > (code hereunder) - I assume it has to do with the MIMEText call but since I > cannot see any MIMEhtml ..... I suspect you need one of the following lines. msg.replace_header('Content-Type', 'text/html') msg.add_header('Content-Type', 'text/html') HTH :) -- ================================= Tim Williams From roy at panix.com Thu Jun 30 21:31:37 2005 From: roy at panix.com (Roy Smith) Date: Thu, 30 Jun 2005 21:31:37 -0400 Subject: map vs. list-comprehension References: <87irzxtqsp.fsf@lucien.dreaming> <42c4068c$0$21964$afc38c87@news.optusnet.com.au> Message-ID: Terry Hancock wrote: > One of the strengths of Python has been that the language itself is > small (which it shares with C and (if I understand correctly, not being > a lisp programmer?) Lisp), but with all the syntax enhancements going > on, Python is getting pretty complicated. I have to wonder if new users > won't begin to find it just as intimidating as Perl or other big > languages. +1 Even some of the relatively recent library enhancements have been kind of complicated. The logging module, for example, seems way over the top. Look at what happened to C when it mutated into C++. In isolation, most of the features of C++ seem like good ideas. Taken together, it's a huge hairy mess that most people only understand increasingly larger subsets of. Fred Brooks called it the second system syndrome. From bogus@does.not.exist.com Thu Jun 30 09:55:02 2005 From: bogus@does.not.exist.com () Date: Thu, 30 Jun 2005 13:55:02 -0000 Subject: No subject Message-ID: #! rnews 2572 Newsgroups: comp.lang.python Path: news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!news-spur1.maxwell.syr.edu!news.maxwell.syr.edu!nntp.abs.net!attws2!ip.att.net!NetNews1!xyzzy!nntp From: Harry George Subject: Re: Modules for inclusion in standard library? X-Nntp-Posting-Host: cola2.ca.boeing.com Content-Type: text/plain; charset=us-ascii Message-ID: User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.4 Lines: 39 Sender: hgg9140 at cola2.ca.boeing.com Organization: The Boeing Company References: <3ian37Fkjle0U1 at individual.net> <11c343ho6i6hv17 at news.supernews.com> <1x6lpi6z.fsf at python.net> <7xwtodvzsv.fsf at ruckus.brouhaha.com> <7x3br1ger1.fsf at ruckus.brouhaha.com> Mime-Version: 1.0 Date: Thu, 30 Jun 2005 13:38:28 GMT Xref: news.xs4all.nl comp.lang.python:384160 Paul Rubin writes: > Rocco Moretti writes: > > Except that (please correct me if I'm wrong) there is somewhat of a > > policy for not including interface code for third party programs which > > are not part of the operating system. (I.e. the modules in the > > standard libary should all be usable for anyone with a default OS + > > Python install.) > > I've never heard of Python having such a policy and I don't understand > how such a stupid policy could be considered compatible with a > proclaimed "batteries included" philosophy. Why would Python > advocates want to make Python deliberately uncompetitive with PHP, > Java, and other languages that do include database modules? > > > A notable exception is the dbm modules, but I seem to recall hearing > > that the official position is that it was a mistake. (Now only kept > > for backward compatability.) > > Ahem: Tkinter. There's actually several more, looking in the lib docs. I typically install dozens of python packages (on IRIX, Solaris, AIX, Linux, Win2K). 21 are standalone enough to be considered for the std library. However I wouldn't necessarily want them in there, because: a) They have their own release cycles, and coordinating would be too painful. We'd get a Python-1.2.3 with a package ABC-2.3.4 which is (too late) discovered to have a bug. So everyone would have to download ABC-2.3.5 and install it anyway. b) Installing distutils-aware python packages is trivial. I'd rather the energy which might go into a bigger std library go instead into helping projects which don't have distutils-style builds. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From agriff at tin.it Tue Jun 21 19:27:32 2005 From: agriff at tin.it (Andrea Griffini) Date: Tue, 21 Jun 2005 23:27:32 GMT Subject: references/addrresses in imperative languages References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> <89jeb1ddsjsaq0l07j0vonehqlah3cq9ce@4ax.com> <1119335440.863575.24360@g14g2000cwa.googlegroups.com> Message-ID: On 20 Jun 2005 23:30:40 -0700, "Xah Lee" wrote: >Dear Andrea Griffini, > >Thanks for explaning this tricky underneath stuff. Actually it's the very logical consequence of the most basic rule about python. Variables are just pointers to values; so every time you assign to a variable you're always changing just that pointer, you're not touching the object pointed to by the variable. Even when x is pointing to an integer with x=x+1 you are computing a new integer (x+1) and making x to point to this new one instead of the old one. You are NOT touching the old integer. Surely this is different from C/C++/Java, but it's IMO all but tricky or underneath. Andrea From gdub at ece.utexas.edu Wed Jun 8 11:34:38 2005 From: gdub at ece.utexas.edu (Gary Wilson Jr) Date: Wed, 08 Jun 2005 10:34:38 -0500 Subject: __init__.py in packages Message-ID: <42A7100E.7070900@ece.utexas.edu> I'm creating a python package foo. What is intended use for __init__.py files? Well, I found this: http://www.python.org/doc/essays/packages.html >From what I can gather it is for initialization of the package when doing an import, but I would really like to see an example or situation that makes good use of the __init__.py file. Looking at the distutils __init__.py file, it only defines things like __version__. However, looking at the logging __init__.py file, it is a 1196-line monster with functions and classes defined throughout. What is the RightThing? Should I only define things in __init__.py that need to be defined when importing a subpackage and/or module of package foo? Is it ok for me to define classes in foo/__init__.py? Whereby I could do something like: from foo import MyClass Or is is better if I were to put these classes and/or functions in foo/core.py? Whereby I would do something like: from foo.core import MyClass From nyamatongwe+thunder at gmail.com Sat Jun 4 17:59:17 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 04 Jun 2005 21:59:17 GMT Subject: using boost to return list In-Reply-To: <1117909185.573323.80670@f14g2000cwb.googlegroups.com> References: <1117909185.573323.80670@f14g2000cwb.googlegroups.com> Message-ID: GujuBoy: > i am trying to make a "cpp" file which will make an array and pass it > to python as a list. > > how is this possible...i am using BOOST...please can someone point me > at some examples This returns a list when called from Python. static list retrieval_as_list(SplitText &self, int position, int retrieveLength) { list result; int *characters = new int[retrieveLength]; int lenRet = self.RetrieveUTF32(position, characters, retrieveLength); for (int i=0;i References: <429efdbf$1@griseus.its.uu.se> Message-ID: Stian S?iland wrote: > There are several ways to create a copy of a list: [snip] > a2 = list(a) # create a new list object out of any sequence I'll just point out that FWIW, this is by far my favorite idiom of the ones offered because it applies to pretty much all the builtin container types: py> d = {1:42, -37:0} py> d2 = dict(d) py> d == d2, d is d2 (True, False) py> s = set(['a', 'd', 'e']) py> s2 = set(s) py> s == s2, s is s2 (True, False) py> L = [3.14, 0.707] py> L2 = list(L) py> L == L2, L is L2 (True, False) STeVe From rbt at athop1.ath.vt.edu Mon Jun 6 16:55:52 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 06 Jun 2005 16:55:52 -0400 Subject: Destructive Windows Script In-Reply-To: <868y1n8b1d.fsf@guru.mired.org> References: <868y1n8b1d.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > "Terry Reedy" writes: > >>On *nix, one could open '/dev/rawdisk' (actual name depends on the *nix >>build) and write a tracks worth of garbage for as many tracks as there are. >>I don't how to programmaticly get the track size and number (if there is a >>standard way at all). > > > Modern Unix systems assume drives don't care much about geometry, what > with sector forwarding and variable track lengths and the like. > > Just open the raw disk device (assuming your Unix has such), and start > writing data to it. Keep going until the write fails at the end of the > media. > > <2MCdnf5cFKCCLjXfRVn-pw@powergate.ca> Message-ID: Peter Hansen writes: > class _Helper(object): > """Define the built-in 'help'. > This is a wrapper around pydoc.help (with a twist). > > """ > > def __repr__(self): > return "Type help() for interactive help, " \ > "or help(object) for help about object." > def __call__(self, *args, **kwds): > import pydoc > return pydoc.help(*args, **kwds) Thanks, but how do I integrate this with cmd.Cmd? From aahz at pythoncraft.com Sun Jun 12 20:15:19 2005 From: aahz at pythoncraft.com (Aahz) Date: Sun, 12 Jun 2005 17:15:19 -0700 Subject: OSCON: Volunteer for Python? Message-ID: <20050613001518.GA28139@panix.com> I'm trying to organize a group of people to run a Python booth at OSCON so that people will see an alternative to Perl. ;-) I'd like at least ten or twelve volunteers so that nobody has to pull a long shift. If you're interested, please subscribe to the OSCON mailing list: http://mail.python.org/mailman/listinfo/oscon -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From ggg at zzz.it Fri Jun 10 09:51:42 2005 From: ggg at zzz.it (deelan) Date: Fri, 10 Jun 2005 15:51:42 +0200 Subject: MySQLDBAPI In-Reply-To: References: <2tqln2-6c3.ln1@news.interplanet.it> Message-ID: Gregory Pi?ero wrote: > I didn't see anything about mysql-devel package in the release notes. it's there, section "Prerequisites". > Is that something I can install all to my home directory? never tried, but sounds hard to do. mysql-devel is a bunch of libs and include files tied to mysql. the "_mysql" extension will be complied against such files and then wrapped by python code. HTH. -- deelan, #1 fan of adriana lima! From jarrod.roberson at gmail.com Fri Jun 10 14:58:27 2005 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 10 Jun 2005 11:58:27 -0700 Subject: Dealing with marketing types... In-Reply-To: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <1118429907.140244.298390@g43g2000cwa.googlegroups.com> get your resume in order and start looking . . . From vinodmap at gmail.com Fri Jun 24 23:50:48 2005 From: vinodmap at gmail.com (vm) Date: 24 Jun 2005 20:50:48 -0700 Subject: http POST only returning GET data In-Reply-To: References: <1119666846.766429.68550@f14g2000cwb.googlegroups.com> Message-ID: <1119671448.447784.314000@z14g2000cwz.googlegroups.com> Benji - that worked like a champ - my mistake. thanks Vinod From renato.ramonda at gmail.com Thu Jun 9 18:03:39 2005 From: renato.ramonda at gmail.com (Renato Ramonda) Date: Fri, 10 Jun 2005 00:03:39 +0200 Subject: Fast text display? In-Reply-To: <863brr6xiw.fsf@guru.mired.org> References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> <863brr6xiw.fsf@guru.mired.org> Message-ID: <%03qe.15856$TR5.781@news.edisontel.com> Mike Meyer ha scritto: > Then I can go do something useful while the package system downloads, > compiles and installs all the required software. I don't know if > Debian has a similar system for installing from source. Gentoo does if > you want to stay with Linux. Debian actually has such a mechanism, if you have deb-src repositories in your apt sources list. The real problem will come from conflicting versions of wx and/or gtk required by different (other) programs. -- Renato -------------------------------- Usi Fedora? Fai un salto da noi: http://www.fedoraitalia.org From flupke at nonexistingdomain.com Thu Jun 16 16:44:03 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 16 Jun 2005 20:44:03 GMT Subject: poker card game revisited (code included) In-Reply-To: References: <7Rcpe.112980$Ro5.6679671@phobos.telenet-ops.be> <6rqdnXqlKqN0bTjfRVn-tg@speakeasy.net> Message-ID: John Hazen wrote: > [Erik Max Francis] > >>>>Searching for straights and flushes is much better done by masks. > > > Interesting. I've been thinking about playing with this stuff too, but > hadn't considered masks. So each card has a representation: > > n bits for rank, then m bits for suit. > > 00000000000010 0001 = 2 clubs > 01000000000000 1000 = K spades > ... > > [flupke] > >>>As for straights, if i understand correctly, you make all possible >>>straights of the cards in the hand and then see if one matches? > > > Yeah, I originally thought that's what you meant, too. But if you take > the scheme above, and sort the cards before you merge them into the > hand-bits aggregate, then you can just have *one* mask for straights, > and shift it down by a bit each time you check. So the best straight > mask (A high) would be (ignoring suit bits): > > 10000000000000 01000000000000 00100000000000 00010000000000 00001000000000 > > Then this could be shifted right for a K-high straight: > > 01000000000000 00100000000000 00010000000000 00001000000000 00000100000000 > > I guess that means that an Ace has to have the following representation, > since it can be both at the high and low end of a straight: > > 10000000000001 0100 = A hearts > > But this may mess with bit-counting shortcuts for other calculations... > > This is interesting to think about. Thanks for the pointer. I'm also > going to look at pokersource, though I may put that off until I at least > partially re-invent the wheel for learning purposes. > > -John I haven't had to much time to play around with it either and i agree it's fascinating. However my code now detects high hands properly (need to do low hands too and check the wildcards some more. I really need to build a test suit) and i find it quite readable code. Why would you want to start messing with bits in python? It feels like a pure c++ approach. Check the way the straight is checked in the code posted here. It's very readable and i doubt you can make it as readable using bitmasks. I do think that bitmasks are going to be faster but i could program the hand checking stuff fairly quick something that would require a lot more work when doing the same with bitmasks. Anyway, i'm still interested in that approach and i will try it whenever i've got the time. Haven't seen a lot of python code that uses bitmasks though. Maybe the pokersource C/C++ code can be wrapped in python? :) Regards, Benedict From guettli at thomas-guettler.de Wed Jun 1 08:44:45 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 01 Jun 2005 14:44:45 +0200 Subject: ConfigParser, mapping one key to multiple values Message-ID: Hi, I need a config like this: [sync files] ignore=".*/foodir/.*\.pyc" ignore=".*/foodir/.*~" ... The ConfigParser of the standard library can't handle this, because one key maps to multiple values. Is there a simple and lightweight config parser which can handle this? Thomas PS: Needs to be compatible with Python 2.3 -- Thomas G?ttler, http://www.thomas-guettler.de/ From curi at curi.us Fri Jun 3 22:17:25 2005 From: curi at curi.us (Elliot Temple) Date: Fri, 3 Jun 2005 19:17:25 -0700 Subject: Scope In-Reply-To: References: Message-ID: On Jun 4, 2005, at 2:13 AM, Leif K-Brooks wrote: > Elliot Temple wrote: > >> I want to write a function, foo, so the following works: >> >> def main(): >> n = 4 >> foo(n) >> print n >> >> #it prints 7 >> > > What's wrong with: > > def foo(n): > return 7 > > def main(): > n = 4 > n = foo(n) > print n > > Anything else (including the tricks involving mutable objects that > will > no doubt be posted) will result in ugly, hard to maintain code. Nothing is wrong with it in this case. I just want to know if Python can do what I said. -- Elliot Temple http://www.curi.us/ --- [This E-mail scanned for viruses by Declude Virus] From p at ulmcnett.com Tue Jun 14 09:58:27 2005 From: p at ulmcnett.com (Paul McNett) Date: Tue, 14 Jun 2005 06:58:27 -0700 Subject: Single Application Instance Example In-Reply-To: References: Message-ID: <42AEE283.8080204@ulmcnett.com> Chris Lambacher wrote: > Does anyone know of an example of how to make a Python program only > run a single instance. I am specifically looking for examples for > win32. The Python Cookbook, Second Edition, page 380, recipe 9.9: Determining Whether Another Instance of a Script is Already Running in Windows, suggests using a mutex kernel object to be safe from race conditions: from win32event import CreateMutex from win32api import GetLastError from winerror import ERROR_ALREADY_EXISTS from sys import exit handle = CreateMutex(None, 1, 'A unique mutex name') if GetLastError() == ERROR_ALREADY_EXISTS: print "I exist already" exit(1) else: print "I don't exist already" > I think I should be able to do this with win32all but the method is > not obvious. Preferably I would like to be able to get a handle to > the already running instance so that I can push it to the foreground > as well. There are ways using win32 to get the handle to the existing process, but I'm too rusty with win32 to offer that part of the solution. -- Paul McNett http://paulmcnett.com From http Wed Jun 22 21:07:23 2005 From: http (Paul Rubin) Date: 22 Jun 2005 18:07:23 -0700 Subject: Looking For Geodetic Python Software References: <447po2-iqt.ln1@eskimo.tundraware.com> Message-ID: <7xmzph3mpg.fsf@ruckus.brouhaha.com> Tim Daneliuk writes: > 1) Given the latitude/longitude of two locations, compute the distance > between them. "Distance" in this case would be either the straight-line > flying distance, or the actual over-ground distance that accounts for > the earth's curvature. For spherical earth, this is easy, just treat the 2 locations as vectors whose origin is at the center of the earth and whose length is the radius of the earth. Convert the lat-long to 3-D rectangular coordinates and now the angle between the vectors is arccos(x dotproduct y). The over-ground distance is then just R*theta where theta is the angle. > 2) Given n latitude/longitude coordinates, compute the > "geocenter". That is, return the lat/long of the location that > is most "central" to all n initial coordinates. Not sure what this is. > 3) Given n lat/long coordinates, compute a Kruskal-type spanning > tree. Not sure what this is. > 4) Given n lat/long coordinates, compute an optimal (shortest or longest) > visitation path that reaches each node exactly once. Better still would > be something that had "pluggable" heuristic engines so we could try > different approaches like greedy, shortest-path, hill climbing, and > so forth. It would be even nicer if one could also simulate different > routing schemes (Monte Carlo?). This is certainly NP-hard but there are various standard TSP heuristics (the ones intended for maps with 2-d Euclidean distance may not work on spherical problems though). "Combinatorial Optimization" by Steiglitz and Papadimitriou is the standard text on this stuff. From steve at REMOVETHIScyber.com.au Mon Jun 6 11:43:34 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Tue, 07 Jun 2005 01:43:34 +1000 Subject: If - Or statements References: Message-ID: On Sun, 05 Jun 2005 13:52:09 -0400, Roy Smith wrote: > One sure sign of somebody trying to write C in Python is when they loop > over a list by doing > > for i in range (len (myList)): > doSomethingWith (myList[i]) I usually do that, and I've never coded a line of C in my life. I can't even read C :-) Of course, the main reason I use that form is that I frequently have to use older versions of Python without enumerate, and therefore have got into the practice of doing without it. Of course, if I'm just reading the items of myList, I don't bother with the index, and just use for item in myList: dosomethingwith(item) > or when they laboriously check for every possible error condition before > performing an operation instead of just doing it and catching the exception. This is not always a bad idea. For example, if you are modifying an object in place, and an error halfway through could leave the object in an inconsistent state, it may be better to check for error conditions first rather than try to back out of it after you've run into trouble. But still, in general I agree with your observation. -- Steven From martin.witte at gmail.com Thu Jun 30 14:18:46 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 30 Jun 2005 11:18:46 -0700 Subject: Scket connection to server In-Reply-To: References: Message-ID: <1120155526.675411.113540@g44g2000cwa.googlegroups.com> The documentation gives an excellent example on how to do this, see http://docs.python.org/lib/socket-example.html From mg.mailing-list at laposte.net Mon Jun 20 03:15:50 2005 From: mg.mailing-list at laposte.net (mg) Date: Mon, 20 Jun 2005 09:15:50 +0200 Subject: catch argc-argv In-Reply-To: References: Message-ID: <42B66D26.4000705@laposte.net> Wolfram Kraus wrote: >mg wrote: > > >>Hello, >> >>I am writting bindings for a FEM application. In one of my function >>'initModulename', called when the module is imported, I would like to >>get the argc and argv arguments used in the main function of Python. >>So, my question is: does the Python API containe fonctions like >>'get_argc()' and 'get_argv()' ? >> >>Thanks, >> >> >> >> >> >Use sys.argv: >http://python.org/doc/2.4.1/lib/module-sys.html > >HTH, >Wolfram > > I know this module and this function. But, I search the same function in the C-API because a would like to know these variables directly in my bindings written in C++. As an example, I try to create the following fonction : PyMODINIT_FUNC initMyModule( void ) { int argc = Py_GetArgc() ; // I don't know if this function exist : I would like to know... char** argv = Py_GetArgv() ; // I don't know if this function exist : I would like to know... myfunction( argc, argv ) ; PyObject* module = Py_InitModule3( "MyModule", 0, "module of my FEM application" ) ; } Thanks to this C function written with the C-API of Python, I will create a new Python module and import it in the Python interpreter : >>> import MyModule From donald.welch at NOSPAM.hp.com Wed Jun 29 19:07:30 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Wed, 29 Jun 2005 16:07:30 -0700 Subject: Programmers Contest: Fit pictures on a page References: <1120055349.188697.133510@z14g2000cwz.googlegroups.com> <1120081362.325830.111020@z14g2000cwz.googlegroups.com> Message-ID: <42c32af7@usenet01.boi.hp.com> Chung Leong wrote: > Isn't that an NP-complete problem or am I crazy? It is NP complete. Its known as the "cutting stock problem" (aka "Knapsack problem"). Here's a Wikipedia page that describes it: http://en.wikipedia.org/wiki/Cutting_stock_problem There are commerical applications available that "solve" the problem in 2D for use in the woodworking industry (among others). This is generally done to minimize waste when cutting down panels (plywood, etc) into smaller pieces for cabinets, etc. -Don From spam.csubich+block at block.subich.spam.com Mon Jun 27 23:32:40 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Mon, 27 Jun 2005 23:32:40 -0400 Subject: DParser binaries on Win32 with Python 2.4? Message-ID: From the documentation, it looks like DParser-python will do what I need, but I'm having trouble getting it installed properly. I'm using a win32 environment, with official 2.4 Python binaries. The official DParser for Python win32 binaries (staff.washington.edu/sabbey/dy_parser) fail, saying that I don't have Python 2.3 installed. :/ Compling the source on cygwin (with -mno-cygwin) succeeds in compilation, but then attempting to install results in: \Python24\python.exe setup.py install running install running build running build_py creating build creating build\lib.win32-2.4 copying dparser.py -> build\lib.win32-2.4 running build_ext building 'dparser_swigc' extension error: Python was built with version 7.1 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. I lack VS, and would prefer to stay using win32 Python rather than cygwin Python because I got twisted, which I also use, working on win32 and not cygwin. Any ideas? From http Sun Jun 12 16:17:30 2005 From: http (Paul Rubin) Date: 12 Jun 2005 13:17:30 -0700 Subject: How to test if an object IS another object? References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> Message-ID: <7x3brnz5wl.fsf@ruckus.brouhaha.com> eloff777 at yahoo.com writes: > >foo = 3 > >bar = 3 > clearly foo and bar have the same value but they are different objects > aren't they? No, they're the same object. Now try it with 300 instead of 3 ;-). From gsakkis at rutgers.edu Sun Jun 19 13:52:22 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 19 Jun 2005 10:52:22 -0700 Subject: Why is there no instancemethod builtin? References: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> <1119197146.922190.38000@g44g2000cwa.googlegroups.com> <1119201221.143713.8890@z14g2000cwz.googlegroups.com> <1119202546.388847.114650@g14g2000cwa.googlegroups.com> Message-ID: <1119203542.789312.5620@g44g2000cwa.googlegroups.com> Michele Simionato wrote: > I think strings do not have __iter__ on purpose, exactly to distinguish > them from other iterables, since sometimes it is nice to consider them > atomic, but I am not sure of this. You should ask the developers. Anyway, the > right definition of iterable is (as I was told) "an object X such that > iter(X) does not throw an exception". Hmm.. not a very insightful definition unless someone knows the implementation of iter(). > Objects following the __getitem__ protocol - such as strings - are iterables > even if they do not have an __iter__ method. It would be more uniform if the default 'type' metaclass added an __iter__ method to classes that define __getitem__ but not __iter__ with something like: from itertools import count def __iter__(self): for i in count(): try: yield self[i] except IndexError: raise StopIteration George From adsheehan at eircom.net Thu Jun 23 12:26:15 2005 From: adsheehan at eircom.net (adsheehan at eircom.net) Date: 23 Jun 2005 09:26:15 -0700 Subject: Urgent problem: Embedding Python questions.... Message-ID: <1119543975.390653.246910@g43g2000cwa.googlegroups.com> Hi, I am embedding Python into a multi-threaded C++ application runnig on Solaris and need urgent clarification on the embedding architecture and its correct usage (as I am experience weird behaviors). Can anyone clarify: - if Python correctly supports multiple sub-interpreters (Py_NewInterpreter) ? - if Python correctly supports multiple thread states per sub-interpreter (PyThreadState_New) ? and the "real" question: - what is the rationale for choosing one of: [a] one sub-interpreter with many thread states [b] many sub-interpreters with one thread state each [c] many sub-interpreters with many threas states each Thanks for helping Alan From querypk at gmail.com Tue Jun 7 12:40:02 2005 From: querypk at gmail.com (querypk at gmail.com) Date: 7 Jun 2005 09:40:02 -0700 Subject: time consuming loops over lists In-Reply-To: References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> Message-ID: <1118162402.092529.225610@o13g2000cwo.googlegroups.com> wow i dint know that a single statement like that would make such a difference. Thanks you very much. that really improves the performance From exarkun at divmod.com Thu Jun 23 16:24:51 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 23 Jun 2005 16:24:51 -0400 Subject: Hardening enviroment by overloading __import__? In-Reply-To: <56190b6c05062313125aef8332@mail.gmail.com> Message-ID: <20050623202451.5047.897141615.divmod.quotient.7901@ohm> On Thu, 23 Jun 2005 13:12:12 -0700, Steve Juranich wrote: >If this is a FAQ, please let me know where the answer is. > >I have in some code an 'eval', which I hate, but it's the shortest >path to where I need to get at this point. I thought that one way I >could harden the enviroment against malicious code would be to >temporarily disable the import statement by overloading __import__, >but I tried what seemed obvious to me, and it didn't work. > >What I want do do is something like this: > >def __import__(*args, **kwargs): > raise ImportError, 'Not so fast, bucko!' > >eval(potentially_dangerous_string) > >del __import__ # To get the builtin behavior back. > >Am I barking up the wrong tree with __import__?? Where should I look >for this answer? __builtin__.__import__ is what you need to replace. Note, of course, that this only makes it trivially more difficult for malicious code to do destructive things: it doesn't even prevent the code from importing any module it likes, it just makes it take a few extra lines of code. Jp From curi at curi.us Thu Jun 2 00:23:45 2005 From: curi at curi.us (Elliot Temple) Date: Wed, 1 Jun 2005 21:23:45 -0700 Subject: Beginner question: Logs? In-Reply-To: <1117685058.142351.123660@g47g2000cwa.googlegroups.com> References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: On Jun 1, 2005, at 9:04 PM, Svens wrote: > Hey thanks... > > Still getting an error message though. Here's what i'm doing: > ------ > import math > log10(15625) > ------ > -It says that log10 is not defined, but it is since the module is > imported, right? do either import math math.log10(15625) from math import * log10(15625) from math import log10 log10(15625) -- Elliot Temple http://www.curi.us/ --- [This E-mail scanned for viruses by Declude Virus] From sjmachin at lexicon.net Sun Jun 12 09:35:15 2005 From: sjmachin at lexicon.net (John Machin) Date: Sun, 12 Jun 2005 23:35:15 +1000 Subject: How to get/set class attributes in Python In-Reply-To: References: <42ac0c6d$0$10102$626a14ce@news.free.fr> Message-ID: <42AC3A13.9020503@lexicon.net> Kalle Anke wrote: > On Sun, 12 Jun 2005 12:20:29 +0200, tiissa wrote > (in article <42ac0c6d$0$10102$626a14ce at news.free.fr>): > > > >>You can 'hide' you getsetters using a property attribute[1]: >> >>[1]http://docs.python.org/lib/built-in-funcs.html > > > Thanks, this is exactly what I was looking for > > OTOH, I beseech you to consider an attitude transplant :-) I.e. put your effort into writing code that allows people to do useful things, rather than opaque guff full of __blahblah__ that stops them from doing dopey or evil things they're usually smart enough or righteous enough not to do anyway. BTW, what do you think of this: sys.maxint = -12345 Cheers & HTH, John From steven.bethard at gmail.com Mon Jun 6 13:51:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 06 Jun 2005 11:51:07 -0600 Subject: how to get name of function from within function? In-Reply-To: References: Message-ID: Christopher J. Bottaro wrote: > Steven Bethard wrote: >>... def _impl_wrapper(self, func): >>... def wrapper(*args, **kwargs): >>... try: >>... return func(*args, **kwargs) >>... except: >>... print "entered except" >>... raise >>... return wrapper >>... [snip] > > The problem is: > >>>>c.func_b.__name__ > > 'wrapper' > > That messes up SOAPpy's RegisterFunction() method which apparently depends > on the __name__ of the function to publish it as an available SOAP > function. Hmm... Nasty. If you were using Python 2.4, you could simply write it as: def _impl_wrapper(self, func): def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: print "entered except" raise wrapper.__name__ = func.__name__ return wrapper Where you fix up the wrapper's __name__ attribute. But I believe the __name__ attribute is read-only in Python 2.3... STeVe From rkern at ucsd.edu Sun Jun 12 19:14:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 12 Jun 2005 16:14:36 -0700 Subject: changing how instances are "created" In-Reply-To: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> Message-ID: newseater wrote: > Hello. I need to be able to control how objects are created. Sometimes > when creating an object, i want to reuse another object instead. I've > searched for factory method implementations and singleton > implementations. They were too much of a hack! > > My first attempt of doing this was to play around with the __new__() > method. But i didn't quite succed. Then i came up with making a static > method which can create my instances or re-use other instances. > However, the below code I cannot get to work :( > > class Creator > def createInstance(cls, *args, **kwargs): > anewinstance = cls.__new__(cls, *args, **kwargs) > anewinstance.__init__(*args, **kwargs) > > return anewinstance > createInstance = staticmethod(createInstance) You want a classmethod, not a staticmethod. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ville at spammers.com Wed Jun 22 04:56:51 2005 From: ville at spammers.com (Ville Vainio) Date: 22 Jun 2005 11:56:51 +0300 Subject: Loop until condition is true References: Message-ID: >>>>> "Stelios" == Stelios Xanthakis writes: Stelios> Anyway, if you can't wait for 2.5 either use 'while 1:', Stelios> or pyc[1] ... and I can't see why people don't want to use 'while 1:' in the first place, given that everyone can identify the idiom immediately. It's 4 keystrokes less. -- Ville Vainio http://tinyurl.com/2prnb From superprad at gmail.com Mon Jun 13 16:20:07 2005 From: superprad at gmail.com (PyPK) Date: 13 Jun 2005 13:20:07 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> Message-ID: <1118694007.688607.124530@z14g2000cwz.googlegroups.com> nothing fancy. I just want to be able to read a tiff image, get pixel values, write back to a tiff file. From msmith at msmith.id.au Tue Jun 14 04:53:32 2005 From: msmith at msmith.id.au (Michael Smith) Date: Tue, 14 Jun 2005 18:53:32 +1000 Subject: gobal var inside class without notice??? In-Reply-To: <1118738391.216206.142280@g47g2000cwa.googlegroups.com> References: <1118738391.216206.142280@g47g2000cwa.googlegroups.com> Message-ID: <42AE9B0C.5080300@msmith.id.au> ajikoe at gmail.com wrote: >I have code like this: > >class A: > def __init__(self,j): > self.j = j > > def something(self): > print self.j > print i # PROBLEM is here there is no var i in class A but it >works ??? > >if __name__ == '__main__': > i = 10 > a = A(5) > a.something() > >I don't define global i but it will takes var i from outside of class >A. > >Can somebody explain this ??? > >pujo > > > Actually you *have* defined a global variable called 'i' - when you run code at file scope, as you have where you wrote i = 10, all variables are global. This means that they can be referred to anywhere in the module, as you found. It also means that variable accesses are slower, since accessing globals is slower than accessing local variables. This is why many people suggest that you define a function called main() and have the main script simply call that. Michael From nephish at xit.net Thu Jun 30 00:56:49 2005 From: nephish at xit.net (nephish at xit.net) Date: 29 Jun 2005 21:56:49 -0700 Subject: need help with MySQLdb Message-ID: <1120107408.960230.111180@g44g2000cwa.googlegroups.com> Hey there all, i have a question about how to point my python install to my sql database. when i enter this: db = MySQLdb.connect(user="user", passwd="pass", db="myDB") i get this: Traceback (most recent call last): File "", line 1, in -toplevel- db = MySQLdb.connect(user="user", passwd="pass", db="MyDB") File "/usr/lib/python2.4/site-packages/MySQLdb/__init__.py", line 66, in Connect return Connection(*args, **kwargs) File "/usr/lib/python2.4/site-packages/MySQLdb/connections.py", line 134, in __init__ super(Connection, self).__init__(*args, **kwargs2) OperationalError: (1049, "Unknown database 'MyDB'") i am using the all in one package from lampp (now xampp) and i have tested a couple of python scripts from the cgi, but.... nothing that connects to the database. any ideas? thanks From __peter__ at web.de Wed Jun 8 05:18:18 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Jun 2005 11:18:18 +0200 Subject: time consuming loops over lists References: <1118158808.215392.89090@f14g2000cwb.googlegroups.com> Message-ID: querypk at gmail.com wrote: > X-No-Archive: yes > Can some one help me improve this block of code...this jus converts the > list of data into tokens based on the range it falls into...but it > takes a long time.Can someone tell me what can i change to improve > it... > > def Tkz(tk,data): > no_of_bins = 10 > tkns = [] > dmax = max(data)+1 > dmin = min(data) > rng = ceil(abs((dmax - dmin)/(no_of_bins*1.0))) > rngs = zeros(no_of_bins+1) > for i in xrange(no_of_bins+1): > rngs[i] = dmin + (rng*i) > for i in xrange(len(data)): > for j in xrange(len(rngs)-1): > if data[i] in xrange(rngs[j],rngs[j+1]): > tkns.append( str(tk)+str(j) ) > return tkns On second thought, with bins of equal size you have an option that is even faster than bisect: def bins_calc(tk, data, no_of_bins=10): dmax = max(data) + 1 dmin = min(data) delta = dmax - dmin rng = int(ceil((dmax - dmin)/no_of_bins)) tokens = [tk + str(i) for i in xrange(no_of_bins)] return [tokens[(v-dmin)//rng] for v in data] Peter From serseri_30666 at yahoo.com Sat Jun 18 02:01:42 2005 From: serseri_30666 at yahoo.com (serseri_30666 at yahoo.com) Date: 17 Jun 2005 23:01:42 -0700 Subject: ANN: IssueTrackerProduct 0.6.9 with AJAX and Reports In-Reply-To: <1119046427.954079.135610@z14g2000cwz.googlegroups.com> References: <1119039397.722318.243960@g49g2000cwa.googlegroups.com> <1119046427.954079.135610@z14g2000cwz.googlegroups.com> Message-ID: <1119074502.027616.308020@z14g2000cwz.googlegroups.com> selam benim ismim samet bende sizin gruba katilmak istiyorumkabul ederseniz sevinirim etmeseniz ayrilirim From kveretennicov at gmail.com Fri Jun 17 09:23:55 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Fri, 17 Jun 2005 16:23:55 +0300 Subject: thread.start_new_thread question In-Reply-To: References: Message-ID: <4660fe30050617062318efe812@mail.gmail.com> On 6/17/05, Brian wrote: > Hi KV, > > Here's a site that provides an easy, beginners example of how to do > threading. You might find this useful too... :-) > > http://www.codesampler.com/python.htm > (Look for the "Spawning Threads" section.) Thank you, but that doesn't answer my question. I was asking if there is a reason that "args" is not optional. Oftentimes functions I use to start_new_thread have no arguments (they may get data from bound instance or from closure), but still I have to pass empty "args", always wondering, why? Python lib generally has a very nice and convenient interface and tries to supply sensible defaults when possible. That "args" is a required argument is a mystery to me :) - kv A. No. Q. Is top posting OK? From riccardo_cut1 at cut2_sideralis.net Thu Jun 23 08:50:12 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Thu, 23 Jun 2005 14:50:12 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: On Thu, 23 Jun 2005 13:25:06 +0200, Daniel Dittmar wrote: > He probably meant that a 'join' option would be more natural than an 'abs' > option. After all, your examples use os.path.join to create a valid path > that can be used as the argument to other module os functions. Whether the > results are absolute or relative should depend on the initial argument to > os.listdir. > > Daniel I got the point, and you're right. I didn't though about that and 'abs' as keyword becomes nonsense. Needing a more general kewyword, as pointed out by Peter Otten -- Riccardo Galli Sideralis Programs http://www.sideralis.net From steven.bethard at gmail.com Thu Jun 23 17:41:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Jun 2005 15:41:43 -0600 Subject: Hardening enviroment by overloading __import__? In-Reply-To: References: Message-ID: Steve Juranich wrote: > I have in some code an 'eval', which I hate, but it's the shortest > path to where I need to get at this point. What's this code trying to do? If you care about malicious code at all, you'll avoid 'eval' completely. A couple reasons why: With only a little trouble, I can get to the file object and write stuff to your machine: py> eval("().__class__.mro()[1].__subclasses__()[16]") Sure, you can avoid this by supplying your own __builtins__ to disable the file constructor: py> eval("().__class__.mro()[1].__subclasses__()[16]('temp.txt')", dict(__builtins__={})) Traceback (most recent call last): File "", line 1, in ? File "", line 0, in ? IOError: file() constructor not accessible in restricted mode But even without the file constructor, I can still access pretty much any attribute of any class object by looking at object.__subclasses__(): py> class C(object): ... def __init__(self): ... self.f = file('temp.txt', 'w') ... py> eval("().__class__.mro()[1].__subclasses__()[-1]().f.write('junk')", dict(__builtins__={})) py> file('temp.txt').read() 'junk' Moral of the story: don't use eval if you care about security! STeVe From ramen at lackingtalent.com Wed Jun 15 15:52:33 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Wed, 15 Jun 2005 12:52:33 -0700 Subject: FAQ: __str__ vs __repr__ In-Reply-To: <42b021ba$1@griseus.its.uu.se> References: <42b021ba$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Sorry, but I Just Don't Get It. I did search the 'net, I did read the > FAQ, but I'm too dumb to understand. Say we define a string "s" as follows: >>> s = 'hello' If we print "s", we see its string form (__str__): >>> print s hello However, if we just examine "s", we see its representation (__repr__): >>> s 'hello' This can be verified by calling str() and repr() on the string: >>> str(s) 'hello' >>> repr(s) "'hello'" So, the result of repr() includes quotes, whereas the result of str() does not. This has useful properties when the object is part of a more complex structure. For instance, these two expressions print out the same: >>> [s, s] ['hello', 'hello'] >>> print [s, s] ['hello', 'hello'] That's because, in either case, the repr() form is used. If Python only had str(), we would probably expect str(s) = s, so we'd instead see something like this imaginary snippet: >>> [s, s] [hello, hello] >>> repr([s, s]) '[hello, hello]' So, the convention in Python is that repr() returns a string that, when evaluated, returns the original object. This is not always easy or possible to do, but if you can do it, your objects will print nicely when nested within Python's built-in data structures. Python's actual behavior is this: >>> repr([s, s]) "['hello', 'hello']" And therefore: >>> eval(repr([s, s])) ['hello', 'hello'] Also worth noting is that if you define __repr__, the default behavior of __str__ is to delegate to that definition, so if you only want to define one, it's often more convenient to just define __repr__. Dave From pwilkins at noaddress.org Fri Jun 24 13:59:19 2005 From: pwilkins at noaddress.org (pwilkins) Date: Fri, 24 Jun 2005 13:59:19 -0400 Subject: Newbie question: how to keep a socket listening? Message-ID: First off I'm want to learn socket/network programming with python so a lot of what I ask is newbie related. I have written a test socket server that runs as a daemon. It listens on two sockets (say at ports 8000 and 9000) so that I can telnet over from another machine and get process info (ps type of info), one one port and control the server on the other port. What I want is to have the daemon run thread (A) which listens on port 8000, and then runs another thread (B) which listens 9000. Thread A monitors whether thread B is alive with a thread_B_.isSet() call. If thread B has terminated then thread A can exit when user tells it to, otherwise not. Thread B will terminate when user tells it to exit. I can start the daemon and connect to both ports just fine. If I leave the connections on using telnet for example, the connections keep working (stay alive). This part works. But I also want to be able to disconnect the telnet sessions, but leave the daemon server still listening on both ports so I can reconnect to both ports later. If I disconnect and try to reconnect within about 10secs it works fine. However if I stay disconnected from more than a minute then I cannot reconnect later. It seems as if the the server is not listening anymore....although the threads are still running i.e. the daemon is up. The message from telnet is: >>telnet: connect to address xxx.xxx.xxx.xxx: Connection refused Perhaps I do not understand the function of the following: socket.setdefaulttimeout(15) socket.settimeout(15.0) What is the difference between these?? Yes I have read the python docs - setdefaulttimeout(timeout) Set the default timeout in floating seconds for new socket objects. whereas: - settimeout(value): Set a timeout on blocking socket operations. So what this means to me is that with setdefaulttimeout one can set a global timeout for new sockets, wheres with settimeout one can fine tune it after a socket has been created. This is probably all wrong. Any ideas as to what is causing the server to stop listening after I disconnect for a long period of time. Also does one have to do a socket.shutdown() before one does a socket.close?? How should a server disconnect a client but keep listening for subsequent connections from other clients? I have included a summary of important code below. Let me know if should provide more or different info. Thanks a lot in advance. Pete ------------------------------------- The program basically works as below: ------------------------------------- (1) become a daemon (2) call server function which does the following (summarized): import socket ... HOST = '' socket.setdefaulttimeout(15) try: sa = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sa.bind((HOST, AdminPort)) sa.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sa.settimeout(15.0) sa.listen(1) except: ## exit on failure ## run 2nd socket handler as thread # create an event to signal the completion of client handler thread client_handler_complete=threading.Event() client_handler_complete.clear() server_handler_thread = threading.Thread (None, ClientHandler, None, \ (StateValues, client_handler_complete)) try: server_handler_thread.start() except: ## exit on failure while 1: ## wait for a connection try: #...waiting for connection (client, address)=sa.accept() except sa.timeout: #...waiting for connection timeout continue except: continue ## for now ignore this! #...someone's connecting, so check if ipaddress is allowed remote = str(address[0]) if Allowed_Hosts.has_key(remote): hostname = Allowed_Hosts[remote] Message = '%s connection accepted from: %s (%s:%s))' % \ (FUNCNAME, hostname, address[0], address[1]) log_message(StateValues, Message, 1) else: client.close() Message = '%s connection rejected from: %s' % (FUNCNAME, address) log_message(StateValues, Message, 1) continue socketfile = client.makefile() while 1: ## wait for user input data = '' data=read_data(socketfile) if not data or data == 'CR': continue else: Message = '%s input received: %s' % (FUNCNAME, data) log_debug_message(StateValues, Message) if data == 'q': ##disconnect client but keep waiting for connections ... client.close() elif data == 'x': ##disconnect client and shutdown server ... client.close() socketfile.close() sys.exit(0) ## wait for user input ## end wait for a connection (3) the thread which handles the second socket is coded like that above. From rkern at ucsd.edu Sat Jun 18 23:52:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 18 Jun 2005 20:52:26 -0700 Subject: SciPy gui_thread Problem In-Reply-To: References: Message-ID: Hsuan-Yeh Chang wrote: > Dear SciPy users, If you want to address Scipy users, you should post to the Scipy mailing list. > Can anyone tell me the reason for following error messages: > > >>>>import gui_thread >>>>gui_thread.start() > > Traceback (most recent call last): > File "/usr/lib/python2.4/site-packages/scipy_base/pexec.py", line 56, in > run > exec (code, frame.f_globals,frame.f_locals) > File "", line 1, in ? > ImportError: /usr/lib/wxPython/lib/libwx_gtk2u_ogl-2.5.so.3: undefined > symbol: _ZNK6wxExpr3NthEi Something has been compiled incorrectly or shared libraries are missing. In any case, gui_thread probably won't work with wxPython 2.5. Development on gui_thread has stopped in favor of ipython's threading support. http://ipython.scipy.org http://ipython.scipy.org/doc/manual/node5.html#sec:threading-opts -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From theller at python.net Fri Jun 3 05:06:30 2005 From: theller at python.net (Thomas Heller) Date: Fri, 03 Jun 2005 11:06:30 +0200 Subject: odbc and python In-Reply-To: <1117785062.654497.192330@g44g2000cwa.googlegroups.com> References: <1117785062.654497.192330@g44g2000cwa.googlegroups.com> Message-ID: <3gaksmFbdlbqU1@individual.net> Giles Brown schrieb: > MM wrote: > >>Are there any other odbc packages other than the win32all and mxodbc >>ones? The win32all odbc.pyd can't access table structure info like >>SQLColumns, and mxobdc requires a commercial license which is >>unjustifiable for this tiny project. Any other OS alternatives for >>win32?. Thanks. > > > You could potentially make the ODBC calls using ctypes a la: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303667 > > Not tried this myself and imagine it could be a bit tedious. > > Cheers, > Giles > If someone wants to try this approach (personally, I don't use databases), it seems that the tools provided with ctypes, if you have gccxml (and MSVC) installed, should give a good start. Running h2xml windows.h sql.h -o sql.xml -c and xml2py sql.xml -rSQL.* -o sql.py -lodbc32 -d creates a 830 lines Python module, containing a lot of useful SQL stuff, which can be hacked on. To give an impression, the file starts with the following lines, so a lot of constants and datatypes are already defined: # generated by 'xml2py' # flags 'sql.xml -rSQL.* -o sql.py -lodbc32 -d -m ctypes.com' from ctypes import * SQL_DATETIME = 9 # Variable c_int SQL_MAX_USER_NAME_LEN = 107 # Variable c_int SQL_DEFAULT_TXN_ISOLATION = 26 # Variable c_int SQL_API_SQLFREEHANDLE = 1006 # Variable c_int SQL_ALTER_TABLE = 86 # Variable c_int SQL_IS_DAY_TO_SECOND = 10 SQL_API_SQLCOLUMNS = 40 # Variable c_int SQL_TXN_READ_UNCOMMITTED = 1 # Variable c_long SQL_TRANSACTION_READ_UNCOMMITTED = SQL_TXN_READ_UNCOMMITTED # alias SQL_DBMS_NAME = 17 # Variable c_int SQLSMALLINT = c_short SQLRETURN = SQLSMALLINT SQLHANDLE = c_void_p SQLHDBC = SQLHANDLE SQLUSMALLINT = c_ushort @ stdcall(SQLRETURN, 'odbc32', [SQLHDBC, SQLUSMALLINT, POINTER(SQLUSMALLINT)]) def SQLGetFunctions(p1, p2, p3): # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/sql.h 735 return SQLGetFunctions._api_(p1, p2, p3) SQL_TRUE = 1 # Variable c_int SQLHSTMT = SQLHANDLE SQLCHAR = c_ubyte UDWORD = c_ulong @ stdcall(SQLRETURN, 'odbc32', [SQLHSTMT, SQLUSMALLINT, POINTER(SQLCHAR), SQLSMALLINT, POINTER(SQLSMALLINT), POINTER(SQLSMALLINT), POINTER(UDWORD),POINTER(SQLSMALLINT), POINTER(SQLSMALLINT)]) def SQLDescribeCol(p1, p2, p3, p4, p5, p6, p7, p8, p9): # C:/PROGRA~1/MICROS~3.NET/Vc7/PLATFO~1/Include/sql.h 650 return SQLDescribeCol._api_(p1, p2, p3, p4, p5, p6, p7, p8, p9) SQL_DROP = 1 # Variable c_int SQL_DATA_SOURCE_NAME = 2 # Variable c_int SQL_TXN_SERIALIZABLE = 8 # Variable c_long SQL_TRANSACTION_SERIALIZABLE = SQL_TXN_SERIALIZABLE # alias Thomas From ny_r_marquez at yahoo.com Mon Jun 13 13:45:19 2005 From: ny_r_marquez at yahoo.com (RM) Date: 13 Jun 2005 10:45:19 -0700 Subject: searching for IDE In-Reply-To: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: <1118684719.026680.306940@g47g2000cwa.googlegroups.com> You should also check out eric3. It is cross-platform, free, very advanced, and with a super active development community. -RM alexrait1 wrote: > I need an IDE for python that has the ability to show the filds of a > class when I write "." > Just the way it works in eclipse/JBuilder with java or visual studio > with c++ > For now I treid eric3 and IDLE they don't do this... From timothy.williams at nvl.army.mil Wed Jun 8 10:30:30 2005 From: timothy.williams at nvl.army.mil (timothy.williams at nvl.army.mil) Date: 8 Jun 2005 07:30:30 -0700 Subject: running distutils installer without admin on windows Message-ID: <1118241029.833151.252720@g47g2000cwa.googlegroups.com> Hello all. We don't have admin privs on our Windows boxes, but I'd like to be able to install a package built using distutils. I was able to install Python without admin, but when I tried to run the installer for this package I'm trying to install, I get a message saying that I need admin privs. Is there a way around this? Why can't it just put things in C:\Python23\Lib\site-packages like a good little installer? Do I need to put a service call in to our admins to do this? Thanks. From wookiz at hotmail.com Fri Jun 10 07:04:54 2005 From: wookiz at hotmail.com (wooks) Date: 10 Jun 2005 04:04:54 -0700 Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <1118390462.698504.43650@z14g2000cwz.googlegroups.com> Message-ID: <1118401494.385789.289320@g49g2000cwa.googlegroups.com> > Most assuredly, what Terry sent you is *not* hate mail. It was not taken as hate mail. I think Lucas got it spot on. Thank you for the long lecture on netiquette which I didn't really need. Anybody who has read and understood the book "How to win friends and influence people" would understand what I meant (yes I do own it and no I am not selling it on ebay). From dan at nospam.com Wed Jun 22 14:53:53 2005 From: dan at nospam.com (Dan) Date: Wed, 22 Jun 2005 13:53:53 -0500 Subject: Database recommendations for Windows app In-Reply-To: References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> Message-ID: <3tiue.27$jv6.1568@news.uswest.net> On 6/22/2005 1:14 PM, Dave Cook wrote: > On 2005-06-22, Cameron Laird wrote: > > >>Are you saying that Python-based applications are particularly >>vulnerable in this all-too-common scenario? If so, I'm not >>getting it; why is the architecture described more fragile than >>more traditional Windows-oriented development patterns? If not, >>then, ... well then I truly don't get your point. > > > Maybe the point is the downside of depending on installed DLLs rather than > shipping your own. > > Dave Cook Yes, DLL hell. From jjl at pobox.com Fri Jun 10 14:26:16 2005 From: jjl at pobox.com (John J. Lee) Date: 10 Jun 2005 19:26:16 +0100 Subject: Destructive Windows Script References: <11a99vais6kj95f@corp.supernews.com> Message-ID: <4qc6rruf.fsf@pobox.com> Grant Edwards writes: > > I take this to mean the the drive is non-functional and might > > have well been melted, except that demagnetising is cheaper. > > Yup. In a frequently cited scary paper (on the web &c.), Peter Gutmann claims claims that's not true in practise, IIRC: http://www.cs.auckland.ac.nz/~pgut001/pubs/secure_del.html Go for the thermite reaction instead!-) (please don't try that at home, kids) John From eurleif at ecritters.biz Thu Jun 16 03:31:53 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 16 Jun 2005 07:31:53 GMT Subject: Generating .pyo from .py In-Reply-To: References: Message-ID: skn wrote: > Does the python compiler provide an option to generate a .pyo(optimized byte > code file) from a .py (source file)? > > For generating .pyc I know that I only have to pass the source file name as > an argument to py_compile.py. py_compile.py checks __debug__ to decide whether to use optimize mode, and the -O option to Python turns __debug__ off, so: python -O py_compile.py foo.py From mwm at mired.org Wed Jun 29 21:37:34 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 29 Jun 2005 21:37:34 -0400 Subject: Boss wants me to program References: Message-ID: <86fyv0pqu9.fsf@bhuda.mired.org> "Adriaan Renting" writes: > I realy prefer a WYSIWYG UI design tool > to having to code BUTTON(120, 123, 123, 335, -1, NULL, doButton, "Push", > "push this button") With a modern GUI library, it's more like: buttonBox.addWidget(Button("&New", my, "new")) and your button is added to the buttonbox. Anything that requires you to specify the location exactly (whether in a WYSISOWYG GUI tool or code) is fundamentally broken. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From chad.hughes at pnl.gov Thu Jun 9 11:31:27 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Thu, 09 Jun 2005 08:31:27 -0700 Subject: Posting a reply to a post in an existing thread Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6150@pnlmse27.pnl.gov> This may be a dumb question. I am new to using this list, and I cannot figure out how to send a reply to a message that has been posed in a thread without creating a new thread. Let me rephrase my question. The instructions for posting to the list is to send a message to python-list at python.org. There are no instructions for posting a reply. What I need to know is, what do I put in either the TO field, the CC field, or the SUBJECT field for the list to see my message as a reply to an existing post in a thread and not a new thread. When I use RE: in front of the reply and put python-list at python.org in the TO field, my reply ends up as the start of a new thread. Is this supposed to be the procedure? Thanks, Chad -------------- next part -------------- An HTML attachment was scrubbed... URL: From eurleif at ecritters.biz Sat Jun 11 14:45:52 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 11 Jun 2005 18:45:52 GMT Subject: case/switch statement? In-Reply-To: References: Message-ID: Joe Stevenson wrote: > I skimmed through the docs for Python, and I did not find anything like > a case or switch statement. I assume there is one and that I just > missed it. Can someone please point me to the appropriate document, or > post an example? I don't relish the idea especially long if-else > statements. If you really want one, you could use . From steve at REMOVETHIScyber.com.au Thu Jun 2 12:08:24 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Fri, 03 Jun 2005 02:08:24 +1000 Subject: convert a string to tuple References: <1117570449.887422.225670@g43g2000cwa.googlegroups.com> Message-ID: On Tue, 31 May 2005 13:14:09 -0700, querypk wrote: > how do I convert > b is a string b = '(1,2,3,4)' to b = (1,2,3,4) You can do: def str2tuple(s): """Convert tuple-like strings to real tuples. eg '(1,2,3,4)' -> (1, 2, 3, 4) """ if s[0] + s[-1] != "()": raise ValueError("Badly formatted string (missing brackets).") items = s[1:-1] # removes the leading and trailing brackets items = items.split(',') L = [int(x.strip()) for x in items] # clean up spaces, convert to ints return tuple(L) For real production code, you will probably want better error checking. -- Steven. From peter at engcorp.com Tue Jun 14 08:06:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 08:06:00 -0400 Subject: Resume after exception In-Reply-To: References: Message-ID: Richard Lewis wrote: > Is it possible to have an 'except' case which passes control back to the > point after the exception occurred? Basically no, although I could imagine some gross hack with the frame info and some bytecode hacks that effect a "goto". Basically the stack frame gets unwound to the point where the exception is caught. If you need recoverability, write your open_file function to be resumable in some way. Note that you could easily (perhaps) implement this as a callable object, with the required state stored internally, and make the result almost indistinguishable from what you are asking for: I could imagine an API allowing something like this: open_file = RecoverableOpenFileThingy() while not open_file.completed: try: open_file("foo.bar") except FileLockException, ex: # blah blah if ans != tkMessageBox.YES: open_file.completed = True But since your open_file() doesn't seem likely to be doing anything particularly complicated, I really doubt you need the complexity of a special class here. Just stick the relevant code inside a loop, much like that above, and break out of the loop when things succeed. (What internal state do you think the open_file procedure would have to maintain, which you would be trying to resume? If you are just going to go back to the beginning of it and try again, you don't need anything like what you asked for, just a regular loop.) From dlc at io.frii.com Fri Jun 17 14:26:47 2005 From: dlc at io.frii.com (Dennis Clark) Date: Fri, 17 Jun 2005 18:26:47 -0000 Subject: add new modules? Message-ID: <11b65f7bjjt7a51@corp.supernews.com> This is a total newb question, you have been warned... I've been all over the www.python.org site and googled, but I've not found just how to add new modules. I've tried setting PYTHONPATH, I've tried putting the new module directories into the site-packages directory, I've tried creating the .pth files, I've even done all three of these things at the same time and still my python script refuses to import. What is the cannonical way to add new modules to python? I am running on OS X 10.4 (Macintosh obviously) on basically freeBSD, os I'm doing UNIX type stuff at the console. thanks for any help, DLC -- ============================================================================ * Dennis Clark dlc at frii.com www.techtoystoday.com * * "Programming and Customizing the OOPic Microcontroller" Mcgraw-Hill 2003 * ============================================================================ From michele.simionato at gmail.com Fri Jun 3 06:00:40 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 3 Jun 2005 03:00:40 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: <1117649990.028395.116640@f14g2000cwb.googlegroups.com> References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> <1117649990.028395.116640@f14g2000cwb.googlegroups.com> Message-ID: <1117792840.643784.73150@g49g2000cwa.googlegroups.com> You should read the metaclass book, if you can find it. For the reference, see http://www-106.ibm.com/developerworks/linux/library/l-pymeta.html http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/index.html Michele Simionato From http Wed Jun 1 14:39:54 2005 From: http (Paul Rubin) Date: 01 Jun 2005 11:39:54 -0700 Subject: BUG pythonw vs subprocess References: <429DFB8B.4090102@jessikat.fsnet.co.uk> Message-ID: <7xfyw1zzt1.fsf@ruckus.brouhaha.com> I thought pythonw didn't provide a console and so it could be that stdin and stdout aren't connected to anything. Popen therefore doesn't make sense. You have to use sockets or something. From ramen at lackingtalent.com Sat Jun 25 20:07:31 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sun, 26 Jun 2005 00:07:31 -0000 Subject: Thoughts on Guido's ITC audio interview Message-ID: Guido gave a good, long interview, available at IT Conversations, as was recently announced by Dr. Dobb's Python-URL! The audio clips are available here: http://www.itconversations.com/shows/detail545.html http://www.itconversations.com/shows/detail559.html I'd like to comment on a few parts of that interview. One thing Guido mentions in his comparison of ABC (Python's predecessor) and Python is how ABC was inextricably tied to its environment (a la Smalltalk), where Python, though it supports an interactive mode, follows more of a UNIX-style "do one thing well" philosophy, and was designed to integrate with other tools rather than being a whole world to its own. I find that a similar comparison can be made between Python and Java. Java's startup time is so long that it is not practical for writing small tools for use in command-line scripts, and the propensity toward application servers and integrated development environments suggests a strong preference for a monolithic, self-contained, single-language environments. On the other hand, even though internally "there's only one way to do it" in Python, Python itself is one of many ways to develop software, and does not insist on being the one perfect way to do it. You can use whatever editor you like, and the language doesn't go out of its way to make it difficult to use other programs and processes, including the operating system if so desired. It is a bit ironic that, according to Guido, the command-line interpreter interface to Python was more of an afterthought, since my whole experience with Python has very much centered around the interpreter. Like many, I think, my first use for Python was as a calculator. =) In fact, since discovering Python, I've been very resistant toward learning any language that doesn't have an interpreter. Ruby, Scheme, OCaml and SML/NJ have been fun to learn because I can tinker with them at the command line. "perl -de 42" is rather frustrating to use, as is Haskell's "hugs" due to the inability to define new functions at the command line. Command-line interfaces are a great way to get up to speed on new languages and libraries. One of the advantages of Python is that it allows you to graft a CLI onto environments that weren't designed with one. For instance, Jython gives Java a command-line interface, and this makes working with Java much more tolerable since you can interact with libraries in real-time and learn how they behave at runtime. Likewise with PythonWin and COM scripting. I am glad to see that IronPython is designed with a command-line interpreter as well, should I ever need to learn my way around .NET in a hurry. Guido makes a funny jab at Paul Graham about Graham's nine things that make Lisp Lisp (available here: http://www.paulgraham.com/icad.html) - I had read this essay many times but never saw the subtle irony behind claims of "Greenspunning": in order to claim that a language is approaching Lisp, you have to define what it is about Lisp that other languages are purportedly emulating, and this begs the question of why you have the authority to declare which 9 (or n) attributes of Lisp are most important. I like Paul Graham and his essays a lot, but I must admit I had to laugh too when I heard the way Guido framed this argument. I'm not so sure that Python has 8 out of 9, though: the statement/expression dichotomy rules out #6, and the lack of macros rules out #9. These are arguable, depending on how you define things, but I think the most obvious thing that Python lacks compared with Lisp and Scheme (and also Ruby) is a symbol type (#7). I'm in the process of trying to understand what symbols are good for, outside the context of Lisp and its nested lists of symbols as executable code. Ruby seems to have come up with some creative uses for symbols within Python-like syntax, though I haven't seen anything terribly compelling so far. Guido briefly summarizes language comparisons with other languages: - Perl: similar niche, but Perl is for regexes and text processing, and Python is for objects, data structures, and more general-purpose programming. Obligatory TMTOWTDI argument. - PHP: very successful at its niche, being a point-solution for adding bits of script to web pages. Not very useful outside that context, and lots of language-design gaffes. - Java: the usual static vs. dynamic, static analysis vs. unit testing arguments. Guido says that there's such a small amount of problems that can be caught at compile time, and even the smallest amount of unit testing would also catch these problems. "The blindness of that [static] position... escapes me." - C/C++: same arguments as Java, plus most programmers aren't up to the task of manual memory-management. - Lisp: even though there's no code-equals-data in Python, you still have the compiler available at runtime, and there's a lot you can do to treat code as data even though they're not syntactically idnentical. - Smalltalk: very similar to Python, but Python is easier to integrate into existing shops that use other languages, mainly (IMO) because Smalltalk is a self-contained, integrated environment so the cost of introducing it is much higher There was also some discussion on why Java seems to be such a memory hog. Guido chalks it up to Java's "fancy schmancy garbage collection technology" with its heaps and threads and insistance on far-reaching low-level control over all the poitners in the heap. It is a bit ironic that (C)Python with its simple reference-counting plus cycle-detection seems much less resource-hungry than Java's GC, even though most language experts consider GC to be a vastly better technique. But I think this has more to do with Java's particular implementaion of GC; OCaml, for instance, is garbage-collected but has a very lean memory footprint. I think Python's decision to use reference counting was an instance of worse-is-better: at the time, reference counting was already known not to be "the right thing", but it worked, and the implementation was simple. Likewise with dynamic typing versus type inference. It seems that Guido shares Alan Kay's viewpoint that type inference is really "the right thing", but modern language technology is really not ready to make it mainstream, whereas dynamic typing works today, and is arguably a better "worse" solution than explicit/manifest static typing due to its verbosity. >From the perspective of writing C extensions, Guido claims that the amount of pain (regarding memory management) is about the same whether you're extending a reference-counted language like CPython or a garbage collected language like Java. Anyone with experience writing C extensions want to comment on this? Type inferencing is especially difficult to add to a dynamically typed language, and in general I think results are much better if you have type inference from the very beginning (like ML and Haskell) rather than trying to retrofit it later. Guido says that they've only been able to get it to work reliably in Python with constants, which isn't very useful. Regarding Ruby, Guido said that the community is much smaller than Python, and that it's much more of a "better Perl" than a "better Python". I think that, despite claims by both Guido and Matz, Ruby sits pretty much on the fence betwee the two languages. Guido says he dislikes the code block syntax in Ruby, but doesn't make it clear whether it's the syntax he dislikes or the code blocks themselves. He does mention that if you like Smalltalk, you'll probably like Ruby because of the code blocks... Generators and iterators are, according to Guido, an "80% solution" for the kinds of things people use code blocks for in Ruby. I think that the newly-proposed PEP 343 offers adds another 5-10% to the solution, perhaps; soon, Python will be able to do resource management in addition to iteration patterns without the use of code blocks. I can still think of additional uses for code blocks, and I have to wonder how many "point solutions" Python is going to gain in attempt to avoid adding code blocks to the language. This is not to say that I don't think generators or the newly proposed "with" keyword are cool features to have. (Upon review, I realize that Guido made the "80% solution" comment regarding generators vs. continuations, not code blocks. Still, generators are far more specific of a tool than either continuations or blocks.) Someone in the audience mentioned that the CPython VM is so solid they're surprised nobody's implemented a Java program on top of the Python VM (as opposed to the other way around, as in Jython). Someone in the audience surprised everyone by mentioning an actual project attempting this, called javaclass: http://www.boddie.org.uk/python/javaclass.html In response to any question on how to create a language, a community, a successful project, Guido's response tended to be the same: he doesn't really know what he did that made it work, or made the community follow Python so well and for so long. He says it's probably not a good idea to start a new project by following in the footsteps of an old one. If only we could tap a bit deeper into the mystique of successful software projects. ;) Cheers, Dave From kenobi at gmail.com Sat Jun 4 19:02:37 2005 From: kenobi at gmail.com (Rick Kwan) Date: 4 Jun 2005 16:02:37 -0700 Subject: weird cgi problem w/ apache In-Reply-To: <1117923448.900544.143460@f14g2000cwb.googlegroups.com> References: <1117856044.857442.221610@g43g2000cwa.googlegroups.com> <1117923448.900544.143460@f14g2000cwb.googlegroups.com> Message-ID: <1117926157.408591.153790@g43g2000cwa.googlegroups.com> If it is umask, then that would be umask for the Apache process, not the second script (which I presume doesn't run as Apache). The CGI script can explicitly set the permissions when creating the folder using mkdir() or makedirs() so that others can write into it. (Depending on how public or private the machine is, this may or may not be a security issue.) From gatti at dsdata.it Fri Jun 17 03:27:53 2005 From: gatti at dsdata.it (gatti at dsdata.it) Date: 17 Jun 2005 00:27:53 -0700 Subject: Multiple instances of a python program In-Reply-To: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> References: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> Message-ID: <1118993273.674962.186370@g14g2000cwa.googlegroups.com> Most of the Python interpreter is a shared library, at least on Windows. The only duplication is in loaded Python code, which includes only your bot and the libraries it uses. If you have memory problems, try to do without some libraries or to edit unused parts out of them. Lorenzo Gatti From David.Bear at asu.edu Fri Jun 10 02:49:51 2005 From: David.Bear at asu.edu (David Bear) Date: Fri, 10 Jun 2005 06:49:51 +0000 (UTC) Subject: EOFError not getting raised Message-ID: I have been trying to do something like this: f = open('someDocs.str', 'r') try: while True: ln = f.readline() except EOFError: print 'reached eof' f.close() sys.exit(1) However, EOFError is never raised. What am I missing? From lycka at carmen.se Thu Jun 9 06:37:07 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 09 Jun 2005 12:37:07 +0200 Subject: Python as client-side browser script language In-Reply-To: <7xk6leylhi.fsf@ruckus.brouhaha.com> References: <1117576472.580086.300140@g43g2000cwa.googlegroups.com> <7xk6leylhi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Magnus Lycka writes: > >>Of course, one might suggest that it's the task of the browser, >>and not of the scripting language, to provide a safe sandbox >>where scripts can mess around and without causing havoc on >>your computer. Such a system in the browser could be used to >>grant different rights to different parts of the net, regardless >>of what kind of scripting language the resources on those parts >>of the net use. When Firefox has something like that, it's time >>to start marketing Python for client side scripting I think. > > > Huh? The language itself has to provide the sandbox. If the > browser's control over the script language is so fine-grained as to > control every attribute access then the browser and the language are > no longer separate. Remember that scripts have to be able to see > certain DOM elements but not others, and some of them have to be > read-only, etc. I'm not sure I agree with you. This is certainly not the way security is typically handled in computer systems. Operating systems limits access to OS resources such as files, memory, I/O etc. Resource managers such as database systems limit access to data based on some kind of authentication. It's not up to e.g. the database client to control this. The same underlying mechanisms work regardless of the programming language used to code the applicaqtion that wants access to the resources. There are no particular securty issues in writing DB apps in Python instead of Java for instance. Why shouldn't the browser manage resource access for a "foreign" script running embedded in it? I think it's fairly obvious concerning pure browser resources such as the DOM. Concerning pure OS resources such as files, it seems to me that something like a chrooted environment would be best, and I assume this must somehow be provided by the OS. I'm sure it's a non-trivial task to develop such an environment so that it's practical, efficient and safe, but it would open a lot of doors if it could be done. It's possible that new scriping languages must be trimmed a bit to be able to work in such a confinement, but it would certainly enable the use of alternatives to Java as powerful client side application languages in web apps. From roccomoretti at hotpop.com Wed Jun 1 18:00:01 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Wed, 01 Jun 2005 17:00:01 -0500 Subject: PySol not working on WinXP, SP2 In-Reply-To: References: Message-ID: Ivan Van Laningham wrote: > Hi All-- > I've been using PySol-4.40 for years, because that was the last Windows > installer version I could find. My wife's been using it for almost the > same length of time. That version's worked just fine on W98, W98SE, W2K > (server included), and WinXP SP1. > > I upgraded to SP2 and pysol fails silently. Running 'python pysol.pyw' > gives me this error: > > Traceback (most recent call last): > > File "pysol.pyw", line 64, in ? > > imp.load_compiled("__main__", sys.argv[0]) > > ImportError: Bad magic number in C:\Program > Files\PySol-4.40\data\pysol.pyc Are you sure you're using the Python version (2.3, 2.4 etc) that the Pysol .pyw files were compiled for? As I understand it, that's what the "magic number" is - a versioning number for the .pyc/.pyw files which changes when the Python version is upped. If you had multiple versions of Python installed on your machine, upgrading to SP2 might have muddled your file associations. From newsgroups at jhrothjr.com Sun Jun 26 01:49:40 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 25 Jun 2005 23:49:40 -0600 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> Message-ID: <11bsgfo2r2oei42@news.supernews.com> "Steven D'Aprano" wrote in message news:pan.2005.06.26.05.30.58.959708 at REMOVETHIScyber.com.au... > On Sat, 25 Jun 2005 19:31:20 -0600, John Roth wrote: > >> >> "Dave Benjamin" wrote in message >> news:slrndbrse5.71d.ramen at lackingtalent.com... >>> Guido gave a good, long interview, available at IT Conversations, as was >>> recently announced by Dr. Dobb's Python-URL! The audio clips are >>> available >> >> [snip] >> >>> - Java: the usual static vs. dynamic, static analysis vs. unit testing >>> arguments. Guido says that there's such a small amount of problems >>> that >>> can be caught at compile time, and even the smallest amount of unit >>> testing would also catch these problems. "The blindness of that >>> [static] >>> position... escapes me." >> >> Three years ago, this was a viable arguement. Two years ago, it was >> beginning to show difficulties. Today anyone who makes it can be >> accused of having their head in the sand [1]. >> >> What's being ignored is that type information is useful for other things >> than compile type checking. The major case in point is the way IDEs >> such as IntelliJ and Eclipse use type information to do refactoring, code >> completion and eventually numerous other things. A Java programmer >> using IntelliJ or Eclipse can eliminate the advantage that Python >> used to have, and possibly even pull ahead. > > I haven't used IntelliJ or Eclipse, so I guess I'll have to take your word > for how wonderful they are. You might want to look at something outside of Python. The world changes, and if you keep your eyes closed, you might not notice it changing until it rolls over you. > [snip] >> I'll throw out one very simple example in the string library. The >> index() and find() methods, and their variants, suffer from a bad case >> of non-obviousness inherited from the C library. > > It must be an very bad case of non-obviousness indeed, because it isn't > obvious to me at all what particular bit of non-obviousness it is that > you are referring to. The result of find() cannot be used cleanly in an if statement; you need to compare it to -1. This is not obvious to a novice, and is a fertile source of mistakes. It's an irregularity that has to be checked for. > >> A very simple >> replacement would fix this. >> >> -------------------------------- >> >> findall([maxfind,] sub, [start, [end]]) >> >> findall returns a list (possibly a tuple) of the beginning index of each >> substring which matches sub. If there are no matches, an empty list is >> returned. At most maxfind indexes are returned. start and end have the >> same meaning as in the existing find and index methods. > > Am I the only one who has reservations about having to build a list of all > the matches before doing anything with them? You don't have to build a list of all the matches. First, that's what the maxfind parameter is all about, second, as I said below, it could be implemented as an iterator. I'd expect that to happen if it was going to be used in a for statement. > > s = "a" * 10000000 # 10 MB of data to search > L = s.findall("a") # lots of matches means L is very large > > or imagine a more complex case where I have to programmatically change my > search string as I go. I might not know how many matches I need until I > have found them and can analyse the text around the match. > > Seems to me that rather than having to find all matches regardless of what > you actually want, it would be better to turn find into a generator. Then > findall becomes list(find) and you still have the flexibility of finding > matches one at a time. See below. I covered it. >> This version works intuitively with if statements (an empty list is >> false), goes directly into for statements, can be implemented as an >> iterator, and is only less efficient by a constant (creation of the >> list) if the maxfind parameter is used. It never throws an exception >> (unless the parameter list has the wrong types). Its an example of a >> method that can be used cleanly with a type inferencer, while the index >> and find methods cannot. > > Er, how does that last one work? How can findall be used cleanly? Why > can't find? findall() has a definite type: a list of integers, specifically a list of integers that are legitimate indexes into a specific string. The result of find() does not have this property: it can be an integer that is an index into the string, or it can be a -1. Index can either return an index into the string, or it can throw an exception. Both of these are complex result types that hinder further type inference. John Roth > > > -- > Steven. > From fredrik at pythonware.com Wed Jun 15 08:04:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Jun 2005 14:04:46 +0200 Subject: Tkinter question References: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> Message-ID: Nicholas.Vaidyanathan at aps.com wrote: > I'm sure there must be a way to do this, but I can't figure it out for > the life of me... I'm writing a program where I would like to use a > button's text field as part of an if statement. I set up my button like > this: > > i = [ "7", "8","9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"] > t = 0 #iterator through the sequence > > for x in range(4): > for y in range(4): > self.buttonx = Button(self, text = "%s" %i[t], width=10, command = self.pressed) > self.buttonx.grid( row=x+1, column = y, sticky = W+E+S) > t+=1 > > What I would like to do is is check which buttons' text values are < digits, and if the text is, I would like to append the number to a > label. But: > > if(self.buttonx.title.isdigit): > > Doesn't work. How do I access the button's text field? note that you're assigning all buttons to the same instance variable, so even if the above did work, it would always return a plus. since the command callback doesn't know what widget it was called from, you need to create a separate callback for each widget. here's one way to do that: for x in range(4): for y in range(4): text = i[t] # label text def callback(): self.pressed(text) buttonx = Button(self, text=text, width=10, command=callback) buttonx.grid( row=x+1, column = y, sticky = W+E+S) the "def callback" statement creates a small dispatcher which calls your original key handler with the widget's text as the argument. def pressed(self, text): print "PRESSED", text From erinhouston at gmail.com Tue Jun 14 12:43:45 2005 From: erinhouston at gmail.com (erinhouston at gmail.com) Date: 14 Jun 2005 09:43:45 -0700 Subject: Using PAMIE to upload and download files...is it possible? In-Reply-To: <1118759561.268065.320510@g43g2000cwa.googlegroups.com> References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> <1118256512.379934.292780@z14g2000cwz.googlegroups.com> <1118427453.108199.135860@g14g2000cwa.googlegroups.com> <1118435301.748143.288780@g14g2000cwa.googlegroups.com> <1118759561.268065.320510@g43g2000cwa.googlegroups.com> Message-ID: <1118767425.720972.242180@g44g2000cwa.googlegroups.com> So here is a class that should do what you want. I don't use pamie we use a in house python ie driver. But it has the same problem. Here is a class that should do what you want. import winGuiAuto import threading class SaveAsDocDialog (threading.Thread): ....'''Some Internet Explorer dialog windows will halt all other ....IE functionality until they are populated. This class is ....used to handle these dialog windows. ....This little class saves a document to the pc''' ....def __init__(self, docPath): ........'''The constructor method.''' ........threading.Thread.__init__(self) ........self.windowName = "Save As" ........self.hwnd = None ........self.document = docPath ....def fetchWindow (self,attempts=20): ........'''Grab the handle of the dialog window''' ........tries = 0 ........while tries References: <42aeeef3$1_1@newspeer2.tds.net> <42AF02BD.9080809@bellsouth.net> Message-ID: <4q2dneJoafZNljLfRVn-sQ@powergate.ca> Peter Hansen wrote: > James Tanis wrote: > >> I may be wrong here, but shouldn't you just use a stack, or in other >> words, use the list as a stack and just pop the data off the top. I >> believe there is a method pop() already supplied for you. > > Just a note on terminology here. I believe the word "stack" generally > refers to a LIFO (last-in first-out) structure, not what the OP needs > which is a FIFO (first-in first-out). Or, perhaps he doesn't need either... as Kent points out (I should have read his post before replying above) this isn't what I think James and I both thought it was but something a little less usual... -Peter From hesterumpe at tiscali.dk Thu Jun 9 17:10:26 2005 From: hesterumpe at tiscali.dk (Bue Krogh Vedel-Larsen) Date: Thu, 09 Jun 2005 21:10:26 GMT Subject: Custom type: PyObject_IS_GC access violation Message-ID: I'm extending my C++ app by embedding Python 2.4.1 in it. The app is multithreaded and split into several DLL's. The main EXE calls Py_Initialize and Py_Finalize and each DLL gets a seperate interpreter with Py_NewInterpreter. The problem comes when I try to add a new type. I've been following the "Extending and Embedding the Python Interpreter" tutorial. I've created a PyTypeObject struct like so: struct SA_PyVector { PyObject_HEAD int herman; }; static PyTypeObject SA_PyVector_Type = { PyObject_HEAD_INIT( 0 ) 0, "vector.Vector", sizeof(SA_PyVector), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT, "Vector objects", }; But if I call SA_PyVector_Type.tp_new = PyType_GenericNew; PyType_Ready( &SA_PyVector_Type ); then, when Py_Finalize is called, PyObject_IS_GC(op) in visit_decref() in gcmodule.c causes an access violation. If I don't call PyType_Ready, then the access violation doesn't occure, but then the type can't be used... So, the question is, does anyone have any idea about what could be causing this? /Bue From uche.ogbuji at gmail.com Sat Jun 4 23:29:23 2005 From: uche.ogbuji at gmail.com (uche.ogbuji at gmail.com) Date: 4 Jun 2005 20:29:23 -0700 Subject: Newbie Python & XML In-Reply-To: <1117899758.058056.291670@g47g2000cwa.googlegroups.com> References: <1117899758.058056.291670@g47g2000cwa.googlegroups.com> Message-ID: <1117942163.758775.113800@g49g2000cwa.googlegroups.com> "I have a situation at work. Will be receiving XML file which contains quote information for car insurance. I need to translate this file into a flat comma delimited file which will be imported into a software package. Each XML file I receive will contain information on one quote only. I have documentation on layout of flat file and examples of XML file (lot of fields but only container tags and field tags no DTD's,look easy enough). I am just starting to learn python and have never had to work with XML files before. Working in MS Windows environment. I have Python 2.4 with win32 extensions. " Sounds like the sort of thing I and others have done very easily with Amara: http://www.xml.com/pub/a/2005/01/19/amara.html Overall, if you're new to Python and XML, here are some resources: http://www.xml.com/pub/at/24 http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/general-section -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://fourthought.com http://copia.ogbuji.net http://4Suite.org Use CSS to display XML, part 2 - http://www-128.ibm.com/developerworks/edu/x-dw-x-xmlcss2-i.html XML Output with 4Suite & Amara - http://www.xml.com/pub/a/2005/04/20/py-xml.htmlUse XSLT to prepare XML for import into OpenOffice Calc - http://www.ibm.com/developerworks/xml/library/x-oocalc/ Schema standardization for top-down semantic transparency - http://www-128.ibm.com/developerworks/xml/library/x-think31.html From cjbottaro at alumni.cs.utexas.edu Tue Jun 7 13:54:52 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Tue, 07 Jun 2005 12:54:52 -0500 Subject: DB API 2.0 and transactions Message-ID: Hi, Why is there no support for explicit transactions in the DB API? I mean like transaction() to start the trans and commit() and rollback() would end the trans or something. The reason why I ask is because I wrote a daemon that interacts with a Postgres DB. The value of CURRENT_TIMESTAMP according to Postgres is NOT the actual walltime, but the walltime when the current transaction started. This gets weird when using the Python DB API to interact with Postgres because a transaction gets started in 3 places: connection, commit, rollback. So consider the daemon: [pseudo code] connect # begin trans at 12:00 sleep waiting # lets say 15 mins wake up put entry in db using CURRENT_TIMESTAMP # oops [/code] Oops, the CURRENT_TIMESTAMP evaluates to 12:00, not 12:15. Now I know there are ways around this... 1) In Postgres, you can get the walltime and cast it to a timestamp. 2) In Python, you can just do an empty commit in order to "manually" start a new transaction. I just think its a bit weird because this bit me in the butt for quite a while and this didn't happen when doing the same thing in other langs. Anyone have any opinions on this? From ajikoe at gmail.com Wed Jun 8 04:11:50 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 8 Jun 2005 01:11:50 -0700 Subject: circular import Module Message-ID: <1118218310.415692.194910@f14g2000cwb.googlegroups.com> Hello, I have two modules (file1.py and file2.py) Is that ok in python (without any weird implication) if my module import each other. I mean in module file1.py there exist command import file2 and in module file2.py there exist command import file1? This is not working in C#. pujo From tomlis at notmyisp.pl Tue Jun 14 06:14:31 2005 From: tomlis at notmyisp.pl (Tomasz Lisowski) Date: Tue, 14 Jun 2005 12:14:31 +0200 Subject: Where is Word? In-Reply-To: References: Message-ID: <42aeae07@news.home.net.pl> > Unfortunately, I need to open/edit a (temporary) text file with Word, and > those are opened by default with UltraEdit (or Notepad or..). Thanks for the > tip, though. > > Anything else? Do I need to read the registry? > > g You may try to launch Word as a COM object and control it directly from Python using the COM object methods. This does not require you to know the application's path, only the COM object identifier. TLis From david.tolpin at gmail.com Wed Jun 15 17:46:01 2005 From: david.tolpin at gmail.com (david.tolpin at gmail.com) Date: 15 Jun 2005 14:46:01 -0700 Subject: What is different with Python ? (OT I guess) In-Reply-To: <42aeeee1$1@nntp0.pdx.net> References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <42AED7B3.8060009@carmen.se> <42aeeee1$1@nntp0.pdx.net> Message-ID: <1118871961.884848.37900@g49g2000cwa.googlegroups.com> > > Oh well, I guess it's a bit late to try to rename the Computer > > Science discipline now. > The best I've heard is "Informatics" -- I have a vague impression > that this is a more European name for the field. The word "Informatics" had been invented by a Soviet computer scientist Andrey Ershov several decades ago as a name for his view on Information Theory. In Russian, it is ???????????, Informatika, by analogy with Mathematics, ??????????. It is widely used ever since both in russian-language literature and in many other languages and countries. It is a better name than either Information Theory or Computer Science for the discipline. From paddy3118 at netscape.net Thu Jun 30 02:44:24 2005 From: paddy3118 at netscape.net (Paddy) Date: 29 Jun 2005 23:44:24 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: <1120103487.450255.18800@g44g2000cwa.googlegroups.com> Message-ID: <1120113864.896174.231700@g47g2000cwa.googlegroups.com> Sadly, its not a solution that I'm after, but a particular toolkit that can be used for solving that type of problem. - Pad. From bdesth.quelquechose at free.quelquepart.fr Wed Jun 1 09:01:27 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 01 Jun 2005 15:01:27 +0200 Subject: cgi help In-Reply-To: <1117581222.027646.25710@o13g2000cwo.googlegroups.com> References: <1117581222.027646.25710@o13g2000cwo.googlegroups.com> Message-ID: <429dac47$0$28450$636a15ce@news.free.fr> nephish a ?crit : > Hey there, > i am trying to write an online application using the cgi module. > what i want to do is have an html form display a drop-down list and > have the values of that list be the lines of text written in a file. Simplest, Q&D solution : 1/ open the file for reading 2/ print out the beginning of the html tags for the dropdown (hint: in html, it's ) 3/ for each line in the file, print out the html tags and the line 4/ print out the end of the html 5/ close the file which gives (first try, Q&D, naive implementation, no error handling, etc: f = open("myfile.txt") print "" for line in f: print "" % line.strip() print "" f.close() Now there may be some conditions we want to handle: file doesnt exist or is not readable, file is empty, a line is empty, etc. A second try could be like: try: f = open("myfile.txt") except IOError, e: # TODO : handle error. in the meantime: print "could not open myfile.txt for reading : %s" % e sys.exit(1) else: print "" for line in f: if line.strip(): print "" % line.strip() print "" f.close() Well... This does not handle all potential problems, and we begin to have useless repetitions (here the 'line.strip()' expression). We need to stop and think a little bit. This snippet tries to do too many things at once: reading a file line by line, and printing the html for a select. Since we won't use selects for huge lists (for obvious usability reasons), we can assume that working with an in-memory list will be ok. So we could split this in two parts: one that read the file and returns a cleaned-up, ready to use list, and one that output the needed html: # first part try: f = open("myfile.txt") except IOError, e: # TODO : handle error. in the meantime: print "could not open myfile.txt for reading : %s" % e sys.exit(1) else: options = filter(None, [line.strip() for line in f]) f.close() # second part: if options: print "" for line in options: print "" % line print "" else: # Err ? what should we do here ? print "no selectable option here" Hmm... Better, but still not ok. We can already guess that both parts can be useful indepently of each other, in in other contexts. So why not making this a little be generic ? def listFrom(openedFile): return filter(None, [line.strip() for line in openedFile]) def printSelect(name, options): print "" % name for line in options: print "" % line print "" def printSelectFromFile(name, path): try: f = open(path) except IOError, e: # TODO : handle error. in the meantime: print "could not open %s for reading : %s" % (path, e) sys.exit(1) else: options = listFrom(f) f.close() if options: printDropdownList(name, options) else: print "no selectable option here" Well, this could of course be much more improved, but this will depend on stuffs specific to your application, so I'll leave it up to you... > this would be updated almost every time the site is visited. Err... Better take care of concurrent access... > i have been sucessful in writing text to a file from an html form. but > i need to access this so it can be selected. > is there a way to do this? i have found limited info on how to really > use the cgi module. AFAICT, there's nothing related to the cgi module in your problem. HTH Bruno From dalke at dalkescientific.com Thu Jun 9 12:51:30 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 09 Jun 2005 16:51:30 GMT Subject: tail -f sys.stdin References: Message-ID: garabik: > what about: > > for line in sys.stdin: > process(line) This does not meet the OP's requirement, which was >> I'd like to write a prog which reads one line at a time on its sys.stdin >> and immediately processes it. >> If there are'nt any new lines wait (block on input). It's a subtle difference. The implementation of iter(file) reads a block of data at a time and breaks that into lines, along with the logic to read another block as needed. If there isn't yet enough data for the block then Python will sit there waiting. The OP already found the right solution which is to call the "readline()" method. Compare the timestamps in the following % ( echo "a" ; sleep 2 ; echo "b" ) | python -c "import sys, time\ for line in sys.stdin:\ print time.time(), repr(line)" 1118335675.45 'a\n' 1118335675.45 'b\n' % ( echo "a" ; sleep 2 ; echo "b" ) | python -c "import sys, time\ while 1:\ line = sys.stdin.readline()\ if not line: break \ print time.time(), repr(line)" 1118335678.56 'a\n' 1118335680.28 'b\n' % Andrew dalke at dalkescientific.com From roccomoretti at hotpop.com Fri Jun 24 11:22:03 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 24 Jun 2005 10:22:03 -0500 Subject: Thanks for PIL (and other stuff) In-Reply-To: <1119579123.611615.197720@g14g2000cwa.googlegroups.com> References: <1119579123.611615.197720@g14g2000cwa.googlegroups.com> Message-ID: jean-marc wrote: > PS If I knew that Python had a anniversary date, I'd also write to > thanks our BDFL (and authors)! But no such luck, so I'm restaining > myself! > ;-)) From the FAQ: > Here's a very brief summary of what started it all, written by Guido van Rossum: > > > > During the 1989 Christmas holidays, I had a lot of time on my hand, so I decided to give it a try. During the next year, while still mostly working on it in my own time, Python was used in the Amoeba project with increasing success, and the feedback from colleagues made me add many early improvements. > > In February 1991, after just over a year of development, I decided to post to USENET. The rest is in the Misc/HISTORY file. Misc/HISTORY notes the source was uploaded to alt.sources Google Searching alt.sources gives a posting date of Feb 20 1991, 11:22 am for the message "Python 0.9.1 part 01/21", and the rest of the posts are spread out over 19-21 Feb 1991, according to Google. The text description in the body of the message gives a date of 19 February 1991. If you're looking for an official "Birthday" of Python, you probably couldn't do much better than 19 February 1991. (Happy 14th & 1/3ish Birthday Python!) From richie at entrian.com Thu Jun 30 06:01:04 2005 From: richie at entrian.com (Richie Hindle) Date: Thu, 30 Jun 2005 11:01:04 +0100 Subject: MS Compiler to build Python 2.3 extension In-Reply-To: <1120118453.192290.32170@g44g2000cwa.googlegroups.com> References: <1120054137.471983.240320@o13g2000cwo.googlegroups.com> <1120118453.192290.32170@g44g2000cwa.googlegroups.com> Message-ID: <2jg7c1tpudje7t6dnro0820rhihbu68b15@4ax.com> [woodsplitter] > MS Visual C++ 6 is indeed the compiler that the python.org > distributions are built with Just to add back some context for people not following the thread: this is Python 2.3 we're talking about. 2.4 is built with Visual Studio.NET. > but MinGW works fine too. In fact, the > code generated by MinGW-GCC 3.4.4 outpaces that generated by MSVC++ 6.0 > by a considerable margin in some of my performance-critical extensions, > and the size of the binaries is often smaller. Interesting! -- Richie Hindle richie at entrian.com From steven.bethard at gmail.com Sat Jun 4 11:49:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 09:49:07 -0600 Subject: idiom for constructor? In-Reply-To: <8764wue8t0.fsf@hector.domek> References: <1117648259.190124.76800@f14g2000cwb.googlegroups.com> <87acm6e9ei.fsf@hector.domek> <8764wue8t0.fsf@hector.domek> Message-ID: Peter Dembinski wrote: >class A: > def __init__(self, a, b, c, d): > initial = {'a' : a, 'b' : b, 'c' : c, 'd' : d} > for param in initial.keys(): > exec "self.%s = initial['%s']" % (param, param) This is not a good use case for exec. Use setattr: for param in initial: setattr(self, param, initial[param]) Or better yet, just update the instance dict: self.__dict__.update(initial) But this misses the OP's point. The issues was that the OP didn't want to write a, b, c and d again. Not only does this proposal make you write them again, it makes you write them again twice! STeVe From alexrait at gmail.com Sun Jun 12 15:02:25 2005 From: alexrait at gmail.com (alexrait1) Date: 12 Jun 2005 12:02:25 -0700 Subject: searching for IDE Message-ID: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> I need an IDE for python that has the ability to show the filds of a class when I write "." Just the way it works in eclipse/JBuilder with java or visual studio with c++ For now I treid eric3 and IDLE they don't do this... From wweston at att.net Sat Jun 4 09:52:30 2005 From: wweston at att.net (wes weston) Date: Sat, 04 Jun 2005 13:52:30 GMT Subject: Walking through a mysql db In-Reply-To: References: Message-ID: Jeff Elkins wrote: > I'm writing a small wxpython app to display and update a dataset. So far, I > get the first record for display: > > try: > cursor = conn.cursor () > cursor.execute ("SELECT * FROM dataset") > item = cursor.fetchone () > > Now, how do I step through the dataset one row at a time? My form has 'next' > and 'back' buttons, and I'd like them to step forward or back, fetching the > appropriate row in the table. I've tried setting cursor.rownumber by > incrementing it prior to the fetchone() w/o effect. > > Thanks for any pointers. > > Jeff Elkins > > > > > > Jeff, You just check for a fetchone return of None. "list" is a list of tuples here. ... cursor.execute( sql ) list = [] while 1: row = cursor.fetchone() if not row: break list.append(row) ... wes From timr at probo.com Sun Jun 12 21:59:24 2005 From: timr at probo.com (Tim Roberts) Date: Sun, 12 Jun 2005 18:59:24 -0700 Subject: how to operate the excel by python? References: <1118375729.127295.90870@g43g2000cwa.googlegroups.com> <42AB8CEA.50606@lexicon.net> Message-ID: <92qpa1pr5g8qvn59uol0984bqnmvmdvkvd@4ax.com> John Machin wrote: >Rune Strand wrote: >> The key is Python for Windows : >> http://starship.python.net/crew/mhammond/win32/ >> >> See here for an Excel dispatch example: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325735 >> >> When doing such operations, I generally save all the Excel files to CSV >> files and do the operations on them using the csv module. >> > >Problems with that approach: > >1. Unfortunately, "save as CSV" is very much a WYSIWYG operation. If the >"number formats" are not sensible, loss of information can result. This is a real problem. US postal codes are a particular nasty issue. The value "01234", for example, will be imported into Excel as "1234". -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From peter at engcorp.com Tue Jun 21 11:07:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Jun 2005 11:07:35 -0400 Subject: asynchronous comunication, wxPython and threads. In-Reply-To: References: Message-ID: Zunbeltz Izaola wrote: > I'm developing a GUI program (wxPython). This program has to comunicate > (TCP) whit other program that controls a laboratory machine to do a > measurement. I have a dialog box, wiht two buttoms "Start measurement" and > "Stop". "Start" executes a function that do the measurement in the > following way. > > 1) My program send a socket. Please clarify: what does this mean? "Sending a socket" is not a usual way to describe TCP communications. Do you mean your program _opens_ a socket (like a phone connection) and _sends_ some data, then waits for data to be received from the other end? Or are you (as it almost sounds) opening and closing sockets repeatedly for each part of the conversation? > 2) The other program recives it an send confirmation. > 3) My program waits for the confirmation and send the next when > confirmation received. > > This comunication is done in a new thread not to frezee the GUI. > The problem is that when "Stop" is done (it kills the thread) some > confirmation sockets are mixed (are not receibed in the correct order > although i use tcp). I think you are using the term "socket" where you should be using "packet". A socket is the virtual connection created by TCP. A packet is either a single blob of data sent by the TCP code in the operating system, or perhaps a single chunk of your own data. If you are using a single TCP socket to send multiple packets, and you are talking about those packets being sent out of order, it's very unlikely and there must be another explanation. TCP _is_ reliable, and you will not get data out of order unless you do something to screw things up, for example by creating a race condition by doing multithreaded code incorrectly. > I have been told not to do comunication in a new thread; instead, I should > use asyncronus comunication. Some people advise that, but there's really nothing *wrong* with doing this in a second thread, and in fact I do similar things all the time with no ill effects. While async frameworks _can_ make this easier, they could also make it harder (at least for a while) as you adjust your brain to the new approach. Furthermore, at least in the case of wxPython and Twisted (on Windows) there can be problems integrating the two loops. I don't believe the latest Twisted claims to have fully solved the problems involved yet, so you might still be required to have a second thread for the TCP stuff. > What module should i use, asyncore, asynchat, twisted,(anohter) > How can i implement this asynchronous comunication and the ability to > stop this long run funciton (the measurement can take hours or days, so > i need a way to stop it)? I use a non-blocking socket and select() calls in my thread, and communicate with the GUI thread using appropriate Queue objects and calls to PostEvent() (or CallAfter()) on the wx side of things. It's pretty straightforward, so if you post a small piece of your application which reproduces the problem it shouldn't be hard for someone here to help you fix it. > Can asynchronous comunication garantee that the confirmation socket will > arrive in the correct order (one after each sended socket)? No more so than using threads, unless your problem is caused by the threads themselves (as I suggested above) in which case it might be easier to just fix the problem. -Peter From mfurmaniuk at gmail.com Mon Jun 6 16:07:17 2005 From: mfurmaniuk at gmail.com (Pykid) Date: 6 Jun 2005 13:07:17 -0700 Subject: EnumKey vs EnumValue Message-ID: <1118088437.203560.20220@f14g2000cwb.googlegroups.com> I'm having trouble getting any responses back from the following snippet, where I am just trying to read some data from the Windows Registry. I intend to do a little bit more with this but will work on that later, but I think I can get more data back from EnumValue, I'd like to see the differences between them. I am running Python 2.3 on XP and can get a response from EnumKey, but EnumValue returns nothing at all; the key listing even returns 0 keys when it prints out the status. But EnumKey returns the right number and even prints out the keys I expect, I copied some of this from the Cookbook and can't tell what might be the problem. Thanks for any help. - M ------------------------------------- from _winreg import * findkey = raw_input("What key do you want to look for? ") key = "SOFTWARE\\"+findkey machine = ConnectRegistry(None,HKEY_LOCAL_MACHINE) regpath = OpenKey(machine,key) print "Looking for",key for i in range(25): try: regEndeca = EnumKey(regpath,i) print regEndeca except EnvironmentError: print "There are", i,"keys under",key break print "That was using EnumKey." for j in range(25): try: regstr,value,type = EnumValue(regpath,j) print regstr,value,type except EnvironmentError: print "There are", j,"keys under",key break print "That was using EnumValue." From claudio.grondi at freenet.de Fri Jun 24 07:46:32 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 24 Jun 2005 11:46:32 -0000 Subject: Favorite non-python language trick? References: Message-ID: <3i232vFj0b57U1@individual.net> > And you can do block comments with --[[ and ---]]. I am very happy not to have such "tricks" in Python. Any other (useful) suggestions? Claudio "Joseph Garvin" schrieb im Newsbeitrag news:mailman.837.1119596150.10512.python-list at python.org... > As someone who learned C first, when I came to Python everytime I read > about a new feature it was like, "Whoa! I can do that?!" Slicing, dir(), > getattr/setattr, the % operator, all of this was very different from C. > > I'm curious -- what is everyone's favorite trick from a non-python > language? And -- why isn't it in Python? > > Here's my current candidate: > > So the other day I was looking at the language Lua. In Lua, you make a > line a comment with two dashes: > > -- hey, this is a comment. > > And you can do block comments with --[[ and ---]]. > > --[[ > hey > this > is > a > big > comment > --]] > > This syntax lets you do a nifty trick, where you can add or subtract a > third dash to change whether or not code runs: > > --This code won't run because it's in a comment block > --[[ > print(10) > --]] > > --This code will, because the first two dashes make the rest a comment, > breaking the block > ---[[ > print(10) > --]] > > So you can change whether or not code is commented out just by adding a > dash. This is much nicer than in C or Python having to get rid of """ or > /* and */. Of course, the IDE can compensate. But it's still neat :) From adsheehan at eircom.net Tue Jun 7 11:12:06 2005 From: adsheehan at eircom.net (adsheehan at eircom.net) Date: 7 Jun 2005 08:12:06 -0700 Subject: Embedding Python in Multi-threading App. Any Guidelines, Hints, Recipes ?? Message-ID: <1118157126.875282.103600@z14g2000cwz.googlegroups.com> Hi, I am embedding Python into a multi-threaded application running on Solaris. Python will enable end users to customize and re-program many aspects of the application. I expect that the C++ application will be natively multi-threaded and will embed multiple Python sub-interpreters. Called Python scripts may in turn call back into the C++ application via SWIG wrappers of C++ objects. I need advice and/or pointers to relevant documentation on the subject if available please. In particular, I need advice on the necessary housekeeping (set/reset of GIL, PyThreadStates, PyInterpreterStates etc etc) to invoke a sub-interpreter from a native thread. A native thread may call a number of sub-interpreters in sequence or recursively (due to call backs) and I cannot find specific information on this subject area. Many thanks in advance. Alan From roccomoretti at hotpop.com Tue Jun 28 19:41:18 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 28 Jun 2005 18:41:18 -0500 Subject: Which kid's beginners programming - Python or Forth? In-Reply-To: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: BORT wrote: > I am toying with the idea of teaching my ten year old a little about > programming. I started my search with something like "best FREE > programming language for kids." After MUCH clicking and high-level > scanning, I am looking at Python and Forth. Both have advocates that > say each is a great approach to learning computers. Call me biased, but I'd recommend Python, and it all comes down to a single concept: Transferability. As others have mentioned, Forth programming is in somewhat of it's own class. It's not really imperative, object oriented, or declarative. It's based on an interesting, but rarely used, principle of stack programing. Great for someone who is expanding their horizons, but not a lot of value for a beginning programmer who might want to branch out to C/Visual Basic/Java/etc. Also, due to the stack-based nature of the beast, the base way of specifying mathematical operations doesn't transfer to/from elsewhere, unless you're talking about old HP calculators. Python uses the standard mathematical notation, and even uses mathematical precedents (i.e. multiplication before division). So for Math you'd do something like: y = b + mx + cx^2 (Where ^2 is a superscript 2) For Python it would be: y = b + m*x + c*x**2 IIRC, for Forth it would be something like (please excuse the mistakes in operator notation): x 2 ^ c * m x * + b + 'y' setvar Where you read from left to right, and imagine pushing items onto a stack, and when you encounter an operator, you pop the appropriate number of items, act on them, and push the result back onto the stack. Granted, you can get Forth dialects with the ability to do infix (mathematical) notation, but that leads to another transferability issue, that between interpreters. There is one "official" Python interpreter, and the developers work dang hard to make sure it runs on every commonly used platform. The other interpreters are usually special purpose, and tend to be up front about where they differ from the "official" Python. Thus, if you see Python code somewhere, it is highly likely it will run on your Python interpreter Forth, as it has been around much longer, is a much more fragmented community, with many more interpreters. What works on one may not work on another, and a particular interpreter is likely to be available only for a single platform. With Forth it is *very* easy to extend the language, and so an interpreter-specific piece of code that someone posts may not work for you on your interpreter, especially if you're using a free interpreter for Windows, which tends to be the bastard step child of free stuff. There are ANS and IEEE standards for Forth, but official standards tend to leave things implementation dependent, especially in platform specific things like file access. To further compound the issue, a Forth system tends to be self contained and insular - interaction with the surrounding environment may be minimal at best. Python, where possible, tries to shield the user from platform specifics, while still allowing full access to the environment. There are a number of Python bindings to C libraries which give near complete control to the desktop/screen/sound system, etc. Forth-bound libraries will likely be rarer, and again, interpreter specific. It's been quite some time since I've looked at Forth, and the reference material that I used then was probably outdated anyway, so someone with more recent experience can correct me if I'm wrong. However, I would think it's highly likely that the experience you receive with Forth is going to depend heavily on which interpreter you choose to use. P.S. Any 10 year old getting into programing would likely love a library like PyGame (www.pygame.org) - I'd suggest seeing if the Forth you're considering has something similar before deciding. From grante at visi.com Tue Jun 28 16:25:47 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 28 Jun 2005 20:25:47 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c3c3uipbjcg58@corp.supernews.com> Message-ID: <11c3cib5nv1d65a@corp.supernews.com> On 2005-06-28, Jarek Zgoda wrote: > Grant Edwards napisa?(a): > >>>To be blunt, I have no idea what this has to do with Python. >> >> Monty Python was mostly Brits? > > Wasn't they all Brits? Nope. Terry Gilliam was from Minneapolis. -- Grant Edwards grante Yow! RELAX!!... This at is gonna be a HEALING visi.com EXPERIENCE!! Besides, I work for DING DONGS! From wookiz at hotmail.com Thu Jun 9 08:00:36 2005 From: wookiz at hotmail.com (wooks) Date: 9 Jun 2005 05:00:36 -0700 Subject: Python Developers Handbook Message-ID: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> http://cgi.ebay.co.uk/ws/eBayISAPI.dll?ViewItem&item=5206943952 From majromax at gmail.com Mon Jun 13 14:55:31 2005 From: majromax at gmail.com (Christopher Subich) Date: 13 Jun 2005 11:55:31 -0700 Subject: Tkinter app structure References: Message-ID: <1118688931.354852.86340@g43g2000cwa.googlegroups.com> Richard Lewis wrote: > Hi there, > > I've just started my first project with Tkinter. > This set up should allow me to be able to access main.data and main.root > from the commands.py module and the command callback functions (defined > in commands.py) from mainwindow.py. <...> > Whats going wrong? Is it a 'circular import'? Is there a better way that > I could organise these modules? Yes, this looks like a circular import to me. Remember, though, that an import statement in Python isn't completely analagous to a #include statement in C; because of dynamic typing and the general guideline of duckitude ("if it walks like a duck and quacks like a duck..."), you usually don't /need/ to have circular imports. With the presumption that data = Database() is a mutable object, in that you interact with it normally and don't reassign it anywhere in your program, why not just pass data as a parameter to MainWindow.__init__? Likewise, MainWindow can call commands with root/data as parameters -- you could even organize your commands into an instantiated class, and have the CommandClass take both of these as __init__ arguments. In the program (MUD Client) that I'm working on, I have a vaguely similar dependency between interface-agnostic backend code and the in-development TKinter interface; by wrapping everything except main() and a few constants inside instantiated classes, I think I've mostly avoided circular imports. If you really, truly need data to be a global variable, you could possibly put it inside its own module, and instantiate it via data_module.data = Database() from main. But that's really ugly, and I'm not 100% sure that it'd work -- I've never had need to try it, and am writing this off-the-cuff. But take this advice all with a lagish grain of iodized NaCl, since I'm a rank newbie at Python. From aqua_azul_2000 at yahoo.com.mx Tue Jun 14 12:39:09 2005 From: aqua_azul_2000 at yahoo.com.mx (Vero) Date: Tue, 14 Jun 2005 11:39:09 -0500 (CDT) Subject: Dynamic class inheritance && something else Message-ID: <20050614163909.19881.qmail@web61025.mail.yahoo.com> Hi. My name is Veronica, I am a master student at UNAM. I am working on something related to Artificial Inteligence and I have been looking for the most appropriated programming language to implement my algorithms. I found python to be very close to what I need, but there are still a couple of details that I haven't been able to solve. First, (and most important) I would like to be able to dynamically modify the classes from which a class inherits. I haven't found any way to do it with the language as it is. If there is a way, any suggestion will be truly appreciated. If I had to modify the source code to achieve this, I hope that you could give me some hints; I have an idea of how something like this could be achieved but since I don't know deeply the python sourcode I could get lost. Second, since my program will be modifying classes during run time, I would like to have a way to write on a file the python code that would have defined the class with the functions and attributes as they were left, just as if it had been writen like that at the very begining. I need it to be python code because I will be using that latter. Maybe I will have to solve this second problem by myself but I just wrote in case anybody had a good idea. Thank you very much for your help. Vero La sociedad es inherentemente democr?tica: la mayor?a decide si pensar por si misma o si dejar que alguien m?s les diga qu? pensar. http://mx.geocities.com/aqua_azul_2000/ __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! Reg?strate ya - http://correo.yahoo.com.mx/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From multiethniccommunities at yahoo.com Thu Jun 23 20:30:43 2005 From: multiethniccommunities at yahoo.com (Jenta) Date: Thu, 23 Jun 2005 20:30:43 -0400 Subject: A World Beyond Capitalism 2005, References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> Message-ID: <3cacc254a9d2010cbf5298fc3bd955b0@localhost.talkaboutprogramming.com> Interesting. To anyone who didn't want to know about the conference, my apologies. To everyone who was supportive, thanks. It is appreciated, because like many activists, many python activists have skills which are able to network people worldwide. No matter who you are, thank you for working for a better world, Love And Solidarity Worldwide, Jenta, Volunteer for the AWBC 2005 From tim.golden at viacom-outdoor.co.uk Thu Jun 30 09:19:45 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Jun 2005 14:19:45 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB960@vogbs009.gb.vo.local> [Greg Miller] | | Thanks for the information, I stumbled across that page yesterday. It | seems all the problems with this are solved. The executable | works just | like the Python version. Now I have to come up with an algorithm to | parse through the output data to come up with the version numbers. Just in case you haven't managed it (and because I fancied the challenge), try the code below: (most information from a post by Roger Upole) import win32api lo = win32api.LOWORD hi = win32api.HIWORD def get_version_number (filename): info = win32api.GetFileVersionInfo (filename, "\\") ms = info['FileVersionMS'] ls = info['FileVersionLS'] return hi (ms), lo (ms), hi (ls), lo (ls) if __name__ == '__main__': filename = "c:/python24/python24.dll" print ".".join ([str (i) for i in get_version_number (filename)]) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From hancock at anansispaceworks.com Thu Jun 23 17:12:42 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 23 Jun 2005 16:12:42 -0500 Subject: key - key pairs In-Reply-To: References: Message-ID: <200506231612.42324.hancock@anansispaceworks.com> On Thursday 23 June 2005 02:40 pm, Florian Lindner wrote: > is there in python a kind of dictionary that supports key - key pairs? > I need a dictionary in which I can access a certain element using two > different keys, both unique. > > For example: > > I've a dictionary with strings and times. Sometimes I have the string and I > want to have the time, other time I've the time and I want the string. It > is important that one of the keys supports the min/max builtin function. Well, really, you're always using one or the other as the "key" and the other as the "value". Furthermore, it is not in the general case assured that you can do this --- the keys may not really be 1:1. If you are content to restrict yourself to the 1:1 case, you can construct an inverse dictionary from the first dictionary like this: time2string = dict([ (b,a) for a,b in string2time.items() ]) Note that if string2time has duplicate values, this will arbitrarily pick one (in a consistent, but implementation dependent way) to use as the key in the inverse mapping. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From deets at web.de Wed Jun 8 19:51:00 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 09 Jun 2005 01:51:00 +0200 Subject: Fast text display? In-Reply-To: References: Message-ID: > > That looks quite good, except that Trolltech doesn't yet have a GPL-qt > for Win32. I might take another look at it whenever qt4 comes out, but > in the meantime (since I'm unfortunately developing on a win2k system) > it's not useful. Look at qt feee win edition, available here: http://pythonqt.vanrietpaap.nl/ Diez From phillip.watts at anvilcom.com Tue Jun 28 16:13:48 2005 From: phillip.watts at anvilcom.com (phil) Date: Tue, 28 Jun 2005 15:13:48 -0500 Subject: Boss wants me to program References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119988656.668457.202660@g43g2000cwa.googlegroups.com> Message-ID: <42C1AF7C.1050503@anvilcom.com> > I may > try to convince the boss that I can write dos programs for the existing > machine. If we get any kind of upgrade, I'm sure it will be able to run > linux with X and a low overhead window manager. If that happened, I'd > be able to use python and this "tk" thing you have talked about and > make something that will work for him, am I correct? The other > alternative is to install console mode linux on it and hope that the > ncurses library can be used by python. 1. Python/Tkinter runs perfectly well on Win. don't need Linux. In fact, easier to install on Win32 than Linux. 2. The hardware you describe would actually get much better performance from Linux than Win, if you are confident in going to Linux. 3. Python/Tkinter OR Visual Basic may perform a little doggy but not too bad -- The main thing is memory. 128mb works fine for moderm Linux or Win32 but not really fast. 4. I'm not aware of Python ncurses. Doesn't sound like fun. I mean 2 hours of your pay buys 256MB memory. Unless you are free, even then.... From hsuanyeh at yahoo.com Sat Jun 18 21:08:55 2005 From: hsuanyeh at yahoo.com (Hsuan-Yeh Chang) Date: Sun, 19 Jun 2005 01:08:55 GMT Subject: Is there something similar to ?: operator (C/C++) in Python? References: Message-ID: Bo Peng wrote: > Hi, > > I need to pass a bunch of parameters conditionally. In C/C++, I can do > > func(cond1?a:b,cond2?c:d,.....) > > In Python, I am using temporary variables like > > if cond1: > para1 = a > else: > para1 = b > > # .... > # a bunch of such if/else > > func(para1, para2,...) > > Is there an easier way to do this in Python? > > BTW, I do not want to use the following since all of a,b,c,d etc will be > evaluated. > > def condValue(cond, val1,val2): > if cond: > return val1 > else: > return val2 > > func(condValue(cond1,a,b), condValue(cond2,c,d),...) > > Thanks. > Bo take a look at how to use "lambda" in python. From hesterumpe at tiscali.dk Tue Jun 21 08:06:47 2005 From: hesterumpe at tiscali.dk (Bue Krogh Vedel-Larsen) Date: Tue, 21 Jun 2005 12:06:47 GMT Subject: Embedding Python - Deleting a class instance Message-ID: How do I delete a class instance created using PyInstance_New? I've tried calling Py_CLEAR on the instance, but __del__ isn't called. I've also tried calling PyObject_Del, but this gives an access violation in _PyObject_DebugDumpAddress so I guess that ain't a good idea :) I've noticed that the PyObject returned by PyInstance_New has refcount = 2, does this have any significance? From claudio.grondi at freenet.de Fri Jun 17 06:33:46 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 17 Jun 2005 10:33:46 -0000 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118914590.744021.53950@z14g2000cwz.googlegroups.com> <3hdfqlFgeeorU1@individual.net> Message-ID: <3hfga7FgqmitU1@individual.net> > I always thought about our intellect being something "superior" > to this world made of fragile bones and stinking flesh. > However I realized that there's probably no real magic in > it... knowing there are pills to make you happy is sort of > shocking from a philosophical point of view :-) Yes it is, but it doesn't mean, that this well known insight has an effect on what people think about themselves, the religion and the Universe. For an example of what I try to say here, see the "What Deep Blue showed was that chess is not a game of true intelligence" discussion thread in rec.games.chess.computer and track what meaning people assign to the concept of Artificial Intelligence since the term was coined. As long as a machine can't replicate itself and defend its own existance, its intelligence will be questioned. And even if such a machine can fight its enemies the final answer to the question if "true intelligence" is unique to humans can be only given in a fight, but even then the evidence of existance of superior AI can't be given, because only dead people are forced to agree, but it doesn't matter to them anymore ... Claudio From hancock at anansispaceworks.com Fri Jun 17 00:31:50 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 16 Jun 2005 23:31:50 -0500 Subject: 1980's Home Computer-style Package. In-Reply-To: <200506161609.j5GG9vk01340@blake.inputplus.co.uk> References: <200506161609.j5GG9vk01340@blake.inputplus.co.uk> Message-ID: <200506162331.51241.hancock@anansispaceworks.com> On Thursday 16 June 2005 11:09 am, Ralph Corderoy wrote: > > > Some years ago I saw a Python package or program that gave a > > > programming environment similar to the BASICs of 1980's home > > > computers. You got a cursor-addressable screen, e.g. PRINT TAB(10, > > > 20) "Hello", and some simple pixel-setting functions, e.g. RECTANGLE > > > FILL 0, 10, 20, 30. > > Wild-ass guess, but you might try googling for "turtle python". > OK, I've done that but it didn't help; it wasn't tied in with Turtle Well, it might be LiveWires' python package: http://www.livewires.org.uk/python/ It's a free-licensed python module and it does provide some basic graphics capabilities, much like what you are describing. Even if it isn't what you remember, I bet it would serve. The course materials are interesting, too. Very game oriented --- almost every project ends with some sort of computer game the child can play after they've got it working. I know that'd be a good motivator for my kids, anyway. ;-) -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From light at soton.ac.uk Mon Jun 6 11:51:26 2005 From: light at soton.ac.uk (Mark Light) Date: Mon, 6 Jun 2005 15:51:26 +0000 (UTC) Subject: Adding a command to a Pmw.counter widget References: Message-ID: Martin Franklin wrote: > Mark Light wrote: > > Hi, > > I have a Pmw.Counter widget and I would like to add a command > > that is called on pressing either the up or down arrows (the > > command will be the same for both). I have managed to do this for > > the entryfield with "entryfield_command = ", but can't get the same > > to work for the arrows, could someone help me out with how to do > > this. > > > > Looking at the source for the PmwCounter it doesn't look like it > exposes the buttons callbacks. > > I think the best way to do this would be to provide a validator > method to the Counter's entryfield. The validator gets called > whenever the entryfields value changes. > > Example validator methods are included in the Pmw documentation. > > Martin Thanks - this put me on the right track From kbk at shore.net Tue Jun 14 21:14:02 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 14 Jun 2005 21:14:02 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200506150114.j5F1E2Zf015509@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 338 open ( -1) / 2861 closed ( +4) / 3199 total ( +3) Bugs : 909 open ( +1) / 5047 closed (+11) / 5956 total (+12) RFE : 188 open ( -1) / 170 closed ( +2) / 358 total ( +1) New / Reopened Patches ______________________ byteorder issue in PyMac_GetOSType (2005-06-10) http://python.org/sf/1218421 opened by Ronald Oussoren os.kill on windows (2005-06-14) http://python.org/sf/1220212 opened by Miki Tebeka _csv.c leaks when dialect creation fails (2005-06-14) http://python.org/sf/1220242 opened by Michael Hudson Patches Closed ______________ in IDLE, assume new text files are python source by default (2005-05-06) http://python.org/sf/1196895 closed by kbk Add const specifier to PySpam_System prototype (2005-04-21) http://python.org/sf/1187396 closed by birkenfeld Newline in error output of py_compile.compile (2005-03-26) http://python.org/sf/1171150 closed by birkenfeld trivial bug in error message text (2005-05-06) http://python.org/sf/1196980 closed by kbk New / Reopened Bugs ___________________ email.Utils.py: "'" in RFC2231 header (2005-06-10) http://python.org/sf/1218081 opened by Tokio Kikuchi inspect.getsource doesn't update when a module is reloaded (2005-06-10) http://python.org/sf/1218234 opened by Bj?rn Lindqvist Parser chokes on big files (2005-06-11) CLOSED http://python.org/sf/1218930 opened by Alexander Schremmer 'Expression' AST Node not documented (2005-06-12) http://python.org/sf/1219273 opened by Martin Miller copy.py typo (2005-06-13) CLOSED http://python.org/sf/1219342 opened by Ori Avtalion copy.py typo (2005-06-13) CLOSED http://python.org/sf/1219361 opened by Ori Avtalion small output bug (2005-06-12) CLOSED http://python.org/sf/1219448 opened by Alex Levchuk Need locale arg to strftime() (2005-06-13) http://python.org/sf/1219840 opened by Wilfredo Sanchez misdocumented argument range for curses.pair_content (2005-06-13) CLOSED http://python.org/sf/1219862 opened by dcrosta tp_richcompare documentation wrong and incomplete (2005-06-13) http://python.org/sf/1219903 opened by Barry A. Warsaw subprocess call() helper should close stdin if PIPE (2005-06-14) http://python.org/sf/1220113 opened by Stuart Bishop Re-importing embedded thread dumps core (2005-06-14) http://python.org/sf/1220756 opened by Jay T Miller Bugs Closed ___________ Parser chokes on big files (2005-06-11) http://python.org/sf/1218930 closed by doerwalter color highlighting not working on EDIT windows (2003-09-04) http://python.org/sf/800432 closed by kbk No syntax hilite on new file until saved as *.py (2003-07-21) http://python.org/sf/775012 closed by kbk copy.py typo (2005-06-12) http://python.org/sf/1219342 closed by rhettinger copy.py typo (2005-06-12) http://python.org/sf/1219361 closed by rhettinger small output bug (2005-06-12) http://python.org/sf/1219448 closed by rhettinger misdocumented argument range for curses.pair_content (2005-06-13) http://python.org/sf/1219862 closed by akuchling lax error-checking in new-in-2.4 marshal stuff (2005-04-11) http://python.org/sf/1180997 closed by mwh String and list methods documentation deeply hidden (2005-06-06) http://python.org/sf/1215887 closed by rhettinger Queue.qsize() better info about unreliability (2005-06-02) http://python.org/sf/1213475 closed by rhettinger weakref cannot handle bound methods (in contrast to docu) (2005-05-22) http://python.org/sf/1206537 closed by rhettinger New / Reopened RFE __________________ Create a fat build on darwin (2005-06-10) http://python.org/sf/1218333 opened by Ronald Oussoren RFE Closed __________ Make bisect.* functions accept an optional compare function (2005-04-18) http://python.org/sf/1185383 closed by rhettinger sets needs an 'arbitrary element' method (2005-05-31) http://python.org/sf/1212091 closed by rhettinger From martin.witte at gmail.com Wed Jun 22 14:44:09 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 22 Jun 2005 11:44:09 -0700 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: <42b99d7b$0$21804$626a14ce@news.free.fr> References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: <1119465849.547458.219210@f14g2000cwb.googlegroups.com> You also could use a list to represent your data, then you get more dimensions supported, e.g: import math class Point: def __init__(self, *args): self.points = list(args) def dist(x, y): if len(x.points) != len(y.points): raise RuntimeError('dimensions not the same') d = 0 for i in range(len(x.points)): d += (x.points[i] - y.points[i])**2 return math.sqrt(d) From grig at iitp.ru Thu Jun 9 15:41:34 2005 From: grig at iitp.ru (Nikolai Grigoriev) Date: Thu, 9 Jun 2005 19:41:34 +0000 (UTC) Subject: XMLGenerator.startElementNS bug - how to escalate? Message-ID: Dear all, what is the process to escalate bugs in Python core libraries? I am interested in one specific bug - that of xml/sax/saxutils.py, XMLGenerator.startElementNS(). The method is completely unusable, as it crashes on empty-namespace attributes (making me wonder if its author ever tested it - most XML attributes in the wild are unprefixed, aren't they?). As a result, we're left without any namespace-aware SAX serializer in the core library, which is not good. What puzzles me is that the bug is reported 1.5+ years ago (#847665 in the SourceForge bug tracker), and a fix is attached to the issue in the tracker. Several versions of Python have been released since then, but the issue is still open, and the problem is still there. What else is needed for the patch to find its way into the standard distribution? Can I help pushing it there? Regards, Nikolai Grigoriev From oliver.andrich at gmail.com Mon Jun 20 18:24:27 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Tue, 21 Jun 2005 00:24:27 +0200 Subject: Python and encodings drives me crazy In-Reply-To: <4660fe3005062015135c516cbc@mail.gmail.com> References: <6f7b52d05062013545cbc435d@mail.gmail.com> <6f7b52d05062014292f25e8a9@mail.gmail.com> <4660fe3005062015135c516cbc@mail.gmail.com> Message-ID: <6f7b52d0506201524e34d7f2@mail.gmail.com> 2005/6/21, Konstantin Veretennicov : > It does, as long as headline and caption *can* actually be encoded as > macroman. After you decode headline from utf-8 it will be unicode and > not all unicode characters can be mapped to macroman: > > >>> u'\u0160'.encode('utf8') > '\xc5\xa0' > >>> u'\u0160'.encode('latin2') > '\xa9' > >>> u'\u0160'.encode('macroman') > Traceback (most recent call last): > File "", line 1, in ? > File "D:\python\2.4\lib\encodings\mac_roman.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeEncodeError: 'charmap' codec can't encode character u'\u0160' in position > 0: character maps to Yes, this and the coersion problems Diez mentioned were the problems I faced. Now I have written a little cleanup method, that removes the bad characters from the input and finally I guess I have macroman encoded files. But we will see, as soon as I try to open them on the Mac. But now I am more or less satisfied, as only 3 obvious files aren't converted correctly and the other 1000 files are. Thanks for your hints, tips and so on. Good Night. Oliver -- Oliver Andrich --- http://fitheach.de/ From peter at engcorp.com Sat Jun 18 12:13:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:13:08 -0400 Subject: Unbound names in __del__ In-Reply-To: References: Message-ID: Torsten Bronger wrote: > Peter Hansen writes: >>What's your use case for del? > > Every instance represents a "session" to a measurement instrument. > After the instance is deleted, the session should be closed to free > resources. You mean like GPIB devices? We've written a lot of software that talks to instruments, as well as pumps, motors, and sensors of all kinds. I haven't even needed to "free resources", other than by closing a serial port, for example. Such simple operations don't require the use of __del__ and can easily be done with simple .close() type calls as the application shuts itself down or finishes a test sequence or other operation. Use of __del__ is, in my opinion, a bit of a crutch (meaning it seems to make life easier, but then you start relying on it and find it hard to do without). Given that it isn't really reliable in non-trivial situations, I'd recommend pretending __del__ does not exist and restructuring your system to close these sessions explicitly, under your direct control, at the appropriate point. This has worked very well for us so far. -Peter From pdemb at gazeta.pl Sun Jun 12 11:53:20 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 12 Jun 2005 17:53:20 +0200 Subject: How to get/set class attributes in Python References: <42ac0c6d$0$10102$626a14ce@news.free.fr> <42AC3A13.9020503@lexicon.net> Message-ID: <87zmtvh8r3.fsf@hector.domek> Kalle Anke writes: [snap] >> sys.maxint = -12345 > > I don't really understand what you're meaning. He meant None = 1 :> From kevin.coffey at ism-corp.us Fri Jun 17 14:27:48 2005 From: kevin.coffey at ism-corp.us (Kevin P. Coffey) Date: Fri, 17 Jun 2005 14:27:48 -0400 Subject: how to operate the excel by python? Message-ID: <20050617182839.A54EF1E4003@bag.python.org> Question please: In the post, "How to operate the excel by python," where did you find the codes for HorizontalAlignment and VerticalAlignment (Center = -4108 and Bottom = -4107)? I need the code for HorizontalAlignment = xlRight. Is there a table somewhere that shows these codes? Thanks kevin.coffey at ism-corp.us -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at here.com Wed Jun 1 09:46:29 2005 From: nospam at here.com (Matt Feinstein) Date: Wed, 01 Jun 2005 09:46:29 -0400 Subject: Unhappy with numarray docs Message-ID: I spent all day yesterday trying to figure out how to do file IO in the numarray module-- I -did- (I think) figure it all out, eventually, but it's left me in a rather sour mood. 1. The basic functions and methods: fromfile, fromstring, tofile, and tostring, are buried, in non-alphabetical order, in two chapters that list -all- the functions and methods. This is not user-friendly. The explanations themselves, once I found them, are OK, but a line or two of sample code is always nice. File IO is a real-world necessity in an environment where most people use Matlab and/or IDL. And is it obvious, btw, that reading data should be a function? What if I want to read into a buffer? 2. The memmap documentation is screwed up in a more serious fashion. I was able to deduce relatively rapidly that from numarray.memmap import * was needed for some of the example code. But I didn't immediately have the degree of clairvoyance needed to figure out that import numarray.numarryall as num was required for the critical step of associating an array with a MemmapSlice. Grr. Matt Feinstein -- There is no virtue in believing something that can be proved to be true. From prabapython at yahoo.co.in Wed Jun 29 04:40:35 2005 From: prabapython at yahoo.co.in (praba kar) Date: Wed, 29 Jun 2005 09:40:35 +0100 (BST) Subject: Regarding MySQLdb In-Reply-To: <42c25c0d$0$23840$626a14ce@news.free.fr> Message-ID: <20050629084036.97736.qmail@web8401.mail.in.yahoo.com> Dear All After installation of Mysql-Python Interface. I try to import MySQLdb but I got below error How to correct this error. regards Praba >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? File "MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: libmysqlclient.so.12: cannot open shared object file: No such file or directory >>> import _mysql Traceback (most recent call last): File "", line 1, in ? ImportError: libmysqlclient.so.12: cannot open shared object file: No such file or directory >> __________________________________________________________ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com From pink at odahoda.de Mon Jun 13 08:28:47 2005 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 13 Jun 2005 14:28:47 +0200 Subject: Request for help on naming conventions References: Message-ID: Steven D'Aprano wrote: > Are there any useful naming conventions for modules, classes and > functions? > > For instance, should I name functions as verbs and classes as nouns? > > eg > class Transformer(): > pass > > def transform(): > do_stuff > > What about the module name? transformations.py or transform.py? You probably want to read the PEP 8, "Style Guide for Python Code": http://www.python.org/peps/pep-0008.html > What do people do with their own code? Do folks find that being > consistent helps them remember what is what, or do you name objects > whatever feels right at the time? Naming convention are mostly a matter of personal taste (unless you are working in a larger team, where there are some official conventions that must be followed). So I would say the 'feels right' is the most important factor. -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://www.odahoda.de/ From danricofer at gmail.com Fri Jun 10 11:08:21 2005 From: danricofer at gmail.com (Daniel) Date: 10 Jun 2005 08:08:21 -0700 Subject: Changing entities In-Reply-To: <42a6ed6e$1_1@newspeer2.tds.net> References: <1118235783.224018.281490@g44g2000cwa.googlegroups.com> <42a6ed6e$1_1@newspeer2.tds.net> Message-ID: <1118416101.261858.306910@f14g2000cwb.googlegroups.com> Hi Kent This isn't work with the following line: FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 BYTES) >>> byter = re.compile(r'SIZE \((\d+) BYTE\)') >>> s = 'SIZE (1 BYTE)' >>> byter.sub(r'SIZE(\1)', s) 'SIZE(1)' >>> byter.sub(r'SIZE(\1)', line) 'FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 BYTES)' >>> line 'FieldGraphic56 ::= GraphicString EBCDIC BC= " " SIZE (56 BYTES)' >>> Any idea? :-p From hsuanyeh at yahoo.com Fri Jun 17 20:43:17 2005 From: hsuanyeh at yahoo.com (Hsuan-Yeh Chang) Date: Sat, 18 Jun 2005 00:43:17 GMT Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> Message-ID: cpunerd4 wrote: > Hello programmers, > I stumbled onto the python language by chance and it looks like a > great language. Although from what I've read so far (which isn't much) > I've guessed that python is purely an interpreted language unless its > compiled into another language (ie. it needs python installed in order > to run programs). Is this correct? If it is, I guess my plan of action > would be to use python embeded in java applets. > Another question I have: Does any one know any really good, really > easy to understand python books? I would prefer one that is avalible > online for free, but I would also like to know my choices in print. > Thanks in advance for any advice, > cpunerd4 > > P.S. I'm 14 and I know HTML, PHP, and I know about many others! "Dive into Python," availlable both in print and on-line. "Python - visual quickstart guide," availlable in print only very good for newbies like me.. HYC From ptmcg at austin.rr.com Thu Jun 30 07:04:12 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Jun 2005 04:04:12 -0700 Subject: multi regexp analyzer ? or how to do... In-Reply-To: <1120112390.387551.290770@z14g2000cwz.googlegroups.com> References: <1120112390.387551.290770@z14g2000cwz.googlegroups.com> Message-ID: <1120129452.857277.143020@g14g2000cwa.googlegroups.com> I'd propose a pyparsing implementation, but you don't give us many specifics. Is there any chance you could post some sample data, and one or two of the regexps you are using for matching? -- Paul From agriff at tin.it Thu Jun 9 08:06:37 2005 From: agriff at tin.it (Andrea Griffini) Date: Thu, 09 Jun 2005 12:06:37 GMT Subject: Abstract and concrete syntax References: Message-ID: On Thu, 09 Jun 2005 03:32:12 +0200, David Baelde wrote: >I tried python, and do like it. Easy to learn and read This is a key point. How easy is to *read* is considered more important than how easy is to *write*. Re-read the absence of a ternary operator or the limitations of lambda in python under this light (about lambdas note that you can define a named function in a local scope if you need it; and those are full-blown functions and not just a single expression). HTH Andrea From kveretennicov at gmail.com Sat Jun 25 15:01:56 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Sat, 25 Jun 2005 21:01:56 +0200 Subject: Favorite non-python language trick? In-Reply-To: References: <3i232vFj0b57U1@individual.net> Message-ID: <4660fe300506251201507ec494@mail.gmail.com> On 6/25/05, Steven D'Aprano wrote: > On Sat, 25 Jun 2005 17:41:58 +0200, Konstantin Veretennicov wrote: > > > On 6/25/05, Mandus wrote: > >> It is really a consensus on this; that > >> removing map, filter, reduce is a good thing? It will render a whole lot > >> of my software unusable :( > > > > I think you'll be able to use "from __past__ import map, filter, > > reduce" or something like that :) They don't have to be built-in. > > More likely they will be moved to something like itertools than "__past__". > > Or just define them yourself: > > def map(f, seq): > return [f(x) for x in seq] > > def filter(p, seq): > return [x for x in seq if p(x)] > > def reduce(f, seq, zero): > r = zero > for x in seq: r = f(r, x) > return r FWIW, these don't exactly reproduce behaviour of current built-ins. Filter, for instance, doesn't always return lists and map accepts more than one seq... Just my $.02. - kv From rrr at ronadam.com Tue Jun 14 15:02:30 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 14 Jun 2005 19:02:30 GMT Subject: "also" to balance "else" ? In-Reply-To: References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: Sion Arrowsmith wrote: > Fredrik Lundh wrote: >>nope. else works in exactly the same way for all statements that >>support it: if the controlling expression is false, run the else suite >>and leave the statement. > > > For example, consider the behaviour of: > > condition = False > if condition: > print "true" > else: > print "false" > > and > > condition = False > while condition: > print "true" > break > else: > print "false" > > From this, it's clear that while/else gets its semantics from if/else. > Then: > > i = 0 > while i < 10: > print i > i += 1 > else: > print "Done!" > > for i in range(10): > print i > else: > print "Done!" > > So for/else behaves while/else, hence for/else really is the same way > round as if/else. It may not be "intuitive", but it's consistent, and > personally I'd rather have that. > Thanks Fredric and Sion. That makes it clearer. So for's else is not dependent on entering the loop at all. I'm trying to understand just why it is not intuitive in the first place. In an if-else, if the if-block executes, the else-block will not execute. So the else block is the *abnormal* or counter result of the if condition. So the (my) confusion comes from the tendency to look at it in terms of overall program flow rather than in terms of the specific conditional logic. In a for loop the normal, as in terminating normally, behavior of a loop is one where the loop test evaluates as 'False' ending the loop. And the abnormal or counter behavior is when a break statement executes. Thus the 'else' block is the normal result, and the skipping the 'else' block becomes the abnormal counter behavior. So while the logic is consistent, the expected context is reversed. Why is else needed in loops? I was working from the point of view that if there was enough reason for the else to be in loops, and possibly the same reasoning would apply to an also or counter else. But maybe else shouldn't be part of the loop to start with? Regards, Ron From thomasbartkus at comcast.net Tue Jun 7 11:16:58 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 7 Jun 2005 10:16:58 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net><42a3fc70$0$30762$626a14ce@news.free.fr> Message-ID: "James Tanis" wrote in message news:mailman.59.1118094587.10512.python-list at python.org... > Previously, on Jun 6, Thomas Bartkus said: > > # "James Tanis" wrote in message > # news:mailman.43.1118073133.10512.python-list at python.org... > # > > # > > # > My 2 cents, I'm much more productive with Python and QT Builder as I > # > am with VB and those aren't nearly as intergrated as VB's GUI/IDE. A > # > language's productivity, I believe, rests on how high or low-level the > # > language and its libraries are. Not just that though, productivity is > # > also very much affected by the breadth of the libraries available. > # > # When scripting, Windows or Linux, I also am much more productive with > # Python. > # When automating a process for another human being, I am much more productive > # with a RAD tool like VB. The effort involved in creating the user front end > # simply overwhelms all the considerable efficiencies of Python. > # > # When I code wxPython, I find I want to use VB to create/model my user > # interface. Once I prototype my Windows (Frames!) using VB, I can then xlate > # this to wxPython code. What I couldn't do without the VB IDE was visualize > # and experiment with the impact of various layouts *before* I lay down code. > # It is simply too onerous to experiment by code manipulation and too easy to > # swish around visually with a mouse. > # > # When I use a GUI designer like wxGlade, I still find it awkward enough to > # merit prototyping with the VB IDE and then mimic the windows I create with > # wxGlade. > # > # > Sure, GUI RAD solutions increase development in a very real way, but you > # > can find an offering for just about every language out there these days. > # > # Yes. But the tools available for Python are still primitive compared to RAD > # tools like Delphi/Visual Studio. I still don't know enough wxPython to > # understand what the barriers are to creating a RAD visual design and > # construction tool similar to the Visual Studio environment. > # My ravings here are simply the result of a suspicion - > # > # - The suspicion is that the only barrier is the Python (and Linux!) > # communities grossly underestimating the value of such an undertaking. > # Thomas Bartkus > # > > Hmm, it's not that simple though. Unfortunately efforts get spread > among the various projects, wxPython is only one among many. I realize that. And I wouldn't consider it unfortunate that efforts are spread amongs various projects. It adds richness to the whole environment but, yes, it does dilute efforts. > You seem set on wxPython, ... The attractiveness of wxPython here is that it extends the platform neutrality of Python to GUI interfaces. On a Windows platform, the work looks like any other Windows program. On Gnome/Linux, the identical code fits right into the Gnome desktop scheme. *Big* plus. But stuck? There is so much going, there is so little time, and I wallow in ignorance. Justification for my ravings is to coax out the experience of others. One can't help feeling that one is missing something important simply because there isn't the time to evaluate everything in depth. And much of this stuff *needs* to be examined in depth to give it a fair shot. What neat things am I missing and should be looking at ? > ... and its true, RAD projects based around that toolkit > still seem to be in alpha/beta stages, but that does not go for all the > toolkits. There are no barriers that I know of, but your comparing an > application (vb) that has been 11+ years with one (wxglade) that has > been around what.. maybe three years? Yes. And I'm sorry to sound like I was complaining (but I was :-) I'm here because MS is well along it's declining years and I've jumped off the .NET bandwagon. New/wonderful things are no longer forthcoming from that world. They are in Linux/Python. Thomas Bartkus From skip at pobox.com Sun Jun 5 16:51:04 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 5 Jun 2005 15:51:04 -0500 Subject: mix up a string In-Reply-To: References: Message-ID: <17059.26040.45920.196246@montanaro.dyndns.org> rbt> mix = random.shuffle('dog') Try: lst = list('dog') random.shuffle(lst) print "".join(lst) Skip From mwm at mired.org Sun Jun 5 01:06:19 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 05 Jun 2005 00:06:19 -0500 Subject: Easy way to detect hard drives and partitions in Linux References: <1117730941.946683.88840@g44g2000cwa.googlegroups.com> Message-ID: <86k6l99yus.fsf@guru.mired.org> Jeff Epler writes: >> I need a way to detect hard drives and their partitions... labels would >> be nice too... I did some googling but did not find anything all too >> useful. This will strictly be on Linux / Unix so any help would be >> greatly appreciated. > You're not going to find a single portable "unix" way of doing this. > The format of /etc/fstab and /etc/mtab are pretty portable, but they > only list mountable/mounted partitions, not all partitions. Worse yet, part of what he asks for - labels - may not exist. Either that, or may be something different from what he thinks they are. Unix predates MSDOS, and many Unix systems don't support the MSDOS partition table. Some make use of them optional on disks. /etc/fstab and /etc/mtab have worse problems than not listing all partitions. They list mountable "things", not all of which are partitions on hard drives. For example, my fstab has entries for a memory card reader, a floppy drive, a cdr and a cdrw, as well as two different implementations of procfs. Checking for MSDOS style partitions will miss a lot of things. Unix predates MSDOS, and many Unices don't use MSDOS style partitions, or make their use optional. It's possible you have hard drives hanging off the system that aren't visible to the system *at all*. For instance, the device nodes may never have been created. As others have indicated, some systems expose information about what's on the various system busses via special file systems. Those are system-dependent, and are the only way to find drives that don't have device nodes. Assuming the device nodes have been created, they may not be used otherwise, so the only way to find out about them is groveling through /dev (or /devices, depending on the Unix in question). However, figuring out which are hard disks and which are not will be system-dependent. You could start on this by groveling over the output of mount, or /etc/fstab (to bad getfsent isn't in the standard library). That provides clues about what disk drive file names look like, which could be usefull in looking through /dev. But even then, you're going to pretty quickly run into the differences between systems. I'd recommend deciding which Unix you want this to work for, and then asking the question again for that system. For Linux, you may want to specify a distribution. And then don't be surprised if the answer chances with releases of the underlying system. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From here at there.net Sat Jun 11 18:56:48 2005 From: here at there.net (Drazen Gemic) Date: Sun, 12 Jun 2005 00:56:48 +0200 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <1118429907.140244.298390@g43g2000cwa.googlegroups.com> <1118465860.031581.132590@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 11 Jun 2005 11:51:02 -0500, tom wrote: > The sequence goes like this: > 1) When there is little or no money to be made, you start out with an > implied status as a partner. This means you work long + extra hours for > little pay on the promise that you will be rewarded when/if success comes. Well, customers are NOT partners. You need a contract when you deal with customers. It is not a team work, it is selling and buying. And you are selling. This is a third year that I am working as a freelance, and, during unofficial conversations with customers representatives, I have heard many phrases like: "I am your ally", "covering your back", "we are the team", and I never fell for any of them. I agreed in general, never been impolite, but went on my way. And I never forgot, neither let customers forget, that I am selling, and they are buying, and we are not the team. DG From carroll at nospam-tjc.com Mon Jun 6 00:50:37 2005 From: carroll at nospam-tjc.com (Terry Carroll) Date: Sun, 05 Jun 2005 21:50:37 -0700 Subject: Tkinter: How can I update an image display? References: <7x4qcc2krr.fsf@ruckus.brouhaha.com> Message-ID: On 05 Jun 2005 21:04:40 -0700, Paul Rubin wrote: >Try using root.update()? Thanks! From simon.brunning at gmail.com Thu Jun 30 05:31:27 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 30 Jun 2005 10:31:27 +0100 Subject: Modules for inclusion in standard library? In-Reply-To: <1x6lpi6z.fsf@python.net> References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> Message-ID: <8c7f10c605063002317b829474@mail.gmail.com> On 6/29/05, Thomas Heller wrote: > > To me, this sounds that *at least* a PEP would be needed to convince > Guido. Or, to record the reasoning why it cannot be included. I have a feeling that Guido won't allow ctypes into the standard library since it can crash Python. I don't know about you, but that's I interpret this - . I am prepared to be wrong, though. Only Tim can channel Guido! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From peter at engcorp.com Tue Jun 7 09:38:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Jun 2005 09:38:39 -0400 Subject: how to export data from ZODB to text files In-Reply-To: References: Message-ID: <0umdnaOeMsLiPjjfRVn-gA@powergate.ca> ls wrote: > I looking for help with ZODB data export to text file. I have file > Data.fs > [snip] > Could you point me in to some Python code examples, code contributions > and so on. You can download the "standalone" ZODB code and run it under regular Python without Zope installed or involved, and use that to access your Data.fs file directly. See http://www.zope.org/Products/StandaloneZODB This page lists much documentation (near the bottom): http://www.zope.org/Wikis/ZODB/FrontPage -Peter From tdelaney at avaya.com Tue Jun 14 17:54:22 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Wed, 15 Jun 2005 07:54:22 +1000 Subject: Python in Games (was RE: [Stackless] Python in Games) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025205A8@au3010avexu1.global.avaya.com> Dave LeCompte (really) wrote: >> Who is using Python in games >> >> Python has been used in a number of games, including >> >> * ToonTown - http://www.toontown.com/ >> * EveOnline - http://www.eve-online.com/ >> * Blade of Darkness - http://www.codemastersusa.com/blade/ Add to that: - `The Temple of Elemental Evil`__ - `Vampire: The Masquerade: Bloodlines`__ .. __: http://www.troikagames.com/toee.htm .. __: http://www.vampirebloodlines.com/ Moved to python-list because it's gone beyond Stackless :) Tim Delaney From mitsura at skynet.be Wed Jun 8 11:28:03 2005 From: mitsura at skynet.be (mitsura at skynet.be) Date: 8 Jun 2005 08:28:03 -0700 Subject: programmnig advise needed In-Reply-To: <5l5ca1treamnrsee551fajg2uc9ajel57f@4ax.com> References: <1118171685.749946.240100@g47g2000cwa.googlegroups.com> <5l5ca1treamnrsee551fajg2uc9ajel57f@4ax.com> Message-ID: <1118244483.430059.242300@g49g2000cwa.googlegroups.com> Thanks for the feedback! It is a very good idea to use dictionaries. I will try to implemented it this way. Thanks, Kris Andrea Griffini schreef: > On 7 Jun 2005 12:14:45 -0700, mitsura at skynet.be wrote: > > >I am writing a Python program that needs to read XML files and contruct > >a tree object from the XML file (using wxTree). > > Supposing your XML file has a single top level node (so that it's a > legal XML file) then the following code should be able to read it... > > ######### > from elementtree import ElementTree as ET > > class Node: > def __init__(self, xmlnode): > self.xmlnode = xmlnode > self.children = [] > > def loadtree(f): > root = ET.parse(f).getroot() > nodes = {} > for x in root: > if x.tag.startswith("element"): > nodes[x.tag] = Node(x) > for x in root.findall("association"): > name = x.find("Name").text > parent = x.find("Parent").text > nodes[parent].children.append(nodes.pop(name)) > assert len(nodes) == 1 > return nodes.popitem()[1] > ########## > > The idea is to create a node with an empty list of > logical children and then for every association > removing the child node from the global pool (a dict > indexed by node name) to place it in its parent. > I assumed that the nodes are in random order, but > that the associations are sorted bottom-up in > the tree. If this is not the case then you should > keep TWO dicts, removing from only one of them > the children when you process an association, > and looking up the parent in the *other* dict that > is not changed during processing of associations. > The dict from who you are removing the children > will allow you to detect logical errors in the file > (i.e. a node having two parents - you won't find > that node in the dict the second time - and absence > of a single root - you won't end up with a single > element in the dict after processing all > associations -). > > HTH > Andrea From roy at panix.com Mon Jun 13 14:24:09 2005 From: roy at panix.com (Roy Smith) Date: 13 Jun 2005 14:24:09 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? References: Message-ID: rbt wrote: >You have many hundred gigabytes of data... possible even a terabyte or >two. Within this data, you have private, sensitive information (US >social security numbers) about your company's clients. Your company has >generated its own unique ID numbers to replace the social security numbers. > >Now, management would like the IT guys to go thru the old data and >replace as many SSNs with the new ID numbers as possible. The first thing I would do is a quick sanity check. Write a simple Python script which copies its input to its output with minimal processing. Something along the lines of: for line in sys.stdin.readline(): words = line.split() print words Now, run this on a gig of your data on your system and time it. Multiply the timing by 1000 (assuming a terabyte of real data), and now you've got a rough lower bound on how long the real job will take. If you find this will take weeks of processing time, you might want to re-think the plan. Better to discover that now than a few weeks into the project :-) >You have a tab >delimited txt file that maps the SSNs to the new ID numbers. There are >500,000 of these number pairs. What is the most efficient way to >approach this? I have done small-scale find and replace programs before, >but the scale of this is larger than what I'm accustomed to. The obvious first thing is to read the SSN/ID map file and build a dictionary where the keys are the SSN's and the values are the ID's. The next step depends on your data. Is it in text files? An SQL database? Some other format. One way or another you'll have to read it in, do something along the lines of "newSSN = ssnMap[oldSSN]", and write it back out. From __peter__ at web.de Mon Jun 6 13:34:24 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Jun 2005 19:34:24 +0200 Subject: Reading a CSV file into a list of dictionaries References: <1118078038.100136.56630@f14g2000cwb.googlegroups.com> Message-ID: RFQ wrote: > I have a comma delimited file where each line in the file is something > like: > > PNumber,3056,Contractor,XYZ Contracting,Architect,ABC Architects,... > > So each line is intended to be: key1,value1,key2,value2,key3,value3... > and each line is to be variable in length (although it will have to be > an even number of records so that each key has a value). > > I want to read in this csv file and parse it into a list of > dictionaries. So each record in the list is a dictionary: > > {"PNumber":"3056","Contractor":"XYZ Contracting", ... } >>> row ['PNumber', '3056', 'Contractor', 'XYZ Contracting', 'Architect', 'ABC'] >>> dict(zip(row[::2], row[1::2])) {'Architect': 'ABC', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} A bit more elegant: >>> irow = iter(row) >>> dict(zip(irow, irow)) {'Architect': 'ABC', 'PNumber': '3056', 'Contractor': 'XYZ Contracting'} Peter From mrmaple at gmail.com Sun Jun 19 01:09:00 2005 From: mrmaple at gmail.com (James Carroll) Date: Sun, 19 Jun 2005 01:09:00 -0400 Subject: Extensions on Linux: import without underscore? In-Reply-To: References: Message-ID: Thanks Robert. > > Call it bright.so . > If I rename it bright.so, then I get the error: ImportError: dynamic module does not define init function (initbright) I'm using swig with the module declaration %module bright I've looked at some other source, and it looks like there are some good reasons to have a bright.py that passes calls on to _bright. > If at all possible, you should use distutils to build Python extensions. Where can I find similar distutils C++ examples? Can it do most of what Scons does? > > If you must use Scons, read > > http://www.scons.org/cgi-bin/wiki/PythonExtensions > Very nice, strange that didn't show up for all my googles of scons python, etc. I like how it uses distutils to get flags... I'm extending wxPython, so I'm using the wxWidgets env.ParseConfig('wx-config --cppflags --libs') Technique... I'll have to ponder using one or the other or both. Hmm.... -Jim From jorge at bcs.org.uk Sat Jun 25 06:36:57 2005 From: jorge at bcs.org.uk (Jorge Louis De Castro) Date: Sat, 25 Jun 2005 11:36:57 +0100 Subject: Background thread Message-ID: Hi, I'm new to python and I'm having trouble figuring out a way to have a thread running on the background that over rules the raw_input function. The example I'm working on is something like having a thread that prints "You're taking too long" every 10 seconds, while waiting for input from the user. The problem is that I can only read (and in batch) the thread printout messages on the console after giving something to raw_input. Is it not possible to have the thread print its stuff and then return to raw_input() ? Any code examples or pseudo-code or documentation directions will be highly appreciated. Thanks in advance jorge -------------- next part -------------- An HTML attachment was scrubbed... URL: From desertgarden at netscape.com Mon Jun 27 18:14:52 2005 From: desertgarden at netscape.com (Brian) Date: Mon, 27 Jun 2005 22:14:52 GMT Subject: Boss wants me to program In-Reply-To: References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> Message-ID: Thomas Bartkus wrote: > I would modify that. > > 1) VB shines in the MS Windows/Office realm. > 2) Python shines everywhere else. True. However, it's also important to remember that most computer systems (at least in the United States) come with Microsoft Windows installed on them. You have to write software for the platform that one will be working with -- in most cases, that's Microsoft Windows. :-) Brian --- From whisper at oz.net Tue Jun 21 20:49:28 2005 From: whisper at oz.net (whisper at oz.net) Date: Tue, 21 Jun 2005 17:49:28 -0700 Subject: Need Python web hosting ASAP Message-ID: <42B8B598.4000909@oz.net> Medium/small site with mod_python and sqllite or mySQL running Python 2.3.3 or later on Apache 2.x. I can do the python and CGI, but might need a _little_ hand holding for the rest. Will also need SSL and a certificate. Also mailboxes for ~12 people (to start). We don't do unsolicited mailings or expect a huge amount of mail traffic at this time. Will need a domain name transfered. NEED TO GET THIS UP ASAP! Low cost is best. David LeBlanc Seattle, WA USA From utabintarbo at gmail.com Thu Jun 23 09:35:15 2005 From: utabintarbo at gmail.com (utabintarbo at gmail.com) Date: 23 Jun 2005 06:35:15 -0700 Subject: Allowing only one instance of a script? In-Reply-To: References: Message-ID: <1119533715.637993.296780@o13g2000cwo.googlegroups.com> ... lock file? From lycka at carmen.se Tue Jun 21 10:49:07 2005 From: lycka at carmen.se (Magnus Lycka) Date: Tue, 21 Jun 2005 16:49:07 +0200 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Konstantin Veretennicov wrote: > On 6/21/05, Magnus Lycka wrote: > >>I don't know anything about the Python compiler internals, >>but it doesn't seem very hard to identify simple literals following >>while and if, and to skip the runtime test. (Perhaps it's done >>already?) > > > True doesn't seem to be a literal, it is looked up by name and can be > rebound to, say, 0 anytime: Right. Silly me. Maybe in some future Python version, True and False will be constants, like None is since Python 2.4. From jabel at plus.net Thu Jun 2 04:57:59 2005 From: jabel at plus.net (John Abel) Date: Thu, 02 Jun 2005 09:57:59 +0100 Subject: dictionaries and threads In-Reply-To: <1117702209.058492.187520@f14g2000cwb.googlegroups.com> References: <20050601231009.396072.becbe514@goombah.com> <1117702209.058492.187520@f14g2000cwb.googlegroups.com> Message-ID: <429ECA17.9060302@plus.net> Bloke wrote: >I've been trying to find a Python tutorial on threading - does anyone >have a reference? > >Rob > > > You could try this: http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf J From lothar.sch at gmx.de Thu Jun 9 10:13:02 2005 From: lothar.sch at gmx.de (lothar.sch at gmx.de) Date: 9 Jun 2005 07:13:02 -0700 Subject: Python as CGI on IIS and Windows 2003 Server Message-ID: <1118326382.802580.156100@g14g2000cwa.googlegroups.com> Hi, My python scripts are running as cgi scripts on an IIS on Windows XP. I have to distribute it to IIS on Windows 2003 Server. I tried to set python as cgi scripts in IIS on this machine in IIS using advices from http://python.markrowsoft.com/iiswse.asp No test with or without any " let the IIS execute python scrits as cgi. Http Error code is 404 (but i'm sure that the file exists in the requested path). Is there any difference for python as CGI on IIS between Windows XP prof. and Windows 2003 Server? Thanks Lothar From snail at objmedia.demon.co.uk Tue Jun 28 11:40:29 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 28 Jun 2005 16:40:29 +0100 Subject: Thoughts on Guido's ITC audio interview References: <11bs1bc5jotvg9c@news.supernews.com> <42BF6995.1050606@boonthavorn.com> Message-ID: <7wYyv0Lt9WwCFw2u@objmedia.demon.co.uk> In message , Simon Brunning writes >Eclipse's refactorings are a great boon, I find. Refectoring is never >*fully* automatic, of course, but the ability to, for example, select >a chunk of code and have it extracted into a separate method with all >needed arguments and the return value worked out for you is very >helpful. All you have to do is give the new method a name. And this >sort of thing can certainly improve readability. This is not an attach on you Simon, but if people are relying on that type of thing for increases in software productivity they are hiring the wrong people. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From austin at maxtronic.com.tw Tue Jun 21 02:58:31 2005 From: austin at maxtronic.com.tw (Austin) Date: Tue, 21 Jun 2005 14:58:31 +0800 Subject: py2exe problem Message-ID: I use py2exe to build python program to "aa.exe". If this program has a bug, after closed this program, it will show "aa.exe.log" in this folder. Is there any ways to avoid this log file? From tdelaney at avaya.com Mon Jun 27 17:56:00 2005 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 28 Jun 2005 07:56:00 +1000 Subject: Thoughts on Guido's ITC audio interview Message-ID: <2773CAC687FD5F4689F526998C7E4E5F05CAF2@au3010avexu1.global.avaya.com> Aahz wrote: > Perhaps. But adding the time to learn those IDEs in addition to the > time > to learn Java is ridiculous. I've been forced to use Java a bit to > support credit cards for our web application; I've got a friend whose > Java-vs-Python argument hinges on the use of Eclipse; I was unable to > make use of Eclipse in the time I had available for the project. Absolutely. I've really tried to use Eclipse - it's the standard editor for my current project (Java - blegh!). I *hate* it. It's huge, bulky, slow ... I've gone back to my text editor. I'm a hell of a lot more productive because the IDE isn't getting in my way. The only IDE I've ever actually liked using was Metrowerks CodeWarrior (on MacOS classic). Simple, unobtrusive. Good project management, without trying to control every aspect of the development process. And it allowed me to use the entire screen for editing if I wished whilst still having everything readily available. Tim Delaney From reinhold-birkenfeld-nospam at wolke7.net Tue Jun 7 15:13:02 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 07 Jun 2005 21:13:02 +0200 Subject: the python way? In-Reply-To: References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> <3gjksrFcmvf4U1@individual.net> Message-ID: <3gm9tuFd3j1qU2@individual.net> Andrew Dalke wrote: > Reinhold Birkenfeld wrote: >> To make it short, my version is: >> >> import random >> def reinterpolate2(word, vocals='aeiouy'): >> wlist = list(word) >> random.shuffle(wlist) >> vees = [c for c in wlist[::-1] if c in vocals] >> cons = [c for c in wlist[::-1] if c not in vocals] > > Why the [::-1]? If it's randomly shuffled the order isn't important. I wanted to keep compatibility with Groops' version so that I could test that my one works right. Since he did list.pop() it was necessary. >> short, long = sorted((cons, vees), key=len) >> return ''.join(long[i] + short[i] for i in range(len(short))) + ''.join(long[len(short):]) > > All the cool kids are using 2.4 these days. :) Yep, it's the best way to advertise for its cool features ;) Reinhold From steven.bethard at gmail.com Mon Jun 6 10:57:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 06 Jun 2005 08:57:27 -0600 Subject: If - Or statements In-Reply-To: <42a40590$0$23331$636a15ce@news.free.fr> References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> <42a40590$0$23331$636a15ce@news.free.fr> Message-ID: bruno modulix wrote: > Here's a somewhat more pythonic version: > > filelist = os.listdir(path) > for filename in filelist: > # I assume you want to remember what's the ext is > ext = os.path.splitext(filename) Check the docs[1]. This should probably read: _, ext = os.path.splitext(filename) because splitext returns a pair of (root, ext). > # debug trace > print "filename : %s - ext : %s" % (filename, ext) > if ext in ['.this', '.that', '.whatnot']: > print "ext is %s - should process this file" % ext STeVe [1] http://docs.python.org/lib/module-os.path.html From oneill at konto.pl Wed Jun 15 10:43:07 2005 From: oneill at konto.pl (Grzegorz) Date: Wed, 15 Jun 2005 16:43:07 +0200 Subject: eclipse, pydev and wxpython - standard output redirection ? References: Message-ID: Uzytkownik "Philippe C. Martin" napisal w wiadomosci news:pvIre.794$kX4.452 at newssvr30.news.prodigy.com... > app = MyApp(False) > app.MainLoop() > > will keep wxWidgets from using its own window. > > that's it ! Thanks a lot :) From i at hate-spam.com Wed Jun 8 19:43:55 2005 From: i at hate-spam.com (Paul Bredbury) Date: Wed, 8 Jun 2005 23:43:55 +0000 (UTC) Subject: MoinMoin WikiName and python regexes In-Reply-To: References: Message-ID: Ara.T.Howard wrote: > i know nada about python so please forgive me if this is way off base. i'm > trying to fix a bug in MoinMoin whereby > > WordsWithTwoCapsInARowLike I don't think there is such a thing as the perfect "hyperlink vs just-text" convention. In MoinMoin, you can force a custom link using e.g.: [wiki:WebsiteSecurity this is the link text to WebsiteSecurity so call it whatever you want such as WebsiteSecurities] This custom linking, whilst obviously not ideal, solves the problems mentioned at http://www.c2.com/cgi/wiki?WikiName This seems better than producing endless confusing variations on the "standard" (be it formal, actual, or simply obviously desired). I'm not convinced of the usefulness of MoinMoin's "subpages" idea, while we're on the (related) subject - they seem to create more problems than they solve: http://moinmoin.wikiwikiweb.de/HelpOnEditing/SubPages From peter at engcorp.com Thu Jun 9 07:55:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 07:55:59 -0400 Subject: Saving/retrieving user preferences In-Reply-To: <42a78012@dnews.tpgi.com.au> References: <42a78012@dnews.tpgi.com.au> Message-ID: Brian Wallis wrote: > This may be a FAQ,but I cannot find it. > > I want to save user preferences, window sizes, recently opened file names, > etc for a python application and I am looking for a package that does this > in a way that is portable across unix/linux and windows (and mac would be > nice as well). > > Is there a 'standard' package for doing this in python? As you can see from the replies so far, there is no 'standard', if by that you mean "one single widely used solution". There are a dozen ways to do it, with (as far as I can tell) no one standing out in popularity. That said, I believe the ConfigParser approach is probably one of the best combinations of simplicity and cleanliness. -Peter From eloff777 at yahoo.com Sun Jun 12 16:13:24 2005 From: eloff777 at yahoo.com (eloff777 at yahoo.com) Date: 12 Jun 2005 13:13:24 -0700 Subject: How to test if an object IS another object? References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> Message-ID: <1118607204.001609.25310@g47g2000cwa.googlegroups.com> Sorry about removing my message, I posted with the wrong google account, I don't really want my email where those irritating spam bots can find it. >The most obvious way (as usual ?): > >if obj1 is obj2: > // your code here I immediately thought of is, and tested it in the console, but it didn't work quite like I expected: >foo = 3 >bar = 3 >zoo = foo >foo is zoo True >foo is bar True >zoo is bar True clearly foo and bar have the same value but they are different objects aren't they? Yet applying the is operator yields True. Thanks, -Dan From michele.simionato at gmail.com Wed Jun 15 00:52:20 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 14 Jun 2005 21:52:20 -0700 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <1118734620.851366.291360@f14g2000cwb.googlegroups.com> Message-ID: <1118811140.395609.6880@g47g2000cwa.googlegroups.com> Andrea Griffini: >Wow... I always get surprises from physics. For example I >thought that no one could drop confutability requirement >for a theory in an experimental science... I mean that I >always agreed with the logic principle that unless you >tell me an experiment whose result could be a confutation >of your theory or otherwise you're not saying anything >really interesting. >In other words if there is no means by which the theory >could be proved wrong by an experiment then that theory >is just babbling without any added content. >A friend of mine however told me that this principle that >I thought was fundamental for talking about science has >indeed been sacrified to get unification. I was told that >in physics there are current theories for which there >is no hypotetical experiment that could prove them wrong... You must always distinguish between Science (=what we know) and Research (=what we do not know). Research is performed with all methods except the scientific one, even if we don't tell the others ;) Michele Simionato From cotyspend at yahoo.com Fri Jun 3 23:34:04 2005 From: cotyspend at yahoo.com (nephish) Date: 3 Jun 2005 20:34:04 -0700 Subject: weird cgi problem w/ apache Message-ID: <1117856044.857442.221610@g43g2000cwa.googlegroups.com> Hello all. i have a strange problem with some python cgi scripts. the deal is..... i keep loosing permission to write to a file created by a cgi script. the file is created in a directory created by a python script. but after the file is created by the cgi script, another script in the same folder cannot open it to write to. think that its a permissions issue. the thing is, all of it works on my Arch linux computer, but it doesn't work on my Ubuntu computer. same folders, same everything (except http.conf) because debian sets up its modules differently. how come it will create the directory, create the files, but not let me go back into the file to edit? any suggestions? what could be different? from one computer to the next? From riccardo_cut1 at cut2_sideralis.net Wed Jun 22 11:57:14 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Wed, 22 Jun 2005 17:57:14 +0200 Subject: PEP ? os.listdir enhancement Message-ID: Hi, I noticed that when I use os.listdir I need to work with absolute paths 90% of times. While I can use a for cycle, I'd prefere to use a list comprehension, but it becomes too long. I propose to add an 'abs' keyword which would make os.listdir return the absolute path of files instead of a relative path. This would bring only advantages, I think. I show two examples from os import listdir from os.path import isdir,join,getsize,isfile ### e.g. 1 part 1 - getting a list of directories ### dirs=[] for i in os.listdir(path): tmp_path=os.path.join(path,i) if os.path.isdir(tmp_path): dirs.append(tmp_path) ### e.g. 1 part 2 ### dirs=[join(path,x) for x in listdir(path) if isdir(join(path,x))] here the list comprehension is still clear, but only because we have direct references to join and friends. moreover whe need to use join twice for each directory. ### e.g. 2 part 1 - getting a list of (file,size) tuples ### path_size=[] for i in os.listdir(path): tmp_path=os.path.join(path,i) if os.path.isfile(tmp_path): path_size.append((tmp_path,getsize(tmp_path)) ### e.g. 2 part 2 ### dirs=[(join(path,x),getsize(join(path,x)) for x in listdir(path) if isfile(join(path,x))] now list comprehension is way too long, and in the worst case we must use join 3 times for each iteration. adding an 'abs' keyword to os.listdir would give benefits both to for cycle and list comprehensions. for cycle would lose the tmp_path assignment and list comprehensions ... ### e.g. 1 part 2 bis ### dirs=[x for x in listdir(path,abs=True) if isdir(x)] here we gain clearness and speed. ### e.g. 2 part 2 bis ### dirs=[(x,getsize(x)) for x in listdir(path,abs=True) if isfile(x)] and here we gain clearness, speed and a truely _usable_ list comprehension What do you think about this ? Thanks for reading, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From grante at visi.com Tue Jun 28 15:23:11 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 28 Jun 2005 19:23:11 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <11c38sv6ul8ck99@corp.supernews.com> On 2005-06-28, muldoon wrote: > Americans consider having a "British accent" a sign of sophistication > and high intelligence. That depends on the accent. I believe that's probably true for the educated south of England, BBC, received pronunciation. I don't think that's true for some of the other dialects from northern areas (e.g. Liverpool) or the "cockney" accent. > Many companies hire salespersons from Britain to represent > their products,etc. Question: When the British hear an > "American accent," does it sound unsophisticated and dumb? I too have always wondered about this. > Be blunt. We Americans need to know. Should we try to change > the way we speak? Are there certain words that sound > particularly goofy? Please help us with your advice on this > awkward matter. -- Grant Edwards grante Yow! Mr and Mrs PED, can at I borrow 26.7 visi.com From peter at engcorp.com Thu Jun 2 09:44:14 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 09:44:14 -0400 Subject: decimal and trunkating In-Reply-To: References: Message-ID: <8dKdnRm_WPb3kALfRVn-vw@powergate.ca> Timothy Smith wrote: > i want to trunkate 199.999 to 199.99 > getcontext.prec = 2 isn't what i'm after either, all that does is E's > the value. > do i really have to use floats to do this? I think you need a context with appropriate rounding set (e.g. ROUND_FLOOR?) and then use the quantize() method with an argument with the appropriate number of decimal places. For example, this works, though I'm definitely not a Decimal expert and am confident there's a more elegant approach (which might depend on more information about what you're doing): >>> d = decimal.Decimal('199.999') >>> decimal.getcontext().rounding = decimal.ROUND_FLOOR >>> d.quantize(decimal.Decimal('1.00')) Decimal("199.99") -Peter (I hope this inspires someone who actually knows what he's doing with Decimal to post an improved solution.) From robin at SPAMREMOVEjessikat.fsnet.co.uk Wed Jun 1 14:16:43 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Wed, 01 Jun 2005 18:16:43 +0000 Subject: BUG pythonw vs subprocess Message-ID: <429DFB8B.4090102@jessikat.fsnet.co.uk> There seems to be a problem with calling subprocesses from a script run with pythonw rather than python. The error doesn't seem to be a function of using pythonw.exe rather than python.exe in the Popen call, but we seem to get an error when pythonw is used to execute the script proc0.py C:\Tmp>cat proc0.py #proc0.py import sys from subprocess import Popen, PIPE sys.stderr = sys.stdout = open('out.txt','w') job = Popen('pythonw.exe -u proc1.py',stdout=PIPE,stderr=PIPE) print 'pid',job.pid out,err=job.communicate() print 'out', out print 'err', err #end of proc0.py C:\Tmp>cat proc1.py #proc1.py import sys, os print 'sys.executable', sys.executable print 'sys.argv', sys.argv print 'stdout IN THE CHILD', os.getpid() print >>sys.stderr, 'stderr IN THE CHILD', os.getpid() #end of proc1 C:\Tmp>python proc0.py C:\Tmp>cat out.txt pid 1156 out sys.executable c:\python\pythonw.exe sys.argv ['proc1.py'] stdout IN THE CHILD 1156 err stderr IN THE CHILD 1156 C:\Tmp>pythonw proc0.py C:\Tmp>cat out.txt Traceback (most recent call last): File "proc0.py", line 5, in ? job = Popen('pythonw.exe -u proc1.py',stdout=PIPE,stderr=PIPE) File "c:\python\lib\subprocess.py", line 549, in __init__ (p2cread, p2cwrite, File "c:\python\lib\subprocess.py", line 609, in _get_handles p2cread = self._make_inheritable(p2cread) File "c:\python\lib\subprocess.py", line 650, in _make_inheritable DUPLICATE_SAME_ACCESS) WindowsError: [Errno 6] The handle is invalid C:\Tmp> -- Robin Becker From rune.strand at gmail.com Wed Jun 1 22:05:14 2005 From: rune.strand at gmail.com (Rune Strand) Date: 1 Jun 2005 19:05:14 -0700 Subject: Strange KeyError using cPickle References: <1117671230.384189.120030@f14g2000cwb.googlegroups.com> Message-ID: <1117677914.469065.301370@g49g2000cwa.googlegroups.com> [Tim Peters] > What is "XWwz"? Assuming it's a bizarre typo for "open", change the > 'w' there to 'wb'. Pickles are binary data, and files holding pickles > must be opened in binary mode, especially since: > > > ... > > (on WinXP, CPython 2.4.1) Thanks Tim. The bizarre 'typo' appears to be caused by ad-blocking software confusing python code with javascript (i think). I had the feeling this was a red facer. Setting the protocol to 0 (text) also make it work. From peter at engcorp.com Tue Jun 14 12:47:55 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 12:47:55 -0400 Subject: collect data using threads In-Reply-To: <42aeeef3$1_1@newspeer2.tds.net> References: <42aeeef3$1_1@newspeer2.tds.net> Message-ID: <4q2dneNoafbYljLfRVn-sQ@powergate.ca> Kent Johnson wrote: > Peter Hansen wrote: >> That will not work, and you will get data loss, as Jeremy points out. >> > Can you explain why not? self.data is still bound to the same list as x. > At least if the execution sequence is x = self.data > self.data.append(a_piece_of_data) > self.data = [] Ah, since the entire list is being returned, you appear to be correct. Interesting... this means the OP's code is actually appending things to a list, over and over (presumably), then returning a reference to that list and rebinding the internal variable to a new list. If another thread calls on_received() and causes new data to be appended to "the list" between those two statements, then it will show up in the returned list (rather magically, at least to my way of looking at it) and will not in fact be lost. Good catch Kent. :-) -Peter From reinhold-birkenfeld-nospam at wolke7.net Wed Jun 1 12:03:30 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 01 Jun 2005 18:03:30 +0200 Subject: Question about mutexes In-Reply-To: <429dda0a$1@griseus.its.uu.se> References: <429dda0a$1@griseus.its.uu.se> Message-ID: <3g64fdFatsvjU1@individual.net> Jan Danielsson wrote: > In OS/2 C, I would do this: > > main() > { > ... > DosCreateMutexSem(NULL, &hmtx, 0UL, FALSE); > ... > } > > thread() > { > ... > DosRequestMutexSem(hmtx); > > Locked! > > DosReleaseMutexSem(hmtx); > ... > } > > How would I go about doing that in Python? I think you will want to create a threading.Lock object. Reinhold From steve at REMOVETHIScyber.com.au Sat Jun 25 22:09:29 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 12:09:29 +1000 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> <1119730516.936848.195640@f14g2000cwb.googlegroups.com> Message-ID: On Sat, 25 Jun 2005 13:31:19 -0700, Robert Kern wrote: > Of course, in a Python 3000 world, nothing stops anyone from using their > own extension module implementing map, filter, and reduce if they really > want to. TSBOOOWTDI in the language/stdlib, but it shouldn't stop anyone > from using other ways to do it that aren't in the stdlib if the > tradeoffs are right for them. Now that's a good point. Since Guido has said that one of the major motivations for removing the functional programming tools like map, filter and reduce is that There Should Be Only One Obvious Way To Do It, and Guido also seems to really like list comprehensions, is it fair to assume that for-loops will be removed from Python 3000 too? Or are they safe until Python 4000? *wink* Of course, I also know that Guido has said a foolish consistency is the hobgoblin of little minds, and I would never accuse him of being a little mind. But one of the things I like about Python is that it has found a nice balance between There Is Always Another Way, and The Language Is A Straight Jacket. It is blindingly easy to refactor map and filter as in-line list comps, and Guido's comments suggest to me that they are safe until list comps are significantly faster. But reduce needs to be re-factored as a for loop, with all the disadvantages that implies. I think that if people like Mandus have good real-world usage cases for reduce, it can be saved, at least as part of itertools. -- Steven. From derek.perriero at gmail.com Thu Jun 9 14:44:21 2005 From: derek.perriero at gmail.com (Derek Perriero) Date: Thu, 9 Jun 2005 14:44:21 -0400 Subject: Remove duplicates from list Message-ID: <17fc2016050609114439ad3fb0@mail.gmail.com> I've been un-triumphantly trying to get a list of mine to have no repeats in it. First, I'm pulling attributes from Zope and forming a list. Next, I'm pulling those same values and comparing them against the same list and if the values equal each other and are not already in the list, they append to my 'nodupes' list. My current result is showing what I put in I am getting out. Below the code is my output of 'nodupes' list. Here's the snippet. regHours = context.getMainPrint(); <---attributes from Zope libslist = [] nodupes = [] #collect libraries for libs in regHours: cache = libs.Monday + libs.Tuesday + libs.Wednesday + libs.Thursday + libs.Friday + libs.Saturday + libs.Sunday libslist.append(cache) #pull repeated values for item in regHours: collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday + item.Friday + item.Saturday + item.Sunday libName = item.libraryName for libs in libslist: if collect == libs and libs not in nodupes: nodupes.append(libs) *My Current Output:* ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - 5pm9am - 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - 5pmClosed'] Thanks -- Perriero, Derek derek.perriero at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From qwweeeit at yahoo.it Fri Jun 17 05:07:46 2005 From: qwweeeit at yahoo.it (qwweeeit at yahoo.it) Date: 17 Jun 2005 02:07:46 -0700 Subject: How to right align IPaddress? In-Reply-To: References: <1118740170.9602.236315256@webmail.messagingengine.com> Message-ID: <1118999266.076485.159830@o13g2000cwo.googlegroups.com> IPnumber.rjust(15) From rbt at athop1.ath.vt.edu Fri Jun 17 09:45:59 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 17 Jun 2005 09:45:59 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <6sudnWgJw6l7UC_fRVn-iQ@powergate.ca> References: <42ae3411@news.eftel.com> <1118928457.18452.13.camel@athop1.ath.vt.edu> <42B23670.70103@lexicon.net> <1119012614.4268.18.camel@athop1.ath.vt.edu> <6sudnWgJw6l7UC_fRVn-iQ@powergate.ca> Message-ID: <1119015959.5960.5.camel@athop1.ath.vt.edu> On Fri, 2005-06-17 at 09:18 -0400, Peter Hansen wrote: > rbt wrote: > > The script is too long to post in its entirety. In short, I open the > > files, do a binary read (in 1MB chunks for ease of memory usage) on them > > before placing that read into a variable and that in turn into a list > > that I then apply the following re to > > > > ss = re.compile(r'\b\d{3}-\d{2}-\d{4}\b') > > > > like this: > > > > for chunk in whole_file: > > search = ss.findall(chunk) > > if search: > > validate(search) > > This seems so obvious that I hesitate to ask, but is the above really a > simplification of the real code, which actually handles the case of SSNs > that lie over the boundary between chunks? In other words, what happens > if the first chunk has only the first four digits of the SSN, and the > rest lies in the second chunk? > > -Peter No, that's a good question. As of now, there is nothing to handle the scenario that you bring up. I have considered this possibility (rare but possible). I have not written a solution for it. It's a very good point though. Is that not why proper software is engineered? Anyone can build a go cart (write a program), but it takes a team of engineers and much testing to build a car, no? Which woulu you rather be riding in during a crash? I wish upper mgt had a better understanding of this ;) From tjreedy at udel.edu Wed Jun 1 18:00:56 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 18:00:56 -0400 Subject: Information about Python Codyng Projects Ideas References: <1117645221.920027.224880@g14g2000cwa.googlegroups.com> Message-ID: "M1st0" wrote in message news:1117645221.920027.224880 at g14g2000cwa.googlegroups.com... > I have read the proposed Ideas from > > http://wiki.python.org/moin/CodingProjectIdeas > > And the more interesting for me were those about Optimization. > > MemoryUsageProfiler > ProfileReplacementProject > SpeedUpInterpreterStartup > > But I many of this there are very few information or nothing about of > what is really needed. > I am taking a Master in Computer Science so I know many of the issues > in this topics, but I would like some hints and every usefull > information. > > I hope that here is the right place for this kind of discussion. Definitely. Brett Cannon just completed his CS thesis on the possible speed benefit of certain type-inferencing in the compiler. He posted a link about a week ago just after successfully defending it. I believe some of the project suggestions may have been stimulated by his request, over a year ago, for thesis project suggestions, of which he got many. If/when you get more info on those specific suggestions, perhaps you could add some of it to the Wiki. As to startup: while 2.4 is generally faster than 2.3, etc, the time it takes to get to the first line of code increased, due to behind-the-scenes imports and maybe something else. There was some discussion of this on the Python development list (gatewayed to gmane.lang.python.devel). I think the consensis was that this was not good, but that a real fix, if one was possible, required a more thorough reexamination of the startup process than any developer could do when 2.4 was otherwise ready to be released. But check the pydev archives. Terry J. Reedy From ksenia.marasanova at gmail.com Sun Jun 12 13:05:26 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Sun, 12 Jun 2005 19:05:26 +0200 Subject: Code documentation tool similar to what Ruby (on Rails?) uses In-Reply-To: <1118589134.311882.5490@z14g2000cwz.googlegroups.com> References: <1118589134.311882.5490@z14g2000cwz.googlegroups.com> Message-ID: <130df193050612100513345c7b@mail.gmail.com> 12 Jun 2005 08:12:14 -0700, Michele Simionato : > What about doing it yourself? > > >>> import inspect, os > >>> print "

%s
" % inspect.getsource(os.makedirs) That's easy, thanks! I guess I'll submit a patch for Epydoc with the functionality I've mentioned :) -- Ksenia From news at NOwillmcguganSPAM.com Wed Jun 22 10:14:18 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 22 Jun 2005 15:14:18 +0100 Subject: Database recommendations for Windows app Message-ID: <42b97240$0$24467$da0feed9@news.zen.co.uk> Hi, I'd like to write a windows app that accesses a locally stored database. There are a number of tables, the largest of which has 455,905 records. Can anyone recommend a database that runs on Windows, is fast / efficient and can be shipped without restrictions or extra downloads? I have googled and found plenty of information on databases, its just that I dont have enough experience with databases to know which one is best for my task! Thanks in advance, Will McGugan -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From beliavsky at aol.com Fri Jun 10 06:39:55 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 10 Jun 2005 03:39:55 -0700 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> Message-ID: <1118399995.306455.161220@o13g2000cwo.googlegroups.com> wooks wrote: > I thought that posting a link that contained the word ebay and a > subject title of Python Developers Handbook conveyed all the relevant > information and didn't want to patronise the NG. > > I have had 110 hits on the item but seem to have upset 3 people. This statement shows a misunderstanding of Usenet. Maybe the majority of comp.lang.python readers agree with Terry Reedy but did not want to clog the newsgroup with ditto messages. From jan.danielsson at gmail.com Thu Jun 9 18:03:35 2005 From: jan.danielsson at gmail.com (Jan Danielsson) Date: Fri, 10 Jun 2005 00:03:35 +0200 Subject: A question about time In-Reply-To: <11ahc8fntjhiad5@corp.supernews.com> References: <42a8ac25@griseus.its.uu.se> <11ahc8fntjhiad5@corp.supernews.com> Message-ID: <42a8bb73$1@griseus.its.uu.se> Grant Edwards wrote: >>In C, I would do this: >> >>server.invalidUntil = time(NULL) + 5*60; // five minute delay > > In Python, I would do this: > > server.invalidUntil = time.time() + 5*60 # five minute delay Ah. Well. Um. I feel like an idiot. I found datetime by accident, and thought "it involves time, so this must be what I'm looking for!". Anyway; thanks, that was exactly what I was looking for. From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 6 16:22:24 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 06 Jun 2005 22:22:24 +0200 Subject: split up a list by condition? Message-ID: <3gjpk0FcrnknU1@individual.net> Hi, while writing my solution for "The python way?", I came across this fragment: vees = [c for c in wlist[::-1] if c in vocals] cons = [c for c in wlist[::-1] if c not in vocals] So I think: Have I overlooked a function which splits up a sequence into two, based on a condition? Such as vees, cons = split(wlist[::-1], lambda c: c in vocals) Reinhold From jeffelkins at earthlink.net Wed Jun 1 08:49:52 2005 From: jeffelkins at earthlink.net (Jeff Elkins) Date: Wed, 1 Jun 2005 08:49:52 -0400 Subject: xml processing Message-ID: <200506010849.52229.jeffelkins@earthlink.net> I've like to use python to maintain a small addressbook which lives on a Sharp Zaurus. This list will never grow beyond 200 or so entries. I've installed pyxml. Speaking generally, given a wxpython app to do data entry, I'm planning to: 1. parse the addressbook file, loading its data into an array. 2. Perform any edit operations within the array. 3. Write out a finished xml file from the array when I'm done. Is this reasonable? Better, smarter ways to accomplish this? Thanks for any advice. Jeff Elkins From gdamjan at gmail.com Wed Jun 22 13:33:36 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 22 Jun 2005 19:33:36 +0200 Subject: MySQLdb reconnect Message-ID: <42b9a0d0_2@x-privat.org> Does MySQLdb automatically reconnect if the connection to the database is broken? I'm asking this since I have a longrunning Python precess that is connected to Mysql-4.1.11, and I execute "set names utf8" when I connect to it. But after running a day the results from the python program were displayed as if the "set names utf8" was not executed i.e. I got question marks where utf-8 cyrillics should've appeared. After restarting the Python program everything was ok, just as when I first started it. The long running Python process is actually a scgi quixote web application. -- damjan From steve.horsley at gmail.com Fri Jun 10 18:44:31 2005 From: steve.horsley at gmail.com (Steve Horsley) Date: Fri, 10 Jun 2005 23:44:31 +0100 Subject: a question from a newcomer to this language In-Reply-To: References: Message-ID: Michael Chermside wrote: > Shankar writes: > >>Is there any way to convert a string into an instruction that will be >>executed? > > > Short answer: > Yes. The exec statement does what you want: > > >>>>x = 3 >>>>y = 4 >>>>exec "z = x * y" >>>>print z > > 12 > Ooh! I didn't know that one. I have to admit that it gives me an uneasy feeling. How woud the author of "z = x * y" know that z was safe to assign to? To Shankar: An intermediate is eval: z = eval("x * y") but even this is unsafe if you do not vet the input strings: String s = "system('format c: /y')" z = eval(s) Steve From python-url at phaseit.net Wed Jun 29 15:08:03 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 29 Jun 2005 19:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 29) Message-ID: QOTW: "And what defines a 'python activist' anyway? Blowing up Perl installations worldwide?" - Ivan Van Laningham "Floating point is about nothing if not being usefully wrong." - Robert Kern Sibylle Koczian needs to sort part of a list. His first attempt made the natural mistake - sorting a *copy* of part of the list: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9b7da3bed2719f18 Kevin Dangoor compares ZODB and pysqlite with SQLObject: http://www.blueskyonmars.com/2005/06/18/zodb-vs-pysqlite-with-sqlobject/ Uwe Mayer needs a little convincing about "consenting adults" philosophy: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d4d8738a6e8281ff Zope 2.8.0 is released: http://article.gmane.org/gmane.comp.web.zope.announce/987 Guido's ITC audio interview sparks off a discussion about the advantages of static typing in terms of tool support: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5aee06316a0412b Only c.l.py can go *this* far off topic without flames: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1be27ccd50534e1b Is there any good stuff left that Python should steal from other languages? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d297170cfbf1bb34 Peter Gengtsson reminds himself and us how useful the \b regular expression special element is: http://www.peterbe.com/plog/slash_b Are there any 3rd party modules that you'd like to see included in the standard library? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cd236084973530dc Is Python a good language for teaching children to program? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/68a3ac09b4937c88 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From fuzzyman at gmail.com Wed Jun 1 09:42:59 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 Jun 2005 06:42:59 -0700 Subject: how to convert string to list or tuple In-Reply-To: References: Message-ID: <1117633379.649380.261120@z14g2000cwz.googlegroups.com> flyaflya wrote: > a = "(1,2,3)" > I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', > '2', ',', '3', ')') not (1,2,3) Probably a bit late... but there's always listquote - It's part of the pythonutils module. http://www.voidspace.org.uk/python/pythonutils.html It will turn strings to lists, including nested lists. Best Regards, Fuzzy http://www.voidspace.org.uk/python From gsakkis at rutgers.edu Thu Jun 30 15:33:46 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 30 Jun 2005 12:33:46 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> <1120084451.475909.19390@o13g2000cwo.googlegroups.com> Message-ID: <1120160026.356015.206440@g47g2000cwa.googlegroups.com> "Tom Anderson" wrote: > if it hadn't been for the quirks of the Cockney accent, we'd all be using curly > brackets and semicolons. +1 QOTW George From peter at engcorp.com Sun Jun 5 21:33:49 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 05 Jun 2005 21:33:49 -0400 Subject: Destructive Windows Script In-Reply-To: References: Message-ID: rbt wrote: > Chris Lambacher wrote: > >> The reason they are slow and tedious is that they need to write to >> every byte on the disk. Depending on the size of the disk, there may >> be a lot of data that needs to be written, and if they are older >> computers, write speed may not be particularly fast. > > > OK, I accept that, but if you have a HDD that's 8GB total and it has 1GB > of files, why must every byte be written to? Why not just overwrite the > used portion? What do you think is in the "unused" space, given that much of it likely had files at some time in the past, maybe even older copies of some of the files that are currently "live"? If you haven't wiped all those files previously, their data is still quite accessible. -Peter From gregpinero at gmail.com Thu Jun 9 08:37:19 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Thu, 9 Jun 2005 08:37:19 -0400 Subject: MySQLDBAPI Message-ID: <312cfe2b05060905373f32de35@mail.gmail.com> Hey guys, I'm trying to install the MySQLDB API at my web host. I only have limited permissions on the system so I want to install it in my home directory. I'm having a lot of trouble though. My first question is if there is anything built into python as far as a Database API that will work with MySQL. It seems like there should be because Python without it is kinda useless for web development. If there is then I'd probably prefer to use that instead. My next question is, any idea why my install attempts below don't work? Here's my system info: >>> print sys.version 2.4.1 (#1, Jun 6 2005, 13:31:05) [GCC 2.96 20000731 (Red Hat Linux 7.2 2.96-112.7.2)] Here are the steps I've taken trying to install it: 1. Download MySQL-python-1.2.0.tar.gz from project page into my home directory http://sourceforge.net/projects/mysql-python 2. tar xvzf MySQL-python-1.2.0.tar.gz 3. Do these commands: >> cd MySQL-python-1.2.0 >> python2.4 setup.py install --home=~ running install running build running build_py running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.4 -c _mysql.c -o build/temp.linux-i686-2.4/_mysql.o -I'/usr/local/mysql/include/mysql' _mysql.c:41:19: mysql.h: No such file or directory _mysql.c:42:26: mysqld_error.h: No such file or directory _mysql.c:43:20: errmsg.h: No such file or directory error: command 'gcc' failed with exit status 1 4. I also tried running build: >> python2.4 setup.py build running build running build_py running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python2.4 -c _mysql.c -o build/temp.linux-i686-2.4/_mysql.o -I'/usr/local/mysql/include/mysql' _mysql.c:41:19: mysql.h: No such file or directory _mysql.c:42:26: mysqld_error.h: No such file or directory _mysql.c:43:20: errmsg.h: No such file or directory error: command 'gcc' failed with exit status 1 (I don't know if I need to run build first or what) I found some help on http://docs.python.org/inst/inst.html but I don't really understand what it's talking about. I also read the README file in the download but it didn't help either. Any ideas would be greatly appriciated. Thanks, Greg From cjw at sympatico.ca Fri Jun 17 08:59:40 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 17 Jun 2005 08:59:40 -0400 Subject: New WYSIWYG Python IDE in the works In-Reply-To: References: <1118857896.992449.294690@z14g2000cwz.googlegroups.com> Message-ID: Steve Holden wrote: > Cappy2112 wrote: > >> This is great, but it might be worth finding out what the other IDE's >> can do first, as well as their weaknesses. >> >> Eric3 seems to be the most popular & powerfull. Uop until recentluy, it >> onluy works on Linux, but has been compiled & runnin on Windows, to >> some degree of success. >> >> QTDesigner is pretty good. >> >> There's also Boa Constructor, and a handfull of other IDE's. >> > I's suggest the Boa Constructor be classed with [wx?]Glade and > PythonCard as GUI builders, though I must confess I am not fully up to > date on Boa developments. It is true that Boa has a heavy GUI development component but it is also analogous to PythonWin with the benefit that it works with Linux and has some other useful features. One minor weakness is that when debugging the interactive actions are not in the local context. Colin W. > > must-look-at-eric-sometime-ly y'rs - steve From piet at cs.uu.nl Fri Jun 17 06:21:38 2005 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 17 Jun 2005 12:21:38 +0200 Subject: How to right align IPaddress? References: Message-ID: >>>>> praba kar (pk) wrote: >pk> Dear all, >pk> Is it possible to right align >pk> the Ipaddress? Normally we can >pk> right align the list of numbers >pk> by %3u or %7u. How we can right >pk> align the Ipaddress? >pk> I expects below format output >pk> eg 203.199.200.0 >pk> 203.33.20.0 "%15s" % ip -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP] Private email: piet at vanoostrum.org From trentm at ActiveState.com Wed Jun 22 19:42:54 2005 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 22 Jun 2005 16:42:54 -0700 Subject: PEP 304 - is anyone really interested? In-Reply-To: <17081.60895.24439.92843@montanaro.dyndns.org> References: <17081.60895.24439.92843@montanaro.dyndns.org> Message-ID: <20050622234254.GB13632@ActiveState.com> [Skip Montanaro wrote] > > I wrote PEP 304, "Controlling Generation of Bytecode Files": > > http://www.python.org/peps/pep-0304.html > > ... > So speak up folks, otherwise my recommendation is that it be put out of its > misery. I've had use for it before, but have managed to work around the problems. I think it is a good feature, but I wouldn't have the time to shepherd the patch. Trent -- Trent Mick TrentM at ActiveState.com From nav+posts at bandersnatch.org Wed Jun 1 13:57:53 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: 01 Jun 2005 13:57:53 -0400 Subject: Python analog of Ruby on Rails? References: <4294adc3$0$2526$626a14ce@news.free.fr> <1117073580.063476.125140@g14g2000cwa.googlegroups.com> <4295ed71$0$6932$626a14ce@news.free.fr> Message-ID: <87y89udkny.fsf@localhost.localdomain> bruno modulix writes: > Err... Looks like I've seen this before, but where ??? Don't know, but it looks sort of familiar... Nick -- # sigmask (lambda deprecation version) 20041028 || feed this to a python print ''.join([chr(ord(x)-1) for x in 'Ojdl!Wbshjti!=ojdlAwbshjti/psh?']) From philippe at philippecmartin.com Mon Jun 27 18:31:01 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 27 Jun 2005 22:31:01 GMT Subject: SCF 1.1 with BasicCard support released Message-ID: Dear all, I am very happy to announce the release of SCF 1.1, a Python based Smart Card development framework for Windows? and Linux. SCF 1.1 introduces support for BasicCard? Enhanced and Professional under GNU/Linux and Windows?. All commands are supported as well as firmware image parsing so you have full control of the personalization process: application + data. The SCF Shell is now "BasicCard-aware". SCF is available on www.snakecard.com for download and free testing. You may also browse the reference guide online. Best regards, Philippe Martin From Scott.Daniels at Acm.Org Thu Jun 16 11:18:48 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 16 Jun 2005 08:18:48 -0700 Subject: Set of Dictionary In-Reply-To: References: Message-ID: <42b1911e$1@nntp0.pdx.net> Vibha Tripathi wrote: > Hi Folks, > > I know sets have been implemented using dictionary but > I absolutely need to have a set of dictionaries...any > ideas how to do that? > > Peace. > Vibha > > "Things are only impossible until they are not." > > > > __________________________________ > Discover Yahoo! > Find restaurants, movies, travel and more fun for the weekend. Check it out! > http://discover.yahoo.com/weekend.html > This is too bad. There is a problem even defining what you want. Assume we have a DictSet type: After: a = dict(a=1, b=2) b = dict(a=2, b=1) c = dict(b=2, a=1) ds = Dictset([a, b, c]) What is len(ds)? After those lines and: c['a'] = 2 What is len(ds)? After all the previous lines and: a['a'] = 2 b['b'] = 2 What is len(ds)? Making sets of mutable things is pretty useless. You could make sets of tuple(sorted(adict.items())) if the "adict"s don't have mutable values. --Scott David Daniels Scott.Daniels at Acm.Org From klachemin at comcast.net Tue Jun 28 23:23:43 2005 From: klachemin at comcast.net (Kamilche) Date: 28 Jun 2005 20:23:43 -0700 Subject: OO refactoring trial ?? References: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> <0001HW.BEE6FEEE000C427BF0407550@news.gmane.org> Message-ID: <1120015423.318185.95600@g14g2000cwa.googlegroups.com> ''' You might find this interesting. Note that the object creation in main() below could easily be read in from a text file instead, thus meeting your requirement of not knowing an item's class until runtime. Sample output: {'password': 'Your Password Here', 'type': 'A', 'logonid': 'Your Logonid Here'} # did A # {'ssn': 555555555, 'type': 'B'} # did B # {'type': 'BASE', 'address': '501 south street'} # did BASE # None ''' def Create(type = 'BASE', **kwargs): if type not in _CLASSES: return None # Or return a default object obj = _CLASSES[type](type = type, **kwargs) return obj class BASE(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) def __str__(self): return str(self.__dict__) def doit(self): print "# did BASE #" class A(BASE): def doit(self): print '# did A #' class B(BASE): def doit(self): print '# did B #' _CLASSES = {'BASE': BASE, 'A': A, 'B': B} def main(): obj1 = Create(type = 'A', logonid = 'Your Logonid Here', password = 'Your Password Here') print obj1 obj1.doit() obj2 = Create(type = 'B', ssn = 555555555) print obj2 obj2.doit() obj3 = Create(address = '501 south street') print obj3 obj3.doit() obj4 = Create(type = 'Missing') print obj4 main() From noreply at gcgroup.net Thu Jun 23 12:44:55 2005 From: noreply at gcgroup.net (William Gill) Date: Thu, 23 Jun 2005 16:44:55 GMT Subject: pass an event up to parent widget Message-ID: I have a Tkinter (frame) widget that contains several other frame widgets, each containing entry widgets. In the parent frame I have a 'save' button that is initially disabled. As it is now, each widget has a hasChanged property that I can poll to see if updates to the source data need to be made. hasChanged is set to True by an event routine in each frame widget, and this works fine for my exit routine which knows to poll each widget for hasChanged. What I don't know how to do is send an event up the chain to the top so it can change the 'save' button to NORMAL (telling the user 'The data has been changed and can be saved if wanted') . I don?t think bind_class() to all entry widgets is the way to go. I could create an after() alarm callback to poll hasChanged, but again this seems to awkward. I have looked at widget.event_add() but, don't know if this is viable. I am thinking a virtual event without any SEQUENCE, and then triggering it programmatically (from within the sub-widget event handlers). Is that doable? Isn't there a better way? Any suggestions? Bill From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 6 15:01:47 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 06 Jun 2005 21:01:47 +0200 Subject: the python way? In-Reply-To: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> References: <1118082472.473438.298290@g14g2000cwa.googlegroups.com> Message-ID: <3gjksrFcmvf4U1@individual.net> Grooooops wrote: > Hi All, > > I've been lurking the list for a month and this is my first post. I am > hoping this post is appropriate here, otherwise, my apologies. > > I'm somewhat new to Python, (I'm reading all the tutorials I can find, > and have read through Andre Lessa's Developers Handbook.) > I am trying to learn the Python way of thinking as well as the syntax. > > I popped this bit of code together for fun, based on a previous post > regarding randomizing a word. > This shuffles a word, then splits out the vowels and then reassembles > it with the vowels interpolated between consonants. > (To create plausible sounding gibberish) To make it short, my version is: import random def reinterpolate2(word, vocals='aeiouy'): wlist = list(word) random.shuffle(wlist) vees = [c for c in wlist[::-1] if c in vocals] cons = [c for c in wlist[::-1] if c not in vocals] short, long = sorted((cons, vees), key=len) return ''.join(long[i] + short[i] for i in range(len(short))) + ''.join(long[len(short):]) > The code just seems kind of bulky to me. I am wondering, is this an > efficient way to do things, or am I making things harder than > necessary? Some comments on your code: > #--------------------------begin code------------------ > """scrambles a word, but creates plausable gibberish""" > import random > def shuffled(s): > """ scrambles word""" > l = list(s) > random.shuffle(l) > return ''.join(l) You can define this function separately, but needn't. > def contains(alist,b): > """...is letter b in list a...""" > ret = [] > for all in alist: > #print all > if all==b: > return 1 > return 0 That is entirely unnecessary - use "b in alist" :) > def newZip(a1,a2): > """ reassemble """ > l1=len(a1) > l2=len(a2) > > longest = [a1,a2][l1 shortest = [a1,a2][longest == a1] > diff = max(l1,l2)-min(l1,l2) diff = abs(l2-l1) would be shorter. > #print longest > seq = len(longest) > ret = "" > for j in range(seq): > if len(longest)>0: > ret = ret + longest.pop() ret += longest.pop() comes to mind. > if len(shortest)>0: > ret = ret + shortest.pop() > return ret > > def reinterpolate(word): > """ main function """ > wlist = shuffled(list(word)) shuffled() will make a list itself, so list() is superfluous here. > vlist = list('aeiouy') # ok, y isn't really a vowel, but... > vees = filter(lambda x: contains(vlist,x),wlist) Use a list comprehension here, like above. > cons = filter(lambda x: not(contains(vlist,x)),wlist) > a=list(vees) > b=list(cons) > return newZip(a,b) > > word = "encyclopedia" > print reinterpolate(word) > > #-------------------------------end code--------------------------- From martin.witte at gmail.com Wed Jun 8 10:02:18 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 8 Jun 2005 07:02:18 -0700 Subject: different time tuple format In-Reply-To: References: <1118173244.732925.9080@f14g2000cwb.googlegroups.com> Message-ID: <1118239337.961657.242660@g49g2000cwa.googlegroups.com> The names are at least platform specific, see below the names of the timezones on my Windows NT 4 box *** Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 *** Type "help", "copyright", "credits" or "license" for more information. *** >>> import time *** >>> print time.tzname *** ('W. Europe Standard Time', 'W. Europe Daylight Time') *** >>> From prashanthellina at gmail.com Thu Jun 9 10:03:11 2005 From: prashanthellina at gmail.com (Prashanth Ellina) Date: 9 Jun 2005 07:03:11 -0700 Subject: Another solution to How do I know when a thread quits? In-Reply-To: References: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> <0umdnaKeMsKDOTjfRVn-gA@powergate.ca> Message-ID: <1118325791.364271.96590@g14g2000cwa.googlegroups.com> Hi, Thanks for the code sample. I will try it out. I guess there is no reliable way to get away with just the "threads" module. Thanks, Prashanth Ellina From twic at urchin.earth.li Thu Jun 30 13:00:01 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Thu, 30 Jun 2005 18:00:01 +0100 Subject: Boss wants me to program In-Reply-To: References: Message-ID: On Wed, 29 Jun 2005, phil wrote: >> Wow! How about a sextant? Simple device really. And a great practical >> demonstration of trigonometry. > > Excellent idea, even found a few how to sites. We'll do it. > Any others? A ballista? For many years when i was a kid, my dad wanted to build a ballista; he collected loads of literature on it. There's a surprising amount of maths involved - the Greeks actually devised instruments for computing cube roots in order to do it! Perhaps not an ideal project for schoolkids, though. tom -- How did i get here? From jjl at pobox.com Wed Jun 1 18:56:53 2005 From: jjl at pobox.com (John J. Lee) Date: 01 Jun 2005 22:56:53 +0000 Subject: Pressing A Webpage Button References: Message-ID: <87is0x7kju.fsf@pobox.com> Elliot Temple writes: > How do I make Python press a button on a webpage? I looked at > urllib, but I only see how to open a URL with that. I searched > google but no luck. [...] You might find the FAQ list and hints below useful after you get over the initial barriers (and the modules at the same site): http://wwwsearch.sourceforge.net/bits/GeneralFAQ.html http://wwwsearch.sourceforge.net/ClientCookie/doc.html#debugging John From hancock at anansispaceworks.com Sun Jun 26 06:29:49 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sun, 26 Jun 2005 05:29:49 -0500 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <200506260529.49224.hancock@anansispaceworks.com> On Saturday 25 June 2005 01:08 pm, Steven D'Aprano wrote: > Using := and = for assignment and equality is precisely as stupid as using > = and == for assignment and equality. Perhaps less stupid: why do we use > == for equals, but not ++ for plus and -- for minus? Probably the most pointless Python wart, I would think. The =/== distinction makes sense in C, but since Python doesn't allow assignments in expressions, I don't think there is any situation in which the distinction is needed. Python could easily figure out whether you meant assignment or equality from the context, just like the programmer does. BASIC did it that way, IIRC. It always seemed like C was seriously twisted for letting you get away with assignment in expressions in the first place. I don't think Python's use of "==" has *ever* helped me find a bug, it just creates them. I really think "=" ought to be accepted as well, and "==" deprecated. But, hey, nobody asked me, I guess. And it doesn't kill me to type the extra "=". ;-) Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From jeff.maitland at gmail.com Thu Jun 30 15:32:17 2005 From: jeff.maitland at gmail.com (Jeffrey Maitland) Date: Thu, 30 Jun 2005 15:32:17 -0400 Subject: Seeking IDE In-Reply-To: References: Message-ID: <6829832e050630123275f71324@mail.gmail.com> I am currently using synEdit. That is because it is a free, small, and very customizable and highlites pythn keywords.(and was on the system at work) Where as at home I use Emacs, or GNUEmacs (depends on which boot up I chose at the time). Jeff From rkern at ucsd.edu Mon Jun 27 00:41:02 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 26 Jun 2005 21:41:02 -0700 Subject: Favorite non-python language trick? In-Reply-To: <200506262322.00250.hancock@anansispaceworks.com> References: <200506260559.18488.hancock@anansispaceworks.com> <200506262322.00250.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > On Sunday 26 June 2005 06:11 am, Robert Kern wrote: > >>Terry Hancock wrote: >> >>>On Sunday 26 June 2005 05:39 am, Torsten Bronger wrote: >>> >>>>However, then you must forbid a=b=1 for assigning to two variables >>>>at the same time. >> >>You need to differentiate >> a = b = 1 >>from >> a = b == 1 > > Okay, I see what you mean. I can't ever recall having needed the > second form, though. I use it all the time with Numeric's rich comparisons. mask = some_arr == 999 > Of course, you could still do assignment like this: > > a, b = (1,)*2 > > But I guess that's not exactly elegant. ;-) Ya think? :-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org Mon Jun 20 08:23:05 2005 From: wyrmwif at tango-sierra-oscar-foxtrot-tango.fake.org (SM Ryan) Date: Mon, 20 Jun 2005 12:23:05 -0000 Subject: references/addrresses in imperative languages References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: <11bdd99imhpus06@corp.supernews.com> # easy way to see this, is to ask yourself: how come in mathematics # there's no such thing as "addresses/pointers/references". The whole point of Goedelisation was to add to name/value references into number theory. Thus Goedel was able to add back pointers contrary to the set hierarchy of the theory of types and reintroduce Russel's paradox. -- SM Ryan http://www.rawbw.com/~wyrmwif/ The little stoner's got a point. From xah at xahlee.org Mon Jun 27 06:33:29 2005 From: xah at xahlee.org (Xah Lee) Date: 27 Jun 2005 03:33:29 -0700 Subject: turn text lines into a list Message-ID: <1119868409.705810.227400@g49g2000cwa.googlegroups.com> i have a large number of lines i want to turn into a list. In perl, i can do @corenames=qw( rb_basic_islamic sq1_pentagonTile sq_arc501Tile sq_arc503Tile ); use Data::Dumper; print Dumper(\@corenames); ---------- is there some shortcut to turn lines into list in Python? Xah xah at xahlee.org ? http://xahlee.org/ From bob at passcal.nmt.edu Sun Jun 5 15:32:31 2005 From: bob at passcal.nmt.edu (Bob Greschke) Date: Sun, 5 Jun 2005 13:32:31 -0600 Subject: tkinter, option_add, entry field trouble References: Message-ID: Yahoo! That was it. When is Grayson coming out with a new version of "Python and Tkinter Programming"? Mine is getting pretty full of pen & ink changes. :) Nice tip, too! Thanks! wrote in message news:mailman.12.1117998826.10512.python-list at python.org... I think you have to spell it Root.option_add("*Entry*highlightThickness", "2") Root.option_add("*Entry*highlightColor", "green") When you're not sure of the capitalization, do something like this interactively: >>> e.configure('highlightcolor') ('highlightcolor', 'highlightColor', 'HighlightColor', 'SystemWindowFrame', 'green') When you use 'configure' this way, the *second* string has the correct capitalization for use in option_add. The fourth is the system default before taking into account the option database, and the last is the current value. Jeff From chinook.nr at tds.net Wed Jun 29 00:30:50 2005 From: chinook.nr at tds.net (Chinook) Date: Wed, 29 Jun 2005 00:30:50 -0400 Subject: OO refactoring trial ?? References: <1119968579.049502.68280@g43g2000cwa.googlegroups.com> <0001HW.BEE6FEEE000C427BF0407550@news.gmane.org> <1120015423.318185.95600@g14g2000cwa.googlegroups.com> Message-ID: <0001HW.BEE79C3A001AB4E9F0407550@news.gmane.org> On Tue, 28 Jun 2005 23:23:43 -0400, Kamilche wrote (in article <1120015423.318185.95600 at g14g2000cwa.googlegroups.com>): > ''' > You might find this interesting. Note that the object creation in > main() below could easily be read in from a text file instead, > thus meeting your requirement of not knowing an item's class > until runtime. > > Sample output: > > {'password': 'Your Password Here', 'type': 'A', 'logonid': 'Your > Logonid Here'} > # did A # > {'ssn': 555555555, 'type': 'B'} > # did B # > {'type': 'BASE', 'address': '501 south street'} > # did BASE # > None > ''' > > def Create(type = 'BASE', **kwargs): > if type not in _CLASSES: > return None # Or return a default object > obj = _CLASSES[type](type = type, **kwargs) > return obj > > class BASE(object): > def __init__(self, **kwargs): > self.__dict__.update(kwargs) > def __str__(self): > return str(self.__dict__) > def doit(self): > print "# did BASE #" > > class A(BASE): > def doit(self): > print '# did A #' > > class B(BASE): > def doit(self): > print '# did B #' > > _CLASSES = {'BASE': BASE, 'A': A, 'B': B} > > def main(): > obj1 = Create(type = 'A', logonid = 'Your Logonid Here', password = > 'Your Password Here') > print obj1 > obj1.doit() > obj2 = Create(type = 'B', ssn = 555555555) > print obj2 > obj2.doit() > obj3 = Create(address = '501 south street') > print obj3 > obj3.doit() > obj4 = Create(type = 'Missing') > print obj4 > > main() > > Kamilche, Yes it is interesting and explicit, thank you. What I was not clear enough about though, is that at runtime the class object creation depends on the information being processed. That is, the context and type of node in the recursed tree. That's why in my trial the potential classes all included a "testit" method and the order of testing is important. Beyond that the "doit" methods all have some varying duplicated expressions, so I was constructing their functionality with code objects. However, in going back over researched material after Paul's comments I noticed another technique that might be better in creating functionality and have to study it further. Thanks for the sample, Lee C From jeremy+plusnews at jeremysanders.net Thu Jun 16 12:53:30 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Thu, 16 Jun 2005 17:53:30 +0100 Subject: Subprocess and time-out References: <42b1ace9$0$4979$636a15ce@news.free.fr> Message-ID: On Thu, 16 Jun 2005 18:36:52 +0200, Gilles Lenfant wrote: > Grabbing the various docs of Python, I didn't find how to do this : > > I Use popen2 to run wvware that transforms lots of M$ word docs to plain > text. Sometimes wvware runs in a deadlock and I can't control this from > Python app. > > I need to stop wvware processing after 30 seconds (considered deadlocked) > and to process the next file. > > Unfortunately, I didn't find any pythonic stuff to control the time spent > runnning subprocesses (and kill'em if needed) launched with popen. > > An hint is welcome. Many thanks by advance. Is this Unix? If you're using the Popen3/Popen4 objects from popen2 module, you could take the pid of the popened process, and fork your program. In the forked child process you could wait for an interval, then do os.wait with W_NOHANG to see whether the process has stopped, and if not kill it with os.kill. Jeremy From felix.schwarz at web.de Sat Jun 25 11:59:42 2005 From: felix.schwarz at web.de (Felix Schwarz) Date: Sat, 25 Jun 2005 16:59:42 +0100 Subject: regex question Message-ID: <3i59q5Fjm0hsU1@individual.net> Hi all, I'm experiencing problems with a regular expression and I can't figure out which words I use when googling. I read the python documentation for the re module multiple times now but still no idea what I'm doing wrong. What I want to do: - Extract all digits (\d) in a string. - Digits are separated by space (\w) What my program does: - It extracts only the last digit. Here is my program: import re line = ' 1 2 3' regex = '^' + '(?:\s+(\d))*' + '$' match = re.match(regex, line) print "lastindex is: ",match.lastindex print "matches: ",match.group(1) Obviously I do not understand how (?:\s+(\d))* works in conjunction with ^ and $. Does anybody know how to transform this regex to get the result I want to have? fs From tjreedy at udel.edu Fri Jun 3 14:22:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 3 Jun 2005 14:22:12 -0400 Subject: optparse.py: FutureWarning error References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> <1117765604.103092.154190@g47g2000cwa.googlegroups.com> <42a02aba$1_3@newspeer2.tds.net> Message-ID: "Kent Johnson" wrote in message news:42a02aba$1_3 at newspeer2.tds.net... > Terry Reedy wrote: >> "kosuke" wrote in message >> news:1117765604.103092.154190 at g47g2000cwa.googlegroups.com... >> >>>man python --- >>> >>>COMMAND LINE OPTIONS >> >> >> This should REALLY be on the doc page of the Python site. > > Hear, hear! I never even knew this existed! > > Where should it go in the docs? In the Language Reference or the Tutorial > or...? Since the Tutorial already has section 2. Using the Python Interpreter that discusses a few of the switches, I would add it as an appendix with a reference to the appendix at the end of the appropriate subsection. Perhaps I will submit a tracker item. Terry J. Reedy From __peter__ at web.de Sun Jun 26 02:35:58 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 26 Jun 2005 08:35:58 +0200 Subject: Favorite non-python language trick? References: <3i232vFj0b57U1@individual.net> Message-ID: Steven D'Aprano wrote: > On Sat, 25 Jun 2005 21:30:26 +0200, Peter Otten wrote: > >> Mandus wrote: >> >>> By using the builtin reduce, I >>> move the for-loop into the c-code which performs better. >> >> No. There is no hope of ever writing fast code when you do not actually >> measure its performance. > > Good grief! You've been spying on Mandus! How else could you possibly know > that he doesn't measure performance? Are you running a key-logger on his > machine? *wink* His mentioning reduce() as a performance panacea was a strong indication even without looking over his shoulders. He filled in some conditions in a later post, but "[U]sing reduce ... performs better [than a for-loop]" is just wrong. > For the record, perhaps now is a good time to mention that even Guido > recommended the use of map, filter and reduce in some circumstances: Personally I wouldn't rely on authority when I can measure without much hassle. And the lesson I take from Guido's essay is rather how he got to his conclusions than what his actual findings were. After all, Python may have advanced a bit since he wrote the text. > Do we really need to profile our code every single time to know this? No. Only if we care about the performance of a particular piece. And if we do we are sometimes in for a surprise. > Isn't it reasonable to just say, "I use join because it is faster than > adding strings" without being abused for invalid optimization? OK, I am making a guess: "".join(strings) is more often faster than naive string addition than reduce() wins over a for-loop. I don't think my pointed comment qualifies as "abuse", by the way. Peter From stephen.thorne at gmail.com Thu Jun 2 01:10:33 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 2 Jun 2005 15:10:33 +1000 Subject: scripting browsers from Python In-Reply-To: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> References: <1117525953.255166.234420@g14g2000cwa.googlegroups.com> Message-ID: <3e8ca5c805060122107ab4a8be@mail.gmail.com> On 31 May 2005 00:52:33 -0700, Michele Simionato wrote: > I would like to know what is available for scripting browsers from > Python. > For instance, webbrowser.open let me to perform GET requests, but I > would like > to do POST requests too. I don't want to use urllib to emulate a > browser, I am > interested in checking that browser X really works as intended with my > application. Any suggestion? > > Michele Simionato I use pbp, http://pbp.berlios.de/ It's essentially a python commandline webbrowser suitable for testing websites. It makes it easy to do things like: go http://user:pass at mywebsite/secure/ follow Admin follow Configure formvalue config max_widgets 300 submit config in a script, and then run that script at your lesuire. As it's designed for testing, everything you do is essnetial an assertion, so if anything fails it fails spectacularly with debug messages and non-zero exit codes. You can also load python code up so you can do arbitary stuff. -- Stephen Thorne Development Engineer From Me at Privacy.NET Thu Jun 2 03:49:16 2005 From: Me at Privacy.NET (Jeff_Relf) Date: 2 Jun 2005 07:49:16 GMT Subject: Like a star, I burn bright, dissipating into the night. References: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> <429e7155.6739473@news.alphalink.com.au> Message-ID: Hi phaywood, Re: Your grooving to this mantra of mine: Like a star, I burn bright, dissipating into the night. Seeing as you're in Comp.Lang.C, I'll express that in MicroSoft_C++ 7.1, slowly dissipating Sun into Night. I'm using special 32 bit random number routines here, but, because the appropriate graphics would be too much work, the results can only be viewed in a debugger. #pragma warning( disable: 4127 4508 ) #define WIN32_LEAN_AND_MEAN #include #define LOOP while ( 1 ) #define Loop( N ) int J = - 1, LLL = N ; while ( ++ J < LLL ) #define LoopD( N ) int J = N ; while( -- J ) #define Tics ( QueryPerformanceCounter( ( Quad * ) & _Tics ), _Tics ) typedef LARGE_INTEGER Quad ; typedef int * int_P ; const int HighResQual = 0x400, DecM = HighResQual* 4- 1, LongLeg = 63 , Short_Leg = 37, BothLegs = LongLeg + Short_Leg , Seed_Buf_Sz = 2 * BothLegs - 1, StopBit = 1 << 30 , EvenBits = StopBit - 2, Rand_Mask = StopBit - 1 ; int LegsBuf [ BothLegs ], HighResBuf [ HighResQual ]; int_P RanE = HighResBuf + BothLegs, RanP ; __int64 _Tics ; Deal(); Shuffle () { int StreamSperation = 70 - 1, Seed_Buf[ Seed_Buf_Sz ] , Seed = int( Tics ), Seed_2 = Seed + 2 & EvenBits; RanP = RanE ; { Loop( BothLegs ) { Seed_Buf[ J ] = Seed_2 ; Seed_2 <<= 1 ; if ( Seed_2 >= StopBit ) Seed_2 -= EvenBits; } } ZeroMemory( Seed_Buf + BothLegs, ( BothLegs - 1 ) * 4 ); Seed_Buf[ 1 ] ++ ; Seed_2 = Seed & Rand_Mask ; LOOP { { LoopD( BothLegs ) Seed_Buf[ 2 * J ] = Seed_Buf[ J ]; } { int_P P = Seed_Buf + 1, R = Seed_Buf + Seed_Buf_Sz - 1 ; Loop( BothLegs - LongLeg / 2 - 1 ) P[ 2 * J ] = R [ -2 * J ] & EvenBits ; } { int_P B = Seed_Buf, P = B + Seed_Buf_Sz, R = B + Short_Leg - 1 ; LoopD( BothLegs ) { if ( ! ( * -- P & 1 ) ) continue; R [ J ] = R [ J ] - * P & Rand_Mask ; B [ J - 1 ] = B [ J - 1 ] - * P & Rand_Mask; } } if ( Seed_2 & 1 ) { memmove( Seed_Buf + 1, Seed_Buf, BothLegs * 4 ); * Seed_Buf = Seed_Buf [ BothLegs ]; if ( Seed_Buf [ BothLegs ] & 1 ) Seed_Buf [ Short_Leg ] = Seed_Buf [ Short_Leg ] - Seed_Buf[ BothLegs ] & Rand_Mask ; } if ( ! Seed_2 && ! -- StreamSperation ) break ; Seed_2 >>= 1 ; } memmove( LegsBuf, Seed_Buf + Short_Leg, LongLeg * 4 ); memmove( LegsBuf + LongLeg, Seed_Buf, Short_Leg * 4 ); Deal(); } int Deal() { if ( ! RanP ) Shuffle(); if ( RanP && RanP < RanE ) return * RanP ++ ; RanP = HighResBuf ; memmove( HighResBuf, LegsBuf, sizeof LegsBuf ); { Loop( HighResQual - BothLegs ) HighResBuf [ J + BothLegs ] = HighResBuf [ J ] - HighResBuf [ J + LongLeg ] & Rand_Mask ; } int_P P = HighResBuf + HighResQual - Short_Leg; { Loop( Short_Leg ) LegsBuf [ J ] = P [ J - LongLeg ] - P [ J ] & Rand_Mask ; } P = HighResBuf + HighResQual - LongLeg ; Loop( LongLeg ) LegsBuf [ J + Short_Leg ] = P [ J ] - LegsBuf [ J ] & Rand_Mask ; return * RanP ++ ; } inline float Rand() { return Deal() / ( float ) Rand_Mask ; } main() { double Star = 1e308, Night = 0 ; LOOP { float Dissipation = Rand(); if ( Star < Dissipation ) { Star = 0 ; return ; } Star -= Dissipation, Night += Dissipation ; } } From dalke at dalkescientific.com Mon Jun 6 14:42:51 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 06 Jun 2005 18:42:51 GMT Subject: Software licenses and releasing Python programs for review References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: max: >> For me, the fact >> that corporations are considered people by the law is ridiculous. Steven D'Aprano wrote: > Ridiculous? I don't think so. Take, for example, Acme Inc. Acme purchases > a new factory. Who owns the factory? The CEO? The Chairperson of the Board > of Directors? Split in equal shares between all the directors? Split > between all the thousands of shareholders? Society has to decide between > these methods. Getting off-topic for c.l.py. Might want to move this to, for example, the talk thread for http://en.wikipedia.org/wiki/Corporate_personhood which is http://en.wikipedia.org/wiki/Talk:Corporate_personhood and read also http://en.wikipedia.org/wiki/Corporation Andrew dalke at dalkescientific.com From dreamingpython at 163.com Thu Jun 9 22:28:54 2005 From: dreamingpython at 163.com (ÒÊÃÉɽÈË) Date: Fri, 10 Jun 2005 10:28:54 +0800 Subject: how to operate the excel by python? Message-ID: i want to compare the content in excel,but i don't know whick module to use! can you help me? From lkirsh at cs.ubc.ca Wed Jun 8 00:11:25 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Tue, 07 Jun 2005 21:11:25 -0700 Subject: reloading my own modules In-Reply-To: References: Message-ID: Hi, Skip Montanaro wrote: > Also, since it's clear you have already imported dbtest and util, there's no > need to check in sys.modules: > > import dbtest, util > reload(dbtest) > reload(util) Won't this load the modules twice on the first run? I only want to load the modules once each time the script is run. From ivanlan at pauahtun.org Wed Jun 1 17:00:39 2005 From: ivanlan at pauahtun.org (Ivan Van Laningham) Date: Wed, 01 Jun 2005 15:00:39 -0600 Subject: PySol not working on WinXP, SP2 References: <429DC8F7.38AFB2B5@pauahtun.org> <17054.5553.369830.823280@montanaro.dyndns.org> Message-ID: <429E21F7.18AE9ED0@pauahtun.org> Hi All-- Robert Kern wrote: > > Skip Montanaro wrote: > > Ivan> I can't find any later version on google... > > > > It may not help you much, but I was able to get it working on MacOSX by > > grabbing the latest available source and tracking down the contents of the > > data directory via the Wayback Machine. If you'd like to give it a try (I'm > > not sure how you'd get sound stuff working - I'm not a Windows guy), let me > > know. > > Source, data, and OS X binaries for 4.82 also available from here: > > http://homepage.mac.com/brian_l/FileSharing6.html > Very cool, but MacOSX doesn't help me much. I'm sure I could get it working on Linux, but I'd like to be able to run it on my main machine, instead of having to hop back over to the Win98 machine (an option my wife doesn't have). Sound server seems to be available as a .pyd file for the Win32 extensions, so I think that's not a problem. Metta, Ivan ---------------------------------------------- Ivan Van Laningham God N Locomotive Works http://www.andi-holmes.com/ http://www.foretec.com/python/workshops/1998-11/proceedings.html Army Signal Corps: Cu Chi, Class of '70 Author: Teach Yourself Python in 24 Hours From gregpinero at gmail.com Wed Jun 29 15:04:05 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 29 Jun 2005 15:04:05 -0400 Subject: Modules for inclusion in standard library? In-Reply-To: References: <3ian37Fkjle0U1@individual.net> <11c343ho6i6hv17@news.supernews.com> <1x6lpi6z.fsf@python.net> <7xwtodvzsv.fsf@ruckus.brouhaha.com> Message-ID: <312cfe2b05062912045ed99bf7@mail.gmail.com> While that policy does make sense, I think a database program falls somewhere in between an OS and an everyday third party program. For web developers, the database might as well be the OS. I use the database to store everything in my web app. That way I can just worry about 1 place to access information and not have to fool with files and other OS issues. So I humbly suggest the policy should be : Python will not include interface code for third party programs which are not part of an operating system or database system. .. But I have no experience in designing world class programming langauges so forgive me if I am too bold. -Greg On 6/29/05, Rocco Moretti wrote: > Paul Rubin wrote: > > Gregory Pi?ero writes: > > > >>I'd like to see some database API's to the most common databases > >>included. > > > > Yes, certainly, this is a serious deficiency with Python. > > Except that (please correct me if I'm wrong) there is somewhat of a > policy for not including interface code for third party programs which > are not part of the operating system. (I.e. the modules in the standard > libary should all be usable for anyone with a default OS + Python install.) > > A notable exception is the dbm modules, but I seem to recall hearing > that the official position is that it was a mistake. (Now only kept for > backward compatability.) > -- > http://mail.python.org/mailman/listinfo/python-list > From daniel at dittmar.net Tue Jun 14 18:18:19 2005 From: daniel at dittmar.net (Daniel Dittmar) Date: Wed, 15 Jun 2005 00:18:19 +0200 Subject: Which Python Wiki engine? In-Reply-To: References: Message-ID: <3h93dpFfvmjfU2@uni-berlin.de> Kenneth McDonald wrote: > I'm looking for a Wiki engine to set up for my company, so that we can > incrementally add user documentation for a fairly complex program, plus > allow users to add their own comments for the benefit of others. I'd > strongly prefer a Python-based Wiki, since that allows me the chance to > add plugins with minimal effort (being a python enthusiast and > programmer). ZWiki has support for showing an outline of the pages. But other than that, I found it less useful than MoinMoin. Also, ZWiki is a Zope product, and to me, Zope programming is not really Python programming. Daniel From peter at engcorp.com Thu Jun 2 09:36:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 02 Jun 2005 09:36:53 -0400 Subject: Beginner question: Logs? In-Reply-To: References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: Elliot Temple wrote: > from math import * > log10(15625) It's always a good idea, especially when answering a beginner's question, to add the caution that this form ("from xxx import *") has certain dangers** associated with it, and is widely considered poor style, and should really only rarely be used. (The math module is probably one of the few places where some people make an exception, however, but it's still not a good habit to get into.) -Peter From saint.infidel at gmail.com Wed Jun 1 14:08:55 2005 From: saint.infidel at gmail.com (infidel) Date: 1 Jun 2005 11:08:55 -0700 Subject: metaclass that inherits a class of that metaclass? In-Reply-To: References: <1117643765.063096.161160@g14g2000cwa.googlegroups.com> <1117644113.523658.173830@g43g2000cwa.googlegroups.com> <1117644636.721724.41050@g14g2000cwa.googlegroups.com> <1117646486.821360.128400@g47g2000cwa.googlegroups.com> <1117647935.916469.164160@g47g2000cwa.googlegroups.com> <1117648438.079178.92490@z14g2000cwz.googlegroups.com> Message-ID: <1117649335.285175.95350@g49g2000cwa.googlegroups.com> Oh great, just when I thought I was starting to grok this mess. From spam.csubich+block at block.subich.spam.com Thu Jun 30 21:55:37 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 30 Jun 2005 21:55:37 -0400 Subject: Scket connection to server In-Reply-To: References: Message-ID: Steve Horsley wrote: > There is a higher level socket framework called twisted that everyone > seems to like. It may be worth looking at that too - haven't got round > to it myself yet. I wouldn't say 'like,' exactly. I've cursed it an awful lot (mostly for being nonobvious), but it does a damn fine job at networking, especially if you're comfortable building your own protocols. From rbt at athop1.ath.vt.edu Thu Jun 2 10:33:39 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 02 Jun 2005 10:33:39 -0400 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: > Philosophy not entirely aside, you should note that object code in any > language can "easily" be reverse-engineered in the same way, with the > only difference being the degree of ease involved. If the code is worth > enough to someone that they are willing to risk violating your license > terms, they *will* be able to recover enough source code (whether it was > Python, C, or assembly) to do what they need. Don't intend to hijack this thread, but this bit interests me. I know several accomplished C/assembly programmers who have told me that reverse engineering object code from either of these two languages is anything but trivial. Yet, I *hear* and *read* the opposite all of the time. Can anyone actually demonstrate a decompile that mirrors the original source? Also, I'd venture to say that the number of people in the world who can consistently reverse engineer object code is almost statistically insignificant... sure, they are out there, but you'll win the lottery before you meet one of them and most of them work for big, bad government agencies ;) From david.baelde at ens-lyon.fr Wed Jun 8 21:32:12 2005 From: david.baelde at ens-lyon.fr (David Baelde) Date: Thu, 09 Jun 2005 03:32:12 +0200 Subject: Abstract and concrete syntax Message-ID: Hi, I tried python, and do like it. Easy to learn and read (at least for the commonly used part), has a very large community so great doc and contributions, and... the design is clean. I come from functional programming languages, and I do like the proper static binding, the first class functions. That's what interests me in Python. It's the most modern of those addictive scripting languages. But, there is something I can't believe. Statements are not expressions. I tried to find some doc about that on the web. I'm not satisfied, and I'd like to learn more and discuss here. First, there are some trolls about Python Zen forbidding statements to be expressions. But I think the Zen is often contradictory. I don't like trolls, want something serious. Basically, I found one good point against statements-as-expressions: it cannot fit the indentation sensitive syntax. --- http://mail.python.org/pipermail/python-list/2005-January/260566.html Python allows statements inside suites and suites inside compound statements. It also allows expressions inside statements and expressions inside expressions. The one thing it never ever does is allow a suite or a statement inside an expression, because doing so would utterly destroy the handling of significant white space. --- I feel there are some real problems here. But I can't find anything absolutely unsolvable. I played a few examples, can't get anything ambiguous. Maybe the nesting analyzer (http://python.org/doc/2.4.1/ref/indentation.html) needs to take into account parenthesis-like delimiters together with indentation, but that doesn't look impossible (although I suspect it's harder than I can imagine). The parenthesis trick could avoid over-deep indentation. set_callback(obj, lambda x: (if a: 2 else: 3) Well, I suspect there are some moral issues, and maybe pythonists don't want statements in expressions. PEP #308 was about having a ternary (?:) operator for expression level conditional, pythonists rejected it. I'd like to read more about the motivations of the vote. Many people will tell me that my tiny example can be written with the if-else outside the assignation. I claim it's better to be able to express it the way you mean it. That's why lambda is here for, too. More generally, I think there is no abstract distinction between statements and expressions. Everything is an expression, can be evaluated to a value. Making function first class objects was the same kind of good and beautiful idea. So if there is no abstract distinction, why should there be a concrete one? If it's just a technical issue, let's work on it. But I guess you'll have more to say on that subject... __ David From kent37 at tds.net Fri Jun 17 14:47:01 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Jun 2005 14:47:01 -0400 Subject: add new modules? In-Reply-To: <11b65f7bjjt7a51@corp.supernews.com> References: <11b65f7bjjt7a51@corp.supernews.com> Message-ID: <42b31a24_3@newspeer2.tds.net> Dennis Clark wrote: > This is a total newb question, you have been warned... > > I've been all over the www.python.org site and googled, but I've not > found just how to add new modules. I've tried setting PYTHONPATH, > I've tried putting the new module directories into the site-packages > directory, I've tried creating the .pth files, I've even done all > three of these things at the same time and still my python script > refuses to import. What is the cannonical way to add new modules > to python? I am running on OS X 10.4 (Macintosh obviously) on basically > freeBSD, os I'm doing UNIX type stuff at the console. If you have a single file that you want to make available, put it directly in site-packages. For example put mymodule.py in site-packages, then in code you can say from mymodule import MyClass If you have a directory of files that you consider related, that is a package. Put the directory in site-packages, add a file named __init__.py to the directory, and import qualified with the directory name. For example if you have site-packages/ mystuff/ __init__.py mymodule.py then in code you say from mystuff.mymodule import MyClass where in both cases MyClass is defined in mymodule.py. Kent From newsgroups at jhrothjr.com Mon Jun 13 18:48:37 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 13 Jun 2005 16:48:37 -0600 Subject: How to use 8bit character sets? References: <42ad11a7$0$24953$9b622d9e@news.freenet.de> <11aqrivp3834200@news.supernews.com> <42ADEFEA.80007@v.loewis.de> Message-ID: <11as3aaarmg836b@news.supernews.com> ""Martin v. L?wis"" wrote in message news:42ADEFEA.80007 at v.loewis.de... > John Roth wrote: >>> That is the default. >> >> >> As far as I can tell, there are actually two defaults, which tends >> to confuse things. > > Notice that there are two defaults already in the operating system: > Windows has the notion of the "ANSI code page" and the "OEM code > page", which are used in different contexts. > >> One is used whenever a unicode to 8-bit >> conversion is needed on output to stdout, stderr or similar; >> that's usually Latin-1 (or whatever the installation has set up.) > > You mean, in Python? No, this is not how it works. On output > of 8-bit strings to stdout, no conversion is ever performed: > the byte strings are written to stdout as-is. That's true, but I was talking about outputing unicode strings, not 8-bit strings. As you say below, the OP may not have been talking about that. >> The other is used whenever the unicode to 8-bit conversion >> doesn't have a context - that's usually Ascii-7. > > Again, you seem to be talking about Unicode conversions - > it's not clear that the OP is actually interested in > Unicode conversion in the first place. > > Regards, > Martin John Roth From onurb at xiludom.gro Tue Jun 7 04:31:07 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 07 Jun 2005 10:31:07 +0200 Subject: Question about Object Oriented + functions/global vars? In-Reply-To: References: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> Message-ID: <42a55b4c$0$24423$636a15ce@news.free.fr> Christopher J. Bottaro wrote: (snip) > 1. The upload function is not an object. Yes it is. In Python, everything's an object. >>> ftp.storbinary.__class__.__name__ 'instancemethod' >>> ftp.storbinary.foobar = 42 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'instancemethod' object has no attribute 'foobar' -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sjmachin at lexicon.net Sat Jun 18 03:42:47 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Jun 2005 17:42:47 +1000 Subject: functions with unlimeted variable arguments... In-Reply-To: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> References: <1119079151.053130.175440@g14g2000cwa.googlegroups.com> Message-ID: <42B3D077.4030606@lexicon.net> Xah Lee wrote: > how can i define a function with variable parameters? For example, > > f(a) would return [a] > f(a,b) would return [a,b] > f(a,b,...) would return [a,b,...] > > One solution is of course to make the argument as a list. i.e. > f([a,b,...]) > but are there other solutions? > >>> def foo(*args): ... print repr(args) ... return list(args) ... >>> foo() () [] >>> foo(42) (42,) [42] >>> foo(666, 'hello', 1.234) (666, 'hello', 1.234) [666, 'hello', 1.234] >>> From twic at urchin.earth.li Mon Jun 13 07:45:08 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Mon, 13 Jun 2005 12:45:08 +0100 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: On Sun, 12 Jun 2005, Peter Hansen wrote: > Andrea Griffini wrote: >> On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen >> wrote: >> >>> I think new CS students have more than enough to learn with their >>> *first* language without having to discover the trials and >>> tribulations of memory management (or those other things that Python >>> hides so well). >> >> I'm not sure that postponing learning what memory is, what a pointer is >> and others "bare metal" problems is a good idea. ... I think that for a >> programmer skipping the understanding of the implementation is just >> impossible: if you don't understand how a computer works you're going >> to write pretty silly programs. > > I won't say that I'm certain about any of this, but I have a very strong > suspicion that the *best* first step in learning programming is a program > very much like the following, which I'm pretty sure was mine: > > 10 FOR A=1 TO 10: PRINT"Peter is great!": END 10 PRINT "TOM IS ACE" 20 GOTO 10 The first line varies, but i suspect the line "20 GOTO 10" figures prominently in the early history of a great many programmers. > More importantly by far, *I made the computer do something*. Bingo. When you realise you can make the computer do things, it fundamentally changes your relationship with it, and that's the beginning of thinking like a programmer. tom -- Think logical, act incremental From gene.tani at gmail.com Sun Jun 19 09:48:15 2005 From: gene.tani at gmail.com (gene tani) Date: 19 Jun 2005 06:48:15 -0700 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: Message-ID: <1119188895.961693.129380@o13g2000cwo.googlegroups.com> If your test variable has specific values to branch on, the standard way is to have those values be keys in a dictionary, and do: branched_func_obj = dict_of_values.get(testvar) And the lambda hack is here, courtesy of Peter Norvig http://www.norvig.com/python-iaq.html From steven.bethard at gmail.com Mon Jun 20 16:44:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Jun 2005 14:44:22 -0600 Subject: Python and encodings drives me crazy In-Reply-To: References: Message-ID: Oliver Andrich wrote: > def remove_html_entities(data): > for html, char in html2text: > data = apply(string.replace, [data, html, char]) > return data I know this isn't your question, but why write: > data = apply(string.replace, [data, html, char]) when you could write data = data.replace(html, char) ?? STeVe From bvande at po-box.mcgill.ca Tue Jun 28 03:44:12 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 28 Jun 2005 03:44:12 -0400 Subject: How to compress a folder and all of its sub directories and files into a zip file? In-Reply-To: <311b5ce10506280029682b9366@mail.gmail.com> References: <311b5ce105062723167e892833@mail.gmail.com> <42C188F3.7010704@rt.sk> <311b5ce1050628002075da2e3@mail.gmail.com> <311b5ce10506280029682b9366@mail.gmail.com> Message-ID: <42C0FFCC.8030708@po-box.mcgill.ca> could ildg said unto the world upon 28/06/2005 03:29: > but the file is just stored, > and not compressed. > > On 6/28/05, could ildg wrote: > >>Thank you, >>it works~~ >> >>On 6/29/05, Peter Szinek wrote: >> >>>Hi, >>> >>>What about this: >>> >>>import os,zipfile >>>from os.path import join >>> >>> >>>zip = zipfile.ZipFile("myzipfile.zip", 'w') >>>for root, dirs, files in os.walk('.'): >>> for fileName in files: >>> zip.write(join(root,fileName)) >>>zip.close() >>> >>>Maybe it zips also the myzipfile.zip ;-) >>>Probably this is not needed, so an additional test (something like >>>fileName != 'myfile.zip' would be needed. >>> >>>HTH, >>>Peter >>> >>>could ildg wrote: >>> >>>>I want to compress a folder and all of its sub files including empty folders >>>>into a zip file. what's the pythonic way to do this? >>>> >>>>Thanks in advance. >>> >>> This thread got me to read the relevant docs: 7.18.1 ZipFile Objects "class ZipFile( file[, mode[, compression]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, or 'a' to append to an existing file. For mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file, such as python.exe. Using cat myzip.zip >> python.exe also works, and at least WinZip can read such files. compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED or ZIP_DEFLATED; unrecognized values will cause RuntimeError to be raised. If ZIP_DEFLATED is specified but the zlib module is not available, RuntimeError is also raised. The default is ZIP_STORED." http://docs.python.org/lib/zipfile-objects.html So, it would appear that compression requires a 3rd party module, not included in Python (and not present on my Windows box). I'm presently filing a bug suggesting this be made a touch more explicit in the zlib docs. Best to all, Brian vdB From kent37 at tds.net Thu Jun 9 08:33:20 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Jun 2005 08:33:20 -0400 Subject: help with sending mail in Program In-Reply-To: <42a814a4_1@newspeer2.tds.net> References: <42a56e49_3@newspeer2.tds.net> <42a814a4_1@newspeer2.tds.net> Message-ID: <42a836bc$1_2@newspeer2.tds.net> Kent Johnson wrote: > Tim Roberts wrote: >> Not exactly like this, you didn't. The list of destination addresses in >> SMTP.sendmail must be a sequence, not a string: > > Yes, exactly like that. This is a working module, the only thing I > changed to post it was the email address and the name of the SMTP > server. SMTP.sendmail() allows a single string as a to address. > > From the comment in smtplib.py: > - to_addrs : A list of addresses to send this mail to. A > bare > string will be treated as a list with 1 > address. I submitted this as a doc bug. Kent From der.rudi at planet-dot-nl.no-spam.invalid Tue Jun 28 08:59:56 2005 From: der.rudi at planet-dot-nl.no-spam.invalid (DeRRudi) Date: Tue, 28 Jun 2005 12:59:56 +0000 (UTC) Subject: Open running processes Message-ID: Hi all, I have a programm. In this program i've made the restriction that only one instance can run at the time. (done with mutex). Now i'd like it to open the running (make visible) instance when someone want's to open it a second time. Does anybody know how to do this? I hope you all understand what i mean. My English isn't to good... Greetz Rudi From msoulier at digitaltorque.ca Sat Jun 18 22:35:13 2005 From: msoulier at digitaltorque.ca (Michael P. Soulier) Date: Sat, 18 Jun 2005 22:35:13 -0400 Subject: oddness in super() In-Reply-To: <3hjf0nFhc1t9U1@uni-berlin.de> References: <3hjf0nFhc1t9U1@uni-berlin.de> Message-ID: <20050619023512.GQ18460@rabbit.digitaltorque.ca> On 18/06/05 Diez B. Roggisch said: > Certainly a bug - but not in python. The super-method works for > new-style classes only. > > The attached script reproduces your observed behaviour. So kit seems > that whatever toolkit you use, it uses new-style classes on windows, and > old-style ones on linux. The code is identical on both. I sort-of found the problem. I'm using Ubuntu Linux, and I found both Python 2.3 and 2.4 installed. /usr/bin/python was 2.4, but things still weren't working quite right, so I uninstalled all of the 2.3 packages. Suddenly everything works. Not entirely sure why, but I guess the 2.4 interpreter was picking up libraries it shouldn't, or something. Whether a new or old style class depends on wxPython, since my code is subclassing from wx.Frame. I was concerned since the code is identical on both platforms, but losing the 2.3 cruft seems to have fixed something. Thanks, Mike -- Michael P. Soulier http://www.digitaltorque.ca http://opag.ca python -c 'import this' Jabber: msoulier at digitaltorque.ca -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From peter at engcorp.com Fri Jun 24 09:05:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 09:05:53 -0400 Subject: webserver application (via Twisted?) In-Reply-To: References: Message-ID: flupke wrote: > I need to program and setup serveral webservices. > If i were still using jsp, i would use Tomcat to make the several > applications available on a given port. > How can i accomplish this in Python? > I was thinking about Twisted but it's not clear to me what parts i need > to make a webserver listen on a certain port and having it serve > different application based on the url that i received. > > Any advice on this? Yes, check the archives for the frequent past nearly identical questions and the detailed responses, or do a quick Google search for Python web frameworks. There are perhaps dozens -- though less than a dozen really popular ones -- and most will do what you want, going by the most general interpretation of your question. (If you're talking about duplicating whatever specific architecture appeals to you in Tomcat, I can't help you...) -Peter From roy at panix.com Mon Jun 27 23:41:55 2005 From: roy at panix.com (Roy Smith) Date: Mon, 27 Jun 2005 23:41:55 -0400 Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: "BORT" wrote: > So, that said... In ~simplest~ terms for the stated goal -- Forth or > Python? > ...the goal is NOT the spelling tutor... it is learning how to use a > tool to solve a problem. I am asking which tool is more suited to an > otherwise arbitrary direction of "spelling tutor program." Forth is an interesting language. But, as a practical tool, Forth is somewhat of an orphan. You're going to find a lot more in the way of Python resources than you're going to find Forth resources (for example, 1945 posts to comp.lang.python vs 236 to comp.lang.forth in the past 2 weeks). I know "most popular" doesn't always mean "best", but in this case, I think it's an important factor. The more you can find in the way of tutorials, libraries, and on-line help, the easier it will be to master. Not to mention, that when you're done learning Python, you will have learned a modern language which includes concepts common to many languages in common use today. When you learn Forth, you will have learned Forth. About the best that can be said about that is that It'll give you a head-start if your next goal is to learn PostScript :-) From ischenko at gmail.com Thu Jun 9 06:28:44 2005 From: ischenko at gmail.com (ischenko at gmail.com) Date: 9 Jun 2005 03:28:44 -0700 Subject: a library of stock mock objects? Message-ID: <1118312924.538527.117150@g14g2000cwa.googlegroups.com> There is a (relatively) widely used technique in unit testing, called mock objects. There is even a pMock library which provides a Mock class for a Python environment. Given the "duck typing" nature of the Python itself, it's pretty trivial to build mocks without using any pre-built libraries. What is less trivial and potentially more worthwhile is to have a library of "stock" mock objects. For instance, I found myself re-implementing ConnectionStub class again and again for different projects. And there is no shortage of other good candidates as well: socket, web request/response, thread objects, etc. Someone on a Python mailing list asks whether anyone implemented a mock filesystem interface, for example. Having a library of such mock classes, realizing widely-used and "heavy" interfaces may be a good idea. The only real problem I can think of is whether it's possible to make these mocks generic enough. Mocks often contain some (application-specific) hard-coded rules and data to realize desired behavior. For instance, socket mock may fail when user attempts to write a "foobar" string - and unit test will use this to check how code handle these kind of errors. These rules may be generalized but it may lead to mock classes becoming unwieldy. Even keeping this problem in mind, it's still a reasonable idea for a library, but obviously I'm biased. What do you think? From invalidemail at aerojockey.com Wed Jun 29 08:24:07 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 29 Jun 2005 05:24:07 -0700 Subject: map vs. list-comprehension In-Reply-To: <42c27238$0$26269$626a14ce@news.free.fr> References: <42c27238$0$26269$626a14ce@news.free.fr> Message-ID: <1120047847.948179.105550@o13g2000cwo.googlegroups.com> F. Petitjean wrote: > Le Wed, 29 Jun 2005 09:46:15 +0000 (UTC), Mandus a ?crit : > > Hi there, > > > > inspired by a recent thread where the end of reduce/map/lambda in Python was > > discussed, I looked over some of my maps, and tried to convert them to > > list-comprehensions. > > > > This one I am not sure how to conver: > > > > Given three tuples of length n, b,i and d, I now do: > > > > map(lambda bb,ii,dd: bb+ii*dd,b,i,d) > > > > which gives a list of length n. > > res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] > > Hoping that zip will not be deprecated. Notice that zip doesn't do any functional stuff--it merely manipulates data structures--so it ought not to be lumped in with map, filter, and reduce. Fear not, people: just as the BDFL does not indiscriminately add features, also he does not indiscriminately remove them. zip, though it feels a little exotic, is very useful and serves a purpose that no language feature serves(*), so rest assured it's not going to disappear. (*) Excepting izip, of course, which is more useful than zip and probably should also be a builtin. -- Carl Banks From greg at cosc.canterbury.ac.nz Thu Jun 9 00:31:12 2005 From: greg at cosc.canterbury.ac.nz (Greg Ewing) Date: Thu, 09 Jun 2005 16:31:12 +1200 Subject: Abstract and concrete syntax In-Reply-To: References: Message-ID: <3gpv0uFdqbi5U1@individual.net> David Baelde wrote: > Statements are not expressions. > > I feel there are some real problems here. But I can't find anything > absolutely unsolvable. There's no doubt that these problems could be solved in a technical sense, but the real issue is whether the resulting code would be *readable*. One of Python's major strengths is that its code is usually very easy to read, even if it means being a bit more verbose at times than strictly necessary. All the proposals I've seen for statements-in-expressions in Python (and there have been quite a few) have been a disaster in the readability department > PEP #308 was about having a ternary (?:) > operator for expression level conditional, pythonists rejected it. Actually, it was really Guido who rejected it, because Pythonistas failed to reach a consensus on syntax, and he wasn't really hot on the idea in the first place. If he had really wanted it, he would have just picked a syntax himself. > More generally, I think there is no abstract distinction between > statements and expressions. Everything is an expression, can be evaluated > to a value. That's true in a functional language, but Python is not a functional language. In imperative programming, often you just do something for its side effect, and there's no obvious value to return. Forcing everything to return a value just for the sake of conceptual purity is an artificiality, in my view. -- Greg Ewing, Computer Science Dept, University of Canterbury, Christchurch, New Zealand http://www.cosc.canterbury.ac.nz/~greg From exarkun at divmod.com Wed Jun 8 17:43:03 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 8 Jun 2005 17:43:03 -0400 Subject: Fast text display? In-Reply-To: Message-ID: <20050608214303.15830.214761019.divmod.quotient.3087@ohm> On Wed, 08 Jun 2005 14:15:35 -0400, Christopher Subich wrote: >As a hobby project, I'm writing a MUD client -- this scratches an itch, >and is also a good excuse to become familiar with the Python language. >I have a conceptual handle on most of the implementation, but the >biggest unknown for me is the seemingly trivial matter of text display. > >My first requirement is raw speed; none of what I'm doing is >processing-intensive, so Python itself shouldn't be a problem here. But >still, it's highly desirable to have very fast text updates (text >inserted only at the end)-- any slower than 20ms/line stretches >usability for fast-scrolling. EVERY other action on the text display, >though, like scrolling backwards or text selection, can be orders of >magnitude slower. > >The second requirement is that it support text coloration. The exact >markup method isn't important, just so long as individual characters can >be independently colored. > >The third requirement is cross-platform-osity; if you won't hold it >against me I'll tell you that I'm developing under Cygwin in Win2k, but >I'd really like it if the app could run under 'nix and mac-osx also. I've done this with Tkinter before. At the time, I surveyed the various toolkits for the quality of their text widgets, and of Tkinter, PyGTK, PyQT, and wxPython, only Tkinter could satisfy the performance requirements. This was about three years ago, so the field may have changed. If you like, you can check out the code: http://sourceforge.net/projects/originalgamer As MUD clients go, it's pretty weak, but it solves the text display problem pretty decently. Hope this helps, Jp From ognjen at mailshack.com Fri Jun 3 15:11:15 2005 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Fri, 03 Jun 2005 20:11:15 +0100 Subject: Formatting Time Message-ID: <42A0AB53.9000600@mailshack.com> I never thought id need help with such a thing as time formatting (admittadly i never did it before) but ok, i guess there is a first for everything. I have a float variable representing seconds, and i want to format it like this: 0:00:00 (h:mm:ss) Now search as I might i am finding this quite elusive, i had a look at the time module but that seems overly complicated for this. Anyone got any simple solutions to doing this? cheers! ============= Amazing, two days and no replies, cant be that i have stumped the python community with this... I have ( a rather bad feeling) that I am having trouble with my email again. I can recieve mail, but on some mailinglists (hear this one and the gentoo list) I can get other peoples topics in the list, but never get mails re. topics I posted (including the original post and any subsequent replies). All in all rather strange. Therefore if anyone has responded to my question, please CC me so that I can receive the info. thx. From jhefferon at smcvt.edu Fri Jun 24 08:21:54 2005 From: jhefferon at smcvt.edu (Jim) Date: 24 Jun 2005 05:21:54 -0700 Subject: create a pdf file In-Reply-To: References: <42C7E766869C42408F0360B7BF0CBD9B014B61B4@pnlmse27.pnl.gov> Message-ID: <1119615714.261010.84060@g44g2000cwa.googlegroups.com> If it is a plain text file (or close to it, like the Gutenburg Project files), think about using pdfLaTeX. Jim From python-url at phaseit.net Wed Jun 22 12:08:03 2005 From: python-url at phaseit.net (Simon Brunning) Date: Wed, 22 Jun 2005 16:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jun 22) Message-ID: QOTW: "Python is more concerned with making it easy to write good programs than difficult to write bad ones." - Steve Holden "Scientists build so that they can learn. Programmers and engineers learn so that they can build." - Magnus Lycka "It happens that old Java programmers make one module per class when they start using Python. That's more or less equivalent of never using more than 8.3 characters in filenames in modern operating systems, or to make a detour on your way to work because there used to be a fence blocking the shortest way a long time ago." - Magnus Lycka Python doesn't currently have a case or switch statement. Case blocks are easily simulated with if, elif, and else, but would Python's readability benefit from having it built in?: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/29e45afc78adcd15 A Podcast worth listening to at last. Guido speaks on Python's history and community: http://www.itconversations.com/shows/detail545.html http://www.itconversations.com/shows/detail559.html If your class implements __eq__ but not __ne__, (a = b) does not imply !(a != b). If this something that should be fixed, or just a "gotcha"? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f6e0986b2c0f01c0 John Machin instructively analyzes several of Excel's defects as a data-management vehicle, obliquely highlighting Python's Zen. Tim Roberts follows up with a small but potentially crucial addendum pertinent, among others, to those who deal with USA "zip codes": http://groups-beta.google.com/group/comp.lang.python/index/browse_frm/thread/d14b13c8bc6e8515/ Recent (unreleased) work on distutils allows you to automatically upload packages to PyPI: http://www.amk.ca/diary/archives/003937.html Text files and line endings; Python helps you out on Windows, which can be a little confusing: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2d3f61b949bca0e9 Kalle wants to protect his instance attributes. He's warned off the idea, but at the same time, alex23 demonstrates an interesting way of doing it using properties(): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9f7c29fed95d7586 Creating a Python iterator by wrapping any callable: http://bob.pythonmac.org/archives/2005/06/14/python-iterators-and-sentinel-values/ Richard Lewis wants resumable exceptions. Python doesn't have them, but Peter Hansen shows him how to achieve what he wants, and Willem shows us how resumable exceptions work in Lisp: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e3dafce228dd4258 Jan Danielsson is confused about the difference between __str__ and __repr__, and what they are both for: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b37f1e3fae1154d6 The Kamaelia Framework; communicating with and linking Python generators: http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml Ron Adams proposes an "also" block to be executed if a "for" loop's "else" block isn't, and more controversially, that the "else" block's meaning be switched: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b15de260c5ca02e0 How you convince your marketing drones that switching from Python to Java would be A Bad Thing? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5b6d1ff54640e9b1 Why should an ambitious 14-year-old look at Python? (And why source-code hiding is a waste of time.) http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/107a4da1dd45b915 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From ggg at zzz.it Tue Jun 7 06:22:54 2005 From: ggg at zzz.it (deelan) Date: Tue, 07 Jun 2005 12:22:54 +0200 Subject: Trouble Encoding In-Reply-To: <1118135690.961381.207490@o13g2000cwo.googlegroups.com> References: <1118135690.961381.207490@o13g2000cwo.googlegroups.com> Message-ID: fingermark at gmail.com wrote: > I'm using feedparser to parse the following: > >
Adv: Termite Inspections! Jenny Moyer welcomes > you to her HomeFinderResource.com TM A "MUST See &hellip;
> > I'm receiveing the following error when i try to print the feedparser > parsing of the above text: > > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u201c' in > position 86: ordinal not in range(256) > > Why is this happening and where does the problem lie? it seems that the unicode character 0x201c isn't part of the latin-1 charset, see: "LEFT DOUBLE QUOTATION MARK" try to encode the feedparser output to UTF-8 instead, or use the "replace" option for the encode() method. >>> c = u'\u201c' >>> c u'\u201c' >>> c.encode('utf-8') '\xe2\x80\x9c' >>> print c.encode('utf-8') ok, let's try replace >>> c.encode('latin-1', 'replace') '?' using "replace" will not throw an error, but it will replace the offending characther with a question mark. HTH. -- deelan From darkpaladin79 at hotmail.com Thu Jun 9 11:28:49 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Thu, 09 Jun 2005 11:28:49 -0400 Subject: help with sending mail in Program In-Reply-To: <42a814a4_1@newspeer2.tds.net> Message-ID: > >>#!/usr/local/bin/python > >> > >>''' Send mail to me ''' > >> > > > >>from smtplib import SMTP > > > >>def sendToMe(subject, body): > >> me = '"Kent Johnson" ' > >> send(me, me, subject, body) > >> > >> > >>def send(frm, to, subject, body): > >> s = SMTP() > >># s.set_debuglevel(1) > >> s.connect('mail.mycompany.com') > >> s.ehlo('10.0.3.160') # IP address of my computer, I don't remember >why I needed this > >> > >> msg = '''From: %s > >>Subject: %s > >>To: %s > >> > >>%s > >>''' % (frm, subject, to, body) > >> > >> s.sendmail(frm, to, msg) > > > > > > s.sendmail(frm, [to], msg) > > > > > >> s.quit() > >> > >> > >>if __name__ == '__main__': > >> sendToMe('Testing', 'This is a test') --- I think this seems like it would work, but I still can't seem to get it to work. I turned on the debugging and everything seemed alright. I'll post how I modified it (I probally made a simple mistake). Can someone help here? #!/usr/local/bin/python ''' Send mail to me ''' from smtplib import SMTP def sendToMe(subject, body): me = '"Ivan Shevanski" ' send(me, me, subject, body) def send(frm, to, subject, body): s = SMTP() #///On or off for test\\\ #s.set_debuglevel(1) s.connect('mail.hotmail.com',) s.ehlo('69.137.27.32') # IP address of my computer, I don't remember why I needed this msg = '''From: %s Subject: %s To: %s %s ''' % (frm, subject, to, body) s.sendmail(frm, to, msg) s.sendmail(frm, [to], msg) s.quit() if __name__ == '__main__': sendToMe('test', 'test') It says it sends it but I get nothing in my inbox or anywhere! This is really frustrating me. _________________________________________________________________ Don?t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From dalke at dalkescientific.com Fri Jun 10 14:54:32 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 10 Jun 2005 18:54:32 GMT Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <42A9DAC3.2010306@anvilcom.com> Message-ID: Robert Kern wrote: > There is no moderator. We are all moderators. I am Spartacus! We are all Kosh. - Nicolas Bourbaki From agriff at tin.it Sat Jun 18 02:51:05 2005 From: agriff at tin.it (Andrea Griffini) Date: Sat, 18 Jun 2005 06:51:05 GMT Subject: What is different with Python ? References: <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> <3hg08rFh2tr3U1@individual.net> <1119015358.155954.92430@g47g2000cwa.googlegroups.com> <1119067837.776544.198870@g49g2000cwa.googlegroups.com> Message-ID: On 17 Jun 2005 21:10:37 -0700, "Michele Simionato" wrote: >Andrea Griffini wrote: >> Why hinder ? > ... >To be able to content himself with a shallow knowledge >is a useful skill ;) Ah! ... I agree. Currently for example my knowledge of Zope is pretty close to 0.00%, but I'm using it and I'm happy with it. I did what I was asked to do and took way less time than hand-writing the cgi stuff required. Every single time I've to touch those scripts I've to open the Zope book to get the correct method names. But I'd never dare to call myself a zope developer... with it I'm just at the "hello world" stage even if I accomplished what would require a lot of CGI expertise. But once I remember running in a problem; there was a file of about 80Mb uploaded in the Zope database that I wasn't able to extract. I was simply helpless: download always stopped arount 40Mb without any error message. I wandered on IRC for a day finding only other people that were better than me (that's easy) but not good enough to help me. In the end someone gave me the right suggestion, I just installed a local zope on my pc, copied the database file, extracted the file from the local instance and, don't ask me why, it worked. This very kind of problem solution (just try doing stupid things without understanding until you get something that looks like working) is what I hate *MOST*. That's one reason for which I hate windows installation/maintenance; it's not an exact science, it's more like try and see what happens. With programming that is something that IMO doesn't pay in the long run. I'm sure that someone that really knows Zope would have been able to get that file out in a minute, and may be doing exactly what I did. But knowing why! And this is a big difference. Indeed when talking about if learning "C" can hinder or help learning "C++" I remember thinking that to learn "C++" *superficially* learning "C" first is surely pointless or can even hinder. But to learn "C++" deeply (with all its quirks) I think that learning "C" first helps. So may be this better explain my position; if you wanna become a "real" programmer, one that really has things under control, then learning a simple assembler first is the main path (ok, may be even a language like C can be a reasonable start, but even in such a low-level language there are already so many things that are easier to understand if you really started from bytes). However, to be able to do just useful stuff with a computer you don't need to start that low; you can start from python (or, why not, even dreamweaver). Andrea From greg_miller at nexpress.com Mon Jun 27 08:08:12 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 27 Jun 2005 05:08:12 -0700 Subject: COM problem .py versus .exe Message-ID: <1119874092.625716.179620@o13g2000cwo.googlegroups.com> I have a .DLL that I am extracting the file version from using wmi.py. The specific code is: c = wmi.WMI() for f in c.CIM_DataFile(Name="c:\\glossersdmsservices\\bin\\glosscmanager.dll"): sdmsver = f.Version this works fine when running the application as a python file, when I build the application into an executable, using py2exe, I get the following error: Traceback (most recent call last): File "autoStart.pyc", line 241, in test File "wmi.pyc", line 138, in ? File "win32com\client\gencache.pyc", line 540, in EnsureDispatch File "win32com\client\CLSIDToClass.pyc", line 50, in GetClass KeyError: '{D2F68443-85DC-427E-91D8-366554CC754C}' the .dll resides outside the directory of the executable. The one thing I notice is that the KeyError value is a different id than the COM object I am accessing. I'm not sure where the value in the KeyError listed is coming from. Do I have to do some preprocessing in the build script? I am at a bit of a loss here, so any input would be appreciated. Thanks in advance. From tim.golden at viacom-outdoor.co.uk Wed Jun 29 11:16:15 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 16:16:15 +0100 Subject: Open running processes Message-ID: <9A28C052FF32734DACB0A288A3533991EBB954@vogbs009.gb.vo.local> [DeRRudi] | Well it doesnt work yet, but its gonna! ;) | i've tested it with a little app. There is my main app (called it | server) wich contains a thread. This thread listens to a mm (memory | mapping) when an other program sets a flag | (finished_producing_event.set() ) it just calls self.iconize(false) | | I'm not sure what pieces of code i have to post here.. posting all of | it makes it too large i believe :) | | >From server: [.. snip ..] | def OnChange(self, event): | shared_memory.seek(0) | tekstding = shared_memory.readline() | if(tekstding.strip() == | "maximize"): | self.Iconize(False) | self.Show(False) | elif(tekstding.strip() == | "minimize"): | self.Iconize(True) | self.Show(True) | self.panel.tekst.SetValue(tekstding) | [/code:1:080343f1b1] | | Hope you can see now how it works! Greetz Interesting; but do you need to use shared memory at all? Why not simply have two events; one for maximise, the other for minimising? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From lbates at syscononline.com Wed Jun 1 18:18:42 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 01 Jun 2005 17:18:42 -0500 Subject: ConfigParser, mapping one key to multiple values In-Reply-To: References: Message-ID: I accomplish this by using the following construct with ConfigParser: [sync files] ignore_001=.*/foodir/.*\.pyc ignore_002=.*/foodir/.*~ . . . It may be a workaround, but it works just fine. It is easy to write code to handle this (not tested): section='sync files' ignore_options=[x for x in ini.options(section) if x.lower().startswith('ignore_')] ignores_list=[] for option in ignore_options: ignores_list.append(ini.get(section, option)) Larry Bates Thomas Guettler wrote: > Hi, > > I need a config like this: > > [sync files] > ignore=".*/foodir/.*\.pyc" > ignore=".*/foodir/.*~" > ... > > The ConfigParser of the standard library can't handle this, > because one key maps to multiple values. > Is there a simple and lightweight config parser which can > handle this? > > Thomas > > PS: Needs to be compatible with Python 2.3 > From roccomoretti at hotpop.com Fri Jun 10 13:23:54 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Fri, 10 Jun 2005 12:23:54 -0500 Subject: Annoying behaviour of the != operator In-Reply-To: <1118419010.114824.200580@g49g2000cwa.googlegroups.com> References: <3gpsl0Fdhq0mU1@individual.net> <1118419010.114824.200580@g49g2000cwa.googlegroups.com> Message-ID: George Sakkis wrote: > "Rocco Moretti" wrote: > > >>One way to handle that is to refuse to sort anything that doesn't have a >>"natural" order. But as I understand it, Guido decided that being able >>to sort arbitrary lists is a feature, not a bug. > > > He has changed his mind since then > (http://mail.python.org/pipermail/python-dev/2004-June/045111.html) but > it was already too late. The indicated message sidesteps the crux of the issue. It confirms that arbitrary *comparisons* between objects are considered a wart, but it says nothing about arbitrary *ordering* of objects. None > True --> Wart [None, True].sort() --> ???? The point that I've been trying to get across is that the two issues are conceptually separate. (That's not to say that Guido might now consider the latter a wart, too.) From dalke at dalkescientific.com Fri Jun 10 00:18:10 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 10 Jun 2005 04:18:10 GMT Subject: Is pyton for me? References: Message-ID: Mark de la Fuente wrote: > Here is an example of the type of thing I would like to be able to do. > Can I do this with python? How do I get python to execute command line > functions? ... > # simple script to create multiple sky files. > > foreach hour (10 12 14) > gensky 3 21 $hour > sky$hour.rad > end Dan Bishop gave one example using os.system. The important thing to know is that in the shell all programs can be used as commands while in Python there isn't a direct connection. Instead you need to call a function which translates a request into something which calls the command-line program. There are several ways to do that. In Python before 2.4 the easiest way is with os.system(), which takes the command-line text as a string. For example, import os os.system("gensky 3 21 10 > sky10.rad") You could turn this into a Python function rather easily import os def gensky(hour): os.system("gensky 3 21 %d > sky%d.rad" % (hour, hour)) for hour in (10, 12, 14): gensky(hour) Python 2.4 introduces the subprocess module which makes it so much easier to avoid nearly all the mistakes that can occur in using os.system(). You could replace the 'gensky' python function with import subprocess def gensky(hour): subprocess.check_call(["gensky", "3", "21", str(hour)], stdout = open("sky%d.rad" % (hour,), "w")) The main differences here are: - the original code didn't check the return value of os.system(). It should do this because, for example, the gensky program might not be on the path. The check_call does that test for me. - I needed to do the redirection myself. (I wonder if the subprocess module should allow if isinstance(stdout, basestring): stdout = open(stdout, "wb") Hmmm....) > If I try and do a gensky command from the python interpreter or within a > python.py file, I get an error message: > > NameError: name ?gensky? is not defined That's because Python isn't set up to search the command path for an executable. It only knows about variable names defined in the given Python module or imported from another Python module. > If anyone has any suggestions on how to get python scripts to execute > this sort of thing, what I should be looking at, or if there is > something else I might consider besides python, please let me know. You'll have to remember that Python is not a shell programming language. Though you might try IPython - it allows some of the things you're looking for, though not all. You should also read through the tutorial document on Python.org and look at some of the Python Cookbook.. Actually, start with http://wiki.python.org/moin/BeginnersGuide Andrew dalke at dalkescientific.com From Scott.Daniels at Acm.Org Wed Jun 22 18:06:03 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 22 Jun 2005 15:06:03 -0700 Subject: import search path In-Reply-To: <86acli13kh.fsf@guru.mired.org> References: <86acli13kh.fsf@guru.mired.org> Message-ID: <42b9d963$1@nntp0.pdx.net> Mike Meyer wrote: > "SHELTRAW, DANIEL" writes: >>If a Python program has an import statement like: >>import FFT >> >>how do I determine the path to the imported file? > > guru% python > Python 2.4.1 (#2, Apr 25 2005, 21:42:44) > [GCC 3.4.2 [FreeBSD] 20040728] on freebsd5 > Type "help", "copyright", "credits" or "license" for more information. > py> import FFT > py> import sys > py> sys.modules['FFT'].__file__ > '/usr/opt/lib/python2.4/site-packages/Numeric/FFT/__init__.pyc' > Much shorter is: > import FFT > FFT.__file__ <> Note that (after the above): > import sys > sys.modules['FFT'] is FFT True --Scott David Daniels Scott.Daniels at Acm.Org From passion_to_be_free at hotmail.com Mon Jun 20 11:30:57 2005 From: passion_to_be_free at hotmail.com (passion_to_be_free at hotmail.com) Date: 20 Jun 2005 08:30:57 -0700 Subject: import via pathname In-Reply-To: References: <1119274298.955687.151070@g49g2000cwa.googlegroups.com> Message-ID: <1119281457.058120.69070@g49g2000cwa.googlegroups.com> Ahh....I see. I played around with the sys.path function...and it looks like python automatically looks in the same directory as my script first. Then is searches to all the other pre-defined paths. So it works for me to just keep my main script in the same directory as the two modules I'm using. Thx! From mkent at webmd.net Tue Jun 14 09:24:25 2005 From: mkent at webmd.net (mkent at webmd.net) Date: 14 Jun 2005 06:24:25 -0700 Subject: AIX 4.3, Python 2.4.1 fails in test_exceptions with a core dump Message-ID: <1118755465.375363.178740@o13g2000cwo.googlegroups.com> I'm attempting to switch from 2.3.2 to 2.4.1 on our AIX 4.3 development system. I have no problems building Python 2.3.2. I build Python 2.4.1 using 'configure --without-threads; gmake; gmake test', and always get a coredump during the tests on 'test_exceptions'. I've searched for any reports of this problem on the Sourceforge bug list and here, with no success. Has anyone seen this problem? From mwm at mired.org Wed Jun 22 11:58:20 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 22 Jun 2005 11:58:20 -0400 Subject: Looking for a web-based messaging system Message-ID: <86k6km1izn.fsf@guru.mired.org> One of my clients has a need for a web-based messaging system. Something python-based is preferred, as that's where our expertise is, but web frameworks built in Python are perfectly acceptable. If you know of something really good that isn't in Python, I wouldn't mind hearing about it - but I do have a long list of non-python solutions. I've got a pretty full set of requirements. Basically, the user should log in to the web site and get a list of outstanding messages. It *has* to support multiple browser windows with different views of the list. Capabilities wanted include sorting in both directions and on multiple fields. Filtering based on arbitrary fields - including both ANDing and ORing together filtering criteria. It should be possible to group related messages together, with a single line display summarizing the group. Likewise, it should be possible to fold related messages into a single line, and unfold specific instances. We'd like the messages to be stored in an SQL database - we're using postgres - so we can use our existing report generation tools. The only licensing requirement is that we get source so we can tailor the product to our needs. Commercial is perfectly fine. GPL is acceptable, but not preferred. So far, the only thing I've found that comes remotely close to this is BoBoMail. Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From brent.heeringa at gmail.com Thu Jun 23 14:49:47 2005 From: brent.heeringa at gmail.com (Brent) Date: 23 Jun 2005 11:49:47 -0700 Subject: trouble subclassing str Message-ID: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> I'd like to subclass the built-in str type. For example: -- class MyString(str): def __init__(self, txt, data): super(MyString,self).__init__(txt) self.data = data if __name__ == '__main__': s1 = MyString("some text", 100) -- but I get the error: Traceback (most recent call last): File "MyString.py", line 27, in ? s1 = MyString("some text", 12) TypeError: str() takes at most 1 argument (2 given) I am using Python 2.3 on OS X. Ideas? From jepler at unpythonic.net Thu Jun 16 15:20:01 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 16 Jun 2005 14:20:01 -0500 Subject: log in to a website In-Reply-To: <1118942713.133261.258480@o13g2000cwo.googlegroups.com> References: <1118942713.133261.258480@o13g2000cwo.googlegroups.com> Message-ID: <20050616192000.GC1763@unpythonic.net> You may find the third-party modules "ClientForm" and "ClientCookie" to be useful. Using ClientForm, the following code uploads a file to a particular web form: forms = ClientForm.ParseResponse(urllib2.urlopen(url)) f = forms[0] f.add_file(open(local, "rb"), filename=remote, name="file") u = f.click("attach") urllib2.urlopen(u) A web search should turn up the homepage for these modules. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steven.bethard at gmail.com Sat Jun 4 21:35:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 19:35:11 -0600 Subject: method = Klass.othermethod considered PITA In-Reply-To: <6qmdnR7ry4wF0D_fRVn-hA@speakeasy.net> References: <87oeallp44.fsf@pobox.com> <6qmdnR7ry4wF0D_fRVn-hA@speakeasy.net> Message-ID: Erik Max Francis wrote: > For instance, for a chat network bot framework, a certain form of bot > will look for any attribute in its instance that starts with verb_ and a > command and execute it when it hears it spoken: > > def verb_hello(self, convo): > "Respond to a greeting." > convo.respond(random.choice(self.greetings)) > > If you'd like it to respond to more than one word like this, then you > only need to assign the additional verbs, rather than redefine them: > > verb_hi = verb_hello > verb_yo = verb_hello > verb_wazzup = verb_hello Well if you want these to work with subclasses that change verb_hello to do something else, one option is to write a simple decorator, and then your lines above become something like: verb_hi = caller(verb_hello) verb_yo = caller(verb_hello) verb_wazzup = caller(verb_hello) or if you prefer to only create one such function: _verb_hello_caller = caller(verb_hello) verb_hi = _verb_hello_caller verb_yo = _verb_hello_caller verb_wazzup = _verb_hello_caller Here's a simple example in action: py> def caller(func): ... def wrapper(self, *args, **kwargs): ... return getattr(self, func.__name__)(*args, **kwargs) ... return wrapper ... py> class C(object): ... def verb_hello(self): ... print "C: hello" ... verb_hi = caller(verb_hello) ... py> class D(C): ... def verb_hello(self): ... print "D: hello" ... py> D().verb_hi() D: hello Notice that verb_hi() still calls verb_hello() in the subclass. STeVe From correiajREMOVECAPS at hotmail.com Tue Jun 7 23:39:51 2005 From: correiajREMOVECAPS at hotmail.com (J Correia) Date: Wed, 08 Jun 2005 03:39:51 GMT Subject: separate IE instances? References: <1118102755.309346.169810@g14g2000cwa.googlegroups.com> <1118144873.935177.287190@g43g2000cwa.googlegroups.com> <1118165668.863841.291290@z14g2000cwz.googlegroups.com> <1118191737.550326.267750@g43g2000cwa.googlegroups.com> Message-ID: >Chris Curvey" wrote in message news:1118191737.550326.267750 at g43g2000cwa.googlegroups.com... > thanks for all the help. I'll give the ShellExecute() approach a try > in the morning. > > The short version of what I'm trying to do is.... > > Have my website login to a 3rd party website on behalf of my customer, > fill out a form, and submit it. I'm just using CGI to keep things > simple, but overlapping requests from different customers are the > problem. The 3rd party site uses a lot of javascript, so mechanize > isn't going to work. I could use some kind of locking mechanism and > "single-thread" access to IE, but that won't scale. I guess the next > approach would be to queue the requests and have a pool of worker > processes (running as different users) process the requests and report > back. You might have a specific reason for using COM, but if not, have you considered using the python urllib or urllib2 modules instead? It should overcome the session cookie / overlapping request issues i think. From simon.brunning at gmail.com Thu Jun 2 08:06:21 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 2 Jun 2005 13:06:21 +0100 Subject: how to retrieve info about print jobs In-Reply-To: <3EAne.108100$xW2.6437935@phobos.telenet-ops.be> References: <3EAne.108100$xW2.6437935@phobos.telenet-ops.be> Message-ID: <8c7f10c605060205062be3b8fe@mail.gmail.com> On 6/2/05, Guy Lateur wrote: > We have several printers in our company network. I would like to know if it > is possible to check the current print jobs/queues for each of them. That > way, if a user wants to print something (big), I could give her a hint as to > which printer would get the job done first. We're using win2k and xp, btw. You can probably do this with WMI. Ah yes, see . You can drive WMI from Python with Tim Golden's WMI module - . Do let us know what you come up with! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Mon Jun 13 11:48:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Jun 2005 11:48:04 -0400 Subject: case/switch statement? In-Reply-To: References: Message-ID: Peter Hansen wrote: > Chinook wrote: > >>On Sun, 12 Jun 2005 17:19:06 -0400, Peter Hansen wrote: >> >>>Case statements are actually more suitable in many cases even when >>>performance is not a goal for reasons of *readability*. >>> >>>When reading an if statement, you have to scan down through effective >>>each statement attempting to find the case in which you are interested. >>> Some cases can be compound. The nested ifs can get confused with the >>>surrounding ones (in Python or a language with explicit block >>>delimiters). The cases are often not written in any particular order, >>>or they are ordered *for* performance reasons, but in ways that make it >>>harder to "scan". >> >>The problem I do see is your apples and oranges argument. You are equating >>at the extreme, "compound" if conditions with "_simple_" case statement >>conditionals. Yet you are leaving out of your argument the transition from >>the former to the latter. If mapping one to the other is simple then the >>readability is no harder with if statements. > > > I dispute that, and believe you've misunderstood my core point. It's > not anything to do with "equivalence" between the two approaches. It's > that if you see a set of if/else statements, you have to look at all of > them to understand completely what's happening. (I mean the structure > of the if/else... the conditionals, not the contents of the blocks.) > With a case statement, on the other hand, you *know* that it must be > just simple conditionals (a series of x == some_constant tests), so you > don't need to look at all the cases, just the one that interests you. > > So it's not a comparison between two ways of writing the same thing, > it's about the fact that with a case statement there are many things you > *cannot* write, so reading one is much easier than reading a similarly > sized compound if/else. > While this is how case statements *tend* to be used, it is of course trivially possible to rewrite any if-then as a case: case : value True: ... value False: ... This would, of course, be a perversion of the purpose of the case statement, and I agree with you that in *normal* usage the case statement is easier to read because once you see the opening clause you know a) that only one of the following cases will be executed, and b) that control flow will resume after the case construct. So despite my nitpicking I do agree with you that there's a margin of readability that it might be useful to include in Python to avoid the sometimes-lengthy if-elif-elif-elif-elif-elif strings one sometimes sees - particularly so if any of the cases require conditionals, as nested conditionals are probably among the more difficult sequences to read. > This is much like saying that a short function is easier to read than a > long one. The long one can obviously do much more, so it's an apples > and oranges comparison in that sense. But clearly if the short one fits > all on one screen and the long one does not, the short one is basically > much easier to grok. > > That's all I'm saying. > And I'm agreeing. > >>In my experience I've also seen where case statements promote overly long and >>partially repetitive code blocks, which would be better constructed in a >>top-down fashion. Admittedly, if statements could be used in a similar way >>but I've not seen the same level of abuse with such. > > > That's true. > Indeed any language can be abused, but Python is more concerned with making it easy to write good programs than difficult to write bad ones. > >>So arguably, if the translation is pretty much one to one then the argument >>is mute :~) > > ^^^^ "moot" > Well, if the argument never said anything perhaps it *was* mute too? :-) > Sort of, except my point here would be that a case statement is then the > better choice in many cases because it communicates to the reader that > the entire thing *is* simple, while the if/else/if/else does not. > > -Peter Precisely. regards Steve -- Steve Holden +1 703 861 4237 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ From hancock at anansispaceworks.com Mon Jun 13 19:28:32 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 18:28:32 -0500 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> Message-ID: <200506131828.32769.hancock@anansispaceworks.com> On Monday 13 June 2005 09:34 am, Steven D'Aprano wrote: > On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote: > > wrote: > >> It means in windows we should use 'wb' to write and 'rb' to read ? > >> Am I right? > > no. > > you should use "wb" to write *binary* files, and "rb" to read *binary* > > files. > > > > if you're working with *text* files (that is, files that contain lines of text > > separated by line separators), you should use "w" and "r" instead, and > > treat a single "\n" as the line separator. > > I get nervous when I read instructions like this. It sounds too much like > voodoo: "Do this, because it works, never mind how or under what > circumstances, just obey or the Things From The Dungeon Dimensions will > suck out your brain!!!" Actually, it's very simple. It just means that '\n' in memory maps to '\r\n' on disk, and vice-versa. So long as you remain on Windows (or MS-DOS for that matter). > When you read a Windows text file using "r" mode, what happens to the \r > immediately before the newline? Do you have to handle it yourself? Or will > Python cleverly suppress it so you don't have to worry about it? '\n' in memory, '\r\n' on disk. Do the same thing on a Linux or Unix system, and it's '\n' in memory, '\n' on disk and on the Mac: '\n' in memory, '\r' on disk > And when you write a text file under Python using "w" mode, will the > people who come along afterwards to edit the file in Notepad curse your > name? Notepad expects \r\n EOL characters, and gets cranky if the \r is > missing. No, all will be well. So long as you use 'r' (or 'rt' to be explicit) and 'w' (or 'wt'). Only use 'rb' and 'wb' if you want to make sure that what is on disk is literally the same as what is in memory. If you write text files this way in Python, you will get '\n' line endings. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From kent37 at tds.net Sun Jun 5 13:03:16 2005 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Jun 2005 13:03:16 -0400 Subject: Iterate through a list calling functions In-Reply-To: References: Message-ID: <42a33011$1_1@newspeer2.tds.net> David Pratt wrote: > Hi. I am creating methods for form validation. Each validator has its > own method and there quite a number of these. For each field, I want to > evaluate errors using one or more validators so I want to execute the > appropriate validator methods from those available. I am iterating over > each validator using validateField method to gather my results. It works > but it ugly and inefficient. Can someone advise whether there is a > better way of doing this. I realize that the validator variable in my > iteration is only a string so question is how can I make the validator > string reference a function so I may be able to shorten validateField to > something similar to this (instead of my long list of ifs which I am not > very happy with): > > for validator in validators_list: > result = validator(name, value) > if type (result) in StringTypes: > results[name] = result Actually you can do exactly that by putting references to the validator functions in your list instead of (string) name. For example if you have validators = [ 'isDecimal', 'isFoo', 'isBar' ] just change it to validators = [ isDecimal, isFoo, isBar ] and your loop above will work. Python makes data-driven programming easy :-) Kent > > Many thanks > David > > My current situation below: > > # A large list of validators > def isDecimal(name, value): > """ Test whether numeric value is a decimal """ > result = validateRegex(name, > value, > r'^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$', > errmsg='is not a decimal number.', > ignore=None) > return result > > def isZipCode(name, value): > """ Tests if field value is a US Zip Code """ > result = validateRegex(name, > value, > r'^(\d{5}|\d{9})$', > errmsg='is not a valid zip code.', > ignore=None) > return result > > ... more validators > > # Iterating over validators to gather field errors > def validateField(name, value, validators_list, range=None, > valid_values=None): > """ Validates field input """ > results={} > for validator in validators_list: > if validator == 'isContainedIn': > result = isContainedIn(name, value) > if type (result) in StringTypes: > more... > if validator == 'isDate': > result = isDate(name, value) > if type (result) in StringTypes: > more... > if validator == 'isDecimal': > result = isDecimal(name, value) > if type (result) in StringTypes: > more... > > more validators ... > From dalke at dalkescientific.com Wed Jun 1 14:58:06 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Wed, 01 Jun 2005 18:58:06 GMT Subject: pickle alternative References: <1117520276.417970.207680@g14g2000cwa.googlegroups.com> <1117524878.988878.181820@g44g2000cwa.googlegroups.com> <1117527950.319411.193030@g44g2000cwa.googlegroups.com> <1117606128.506536.234690@g14g2000cwa.googlegroups.com> <1117615222.581838.226820@g49g2000cwa.googlegroups.com> Message-ID: simonwittber wrote: > It would appear that the new version 1 format introduced in Python 2.4 > is much slower than version 0, when using the dumps function. Interesting. Hadn't noticed that change. Is dump(StringIO()) as slow? Andrew dalke at dalkescientific.com From mg.mailing-list at laposte.net Wed Jun 1 10:06:53 2005 From: mg.mailing-list at laposte.net (mg) Date: Wed, 01 Jun 2005 16:06:53 +0200 Subject: Python 2.5 CVS broken for HP-UX platform? Message-ID: <429DC0FD.4030500@laposte.net> Hello, While trying to compile Python 2.5 from the nighlty CVS image, it raises the following errors on HP-UX. This disables me the use of HP-UX for some projects: Compilation flags: export CC=aCC export CFLAGS="-Ae +DD64" export LDFLAGS="+DD64" make clean ./configure --prefix=/usr/local/python_cvs --with-cxx=aCC (...) creating Makefile aCC -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/ccpython.o ./Modules/ccpython.cc "/usr/include/sys/unistd.h", line 594: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline truncate(const char *a, off_t b) { return __truncate64(a,b); } ^ "/usr/include/sys/unistd.h", line 595: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline prealloc(int a, off_t b) { return __prealloc64(a,b); } ^ "/usr/include/sys/unistd.h", line 596: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline lockf(int a, int b, off_t c) { return __lockf64(a,b,c); } ^ "/usr/include/sys/unistd.h", line 597: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline ftruncate(int a, off_t b) { return __ftruncate64(a,b); } ^ "/usr/include/sys/stat.h", line 173: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline lstat __((const char *, struct stat *)); ^ "./Include/pyport.h", line 612: error #2035: #error directive: "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." ^ 1 error detected in the compilation of "./Modules/ccpython.cc". *** Error exit code 2 Stop. aCC -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE -o Modules/ccpython.o ./Modules/ccpython.cc "/usr/include/sys/unistd.h", line 594: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline truncate(const char *a, off_t b) { return __truncate64(a,b); } ^ "/usr/include/sys/unistd.h", line 595: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline prealloc(int a, off_t b) { return __prealloc64(a,b); } ^ "/usr/include/sys/unistd.h", line 596: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline lockf(int a, int b, off_t c) { return __lockf64(a,b,c); } ^ "/usr/include/sys/unistd.h", line 597: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline ftruncate(int a, off_t b) { return __ftruncate64(a,b); } ^ "/usr/include/sys/stat.h", line 173: warning #2837-D: omission of explicit type is nonstandard ("int" assumed) inline lstat __((const char *, struct stat *)); ^ "./Include/pyport.h", line 612: error #2035: #error directive: "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." ^ 1 error detected in the compilation of "./Modules/ccpython.cc". *** Error exit code 2 Stop. From grante at visi.com Mon Jun 6 19:18:46 2005 From: grante at visi.com (Grant Edwards) Date: Mon, 06 Jun 2005 23:18:46 -0000 Subject: Creating file of size x References: <42a4cea6$1@griseus.its.uu.se> Message-ID: <11a9mem8b2p0t7b@corp.supernews.com> On 2005-06-06, Jan Danielsson wrote: > Is there any way to create a file with a specified size? Sure: 1) Open a new file for writing. 2) Seek to "specified size"-1. 3) Write one byte. -- Grant Edwards grante Yow! I just put lots of at the EGG SALAD in the SILK visi.com SOCKS -- From d at e.f Fri Jun 17 16:15:25 2005 From: d at e.f (D H) Date: Fri, 17 Jun 2005 15:15:25 -0500 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> Message-ID: Peter Hansen wrote: >> But apparently some guru I greatly respect thinks so >> (I'm not kidding, http://www.spellen.org/youcandoit/). > > > With respect to the author, and an understanding that there is probably > much that didn't go into his self-description (add "about.htm" to the > above URL), it sounds as though he knows primarily, perhaps solely, C > and C++, and has done relatively little serious development since he > seems to have spent most of his time either teaching or writing (words, > not source code). > > Does he even *know* any real high level languages such as Python? So you say he "has done relatively little serious development" and that he may not even know about Python. I didn't see any evidence from those pages to draw either conclusion. In fact the 4th paragraph quite contradicts them both. From mdelliot at gmail.com Tue Jun 21 18:18:50 2005 From: mdelliot at gmail.com (Micah) Date: Tue, 21 Jun 2005 15:18:50 -0700 Subject: *Python* Power Tools Message-ID: Anyone know if there is any organized effort underway to implement the Python equivalent of "Perl Power Tools" ? If not, would starting this be a waste of effort since: - it's already being done in Perl? - cygwin thrives? - UNIX is already pervasive :-) ? Or would people really like to claim a pure Python set of UNIX utilities? -- Micah From gethuy at gmail.com Wed Jun 15 18:48:57 2005 From: gethuy at gmail.com (huy) Date: Thu, 16 Jun 2005 08:48:57 +1000 Subject: Strange socket problem In-Reply-To: References: Message-ID: <42B0B059.107@swiftdsl.com.au> Hi Jeff, Thanks for your help. Although I haven't confirmed this, I think you just hit my nail on the head. I thought os.system was like a totally separate process though, i.e nothing is shared. not the usual fork() call within the program. Regards, Huy Jeff Epler wrote: > When using os.system(), files that are open in the parent are available > in the child, as you can see here in Linux' listing of the files open by > the child program: > > [jepler at sofa jepler]$ python -c 'f = open("/tmp/test", "w"); print f.fileno(); import os; os.system("ls -l /proc/self/fd")' > 3 > total 5 > lrwx------ 1 jepler jepler 64 Jun 15 07:25 0 -> /dev/pts/2 > lrwx------ 1 jepler jepler 64 Jun 15 07:25 1 -> /dev/pts/2 > lrwx------ 1 jepler jepler 64 Jun 15 07:25 2 -> /dev/pts/2 > l-wx------ 1 jepler jepler 64 Jun 15 07:25 3 -> /tmp/test > lr-x------ 1 jepler jepler 64 Jun 15 07:25 4 -> /proc/3108/fd > > You may be able to set the FD_CLOEXEC flag on the files that should not > be passed to children, something like this: > old = fcntl.fcntl(fd, fcntl.F_GETFD) > fcntl.fcntl(fd, fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) > Refer to a real Unix reference for more information on what FD_CLOEXEC > does. > > You may want to replace the use of os.system() with fork + close files > + exec. Then "myserver.py" will no longer have the listening socket > descriptor of your cherrypy server. > > Python 2.4's 'subprocess' module may work better in this respect than > os.system. It seems to include support for requesting that fds be > closed in the child (the close_fds parameter to subprocess.Popen) > > Jeff From codedivine at gmail.com Tue Jun 28 20:12:59 2005 From: codedivine at gmail.com (Rahul) Date: 28 Jun 2005 17:12:59 -0700 Subject: strange __call__ Message-ID: <1120003979.370234.143930@g47g2000cwa.googlegroups.com> Consider the following: def a(x): return x+1 def b(f): def g(*args,**kwargs): for arg in args: print arg return f(*args,**kwargs) return g a.__call__ = b(a.__call__) now calling a(1) and a.__call__(1) yield 2 different results!! i.e. for functions a(1) doesnt seem to be translated to a.__call__ if you assign a new value to a.__call__? i am using python 2.3.3 somebody please clear this confusion From rbt at athop1.ath.vt.edu Wed Jun 1 15:51:41 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 01 Jun 2005 15:51:41 -0400 Subject: Calculating Inflation, retirement and cost of living adjustments over 30 years Message-ID: Is this mathematically correct? def inflation(): start = int(str.strip(raw_input("How much money do you need each month at the start of retirement: "))) inflation = float(str.strip(raw_input("What will inflation average over the next 30 years(.03, .04, etc): "))) for x in xrange(30): start = start*inflation+start print start inflation() From trentm at ActiveState.com Tue Jun 28 17:01:19 2005 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 28 Jun 2005 14:01:19 -0700 Subject: ANN: ActivePython 2.4.1 for Solaris 10 on SPARC, x86 and x64 systems In-Reply-To: <20050628004620.GA1935@ActiveState.com> References: <20050627235717.GA27064@ActiveState.com> <200506280010.j5S0Aqnv030806@smtp3.ActiveState.com> <20050628004620.GA1935@ActiveState.com> Message-ID: <20050628210118.GB31180@ActiveState.com> I'm happy to announce that ActivePython 2.4.1 for Solaris 10 on SPARC, x86 and x64 systems is now available for free download from: http://www.ActiveState.com/Products/ActivePython/ This release adds support for Solaris running on x86 and x64 systems. Note: This release (build 247) also includes important updates for the recently released ActivePython for Mac OS X. Please see the release notes for details. http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/relnotes.html#release_history What is ActivePython? --------------------- ActivePython is ActiveState's quality-assured binary distribution of Python. Builds for Linux, Mac OS X, Solaris and Windows are made freely available. ActivePython includes the Python core and core extensions (zlib 1.2.1, bzip2 1.0.2, bsddb 4.2.52, Tk 8.4.9, and Tix 8.1.4) and is fully compatible with other Python distributions of the same version. ActivePython also includes a wealth of Python documentation, including: - the core Python docs; - Andrew Kuchling's "What's New in Python" series; - the Non-Programmer's Tutorial for Python; - Mark Pilgrim's excellent "Dive into Python"; and - a snapshot of the Python FAQs, HOWTOs and PEPs. An online version of the docs can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/welcome.html Thanks, and enjoy! Trent, Python Tech Lead -- Trent Mick TrentM at ActiveState.com From kent37 at tds.net Tue Jun 21 11:15:51 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Jun 2005 11:15:51 -0400 Subject: use a regex or not? In-Reply-To: <1119363495.274573.131630@g14g2000cwa.googlegroups.com> References: <1119363495.274573.131630@g14g2000cwa.googlegroups.com> Message-ID: <42b82e95$1_3@newspeer2.tds.net> Joost Jacob wrote: > I am looking for a function that takes an input string > and a pattern, and outputs a dictionary. Here is one way. I won't say it's pretty but it is fairly straightforward and it passes all your tests. Kent def fill(s, p): """ >>> fill('ab', p='aA') {'A': 'b'} >>> fill('ab', p='Ab') {'A': 'a'} >>> fill('bb', p='Aa') # no match {} >>> fill('aa', p='Aa') {'A': 'a'} >>> fill('aa', p='Ab') # no match {} >>> fill('abb', p='aA') {'A': 'bb'} >>> fill('aba', p='aAa') {'A': 'b'} >>> fill('abb', p='aAa') # no match {} >>> fill('abab', p='aAaA') # A-matches must be equal {'A': 'b'} >>> fill('abac', p='aAaA') # no match {} >>> fill('abac', p='aAaB') {'A': 'b', 'B': 'c'} """ # If s is longer than p the extra chars of s become part of the # last item of s if len(s) > len(p): ss = list(s[:len(p)]) ss[-1] = ss[-1] + s[len(p):] s = ss d = {} seen = {} for s1, p1 in zip(s, p): # Lower case have to map to themselves if p1.islower() and s1 != p1: # print 'Non-identity map for %s: %s' % (p1, s1) return {} try: # Check for multiple mappings from p1 old_s = d[p1] if old_s != s1: # We saw this s before but the mapping is different return {} # We saw this s1, p1 before with the same mapping continue except KeyError: # Check for multiple mappings to p1 if seen.get(s1, p1.lower()) != p1.lower(): return {} # This is a new mapping d[p1] = s1 seen[s1] = p1.lower() # Strip out the lower case mappings return dict((k, v) for k, v in d.iteritems() if k.isupper()) def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() From darkpaladin79 at hotmail.com Mon Jun 6 19:56:13 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Mon, 06 Jun 2005 19:56:13 -0400 Subject: help with sending mail in Program In-Reply-To: <1118101774.792153.203440@z14g2000cwz.googlegroups.com> Message-ID: Ugh. . .I'm really confused. In the example I saw the message was taken from a file on the computer. . .Like it opened it and then sent it. I guess I just need to check out the whole thing a bit more before I get specific. I'll ask again if I need specific help. thanks, -Ivan _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From duncan.booth at invalid.invalid Fri Jun 10 08:08:36 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jun 2005 12:08:36 GMT Subject: match groups: optional groups not accessible References: <1118403410.852579.24710@z14g2000cwz.googlegroups.com> Message-ID: david.reitter wrote: > So I would expect None rather than an IndexError, which is (only?) > supposed to occur "If a string argument is not used as a group name in > the pattern". That is exactly what does happen. > > I would expect named groups and numbered groups to be behave the same > way. > Where's my mistake? Using 'maybe' as a group name when the only group in the pattern is called 'm'. > >>>> import re >>>> m = re.match('(?Pmaybe)?yes', "yes") >>>> m.group(1) >>>> m.group('maybe') > Traceback (most recent call last): > File "", line 1, in ? > IndexError: no such group > From steven.bethard at gmail.com Sat Jun 4 17:38:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Jun 2005 15:38:31 -0600 Subject: Scope In-Reply-To: <87k6laatxi.fsf@hector.domek> References: <87k6laatxi.fsf@hector.domek> Message-ID: Peter Dembinski wrote: > AFAIK inc is builtin function. And builtin functions doesn't have to > be real functions, they can be just aliases to Python's VM bytecodes > or sets of bytecodes. Wrong on both counts. ;) py> inc Traceback (most recent call last): File "", line 1, in ? NameError: name 'inc' is not defined py> __builtins__.inc Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'inc' There is no builtin 'inc'. To verify, check: http://docs.python.org/lib/built-in-funcs.html http://docs.python.org/lib/non-essential-built-in-funcs.html And while builtin functions may not have to be real *functions*, they do have to be real *callables*: py> type(abs) py> help(type(abs)) Help on class builtin_function_or_method in module __builtin__: class builtin_function_or_method(object) | Methods defined here: | | __call__(...) | x.__call__(...) <==> x(...) ... py> type(bool) py> help(type(bool)) Help on class type in module __builtin__: class type(object) | type(object) -> the object's type | type(name, bases, dict) -> a new type | | Methods defined here: | | __call__(...) | x.__call__(...) <==> x(...) ... Note that both and have a __call__ method, which means they are callable objects. They're not just bytecodes; they're real objects, just like everything else in Python. =) STeVe From fred at ucar.edu Thu Jun 30 19:22:20 2005 From: fred at ucar.edu (bandw) Date: 30 Jun 2005 16:22:20 -0700 Subject: Using Numeric 24.0b2 with Scientific.IO.NetCDF Message-ID: <1120173740.608413.242330@g49g2000cwa.googlegroups.com> I am having a problem using Numeric-24.0b2 in conjunction with the NetCDF module from ScientificPython (version 2.4.9). This problem does not surface using Numeric-23.8. The problem arises in using the "min" function on a NetCDF floating array. In 23.8, the "min" function returns a floating scalar, while in 24.0b2 it returns an *array* of length "1". Below I list a simple NetCDF file and a Python script that illustrate the problem. When I run the script using 23.8, I get the result: 1.0 whereas using 24.0b2 I get: 1.0 This creates a backward incompatibility that breaks several of my codes. NetCDF file simple.cdl (used to create simple.nc with "ncgen") -------------------------------------------------------------- netcdf simple { dimensions: num = 3 ; variables: float temp(num) ; data: temp = 1, 2, 3 ; } Python script ------------- import Numeric from Scientific.IO.NetCDF import NetCDFFile cdf_file1 = NetCDFFile("simple.nc","r") temp = cdf_file1.variables["temp"][:] print min(temp), type(min(temp)) From joxeankoret at yahoo.es Wed Jun 29 09:22:47 2005 From: joxeankoret at yahoo.es (Joxean Koret) Date: Wed, 29 Jun 2005 15:22:47 +0200 Subject: XMLRPC and non-ascii characters Message-ID: <1120051367.9425.4.camel@localhost.localdomain> Hi to all! I'm having troubles to make my XMLRPC application working with non ASCII characters. Example: 1.- In one terminal run the following script: -----------XMLRPC Server------------- import SimpleXMLRPCServer server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost",8003)) def test(): return "Test with the non ascii character '?'" server.register_function(test) server.serve_forever() -----------XMLRPC Server------------- 2.- In a second terminal run this: -----------XMLRPC Client------------- import xmlrpclib server = xmlrpclib.Server(("localhost", 8003)) server.test() -----------XMLRPC Client------------- When you runs the XMLRPC Client script the following error is raised: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/xmlrpclib.py", line 1032, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.3/xmlrpclib.py", line 1319, in __request verbose=self.__verbose File "/usr/lib/python2.3/xmlrpclib.py", line 1083, in request return self._parse_response(h.getfile(), sock) File "/usr/lib/python2.3/xmlrpclib.py", line 1217, in _parse_response p.feed(response) File "/usr/lib/python2.3/xmlrpclib.py", line 528, in feed self._parser.Parse(data, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 5, column 50 Any ideas of what can I do? Regards, Joxean Koret -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Esta parte del mensaje est? firmada digitalmente URL: From steve at REMOVETHIScyber.com.au Fri Jun 10 10:57:19 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sat, 11 Jun 2005 00:57:19 +1000 Subject: Annoying behaviour of the != operator References: <3gpsl0Fdhq0mU1@individual.net> Message-ID: On Thu, 09 Jun 2005 08:10:09 -0400, Dan Sommers wrote: >>> The main problem is that Python is trying to stick at least three >>> different concepts onto the same set of operators: equivalence (are >>> these two objects the same?), ordering (in a sorted list, which comes >>> first?), and mathematical "size". [snip] >>> This gives the wacky world where >>> "[(1,2), (3,4)].sort()" works, whereas "[1+2j, 3+4j].sort()" doesn't. > > Python inherits that wackiness directly from (often wacky) world of > Mathematics. > > IMO, the true wackiness is that > > [ AssertionError, (vars, unicode), __name__, apply ].sort( ) > > "works," too. Python refusing to sort my list of complex numbers is a > Good Thing. Only if you understand sorting as being related to the mathematical sense of size, rather than the sense of ordering. The two are not the same! If you were to ask, "which is bigger, 1+2j or 3+4j?" then you are asking a question about mathematical size. There is no unique answer (although taking the absolute value must surely come close) and the expression 1+2j > 3+4j is undefined. But if you ask "which should come first in a list, 1+2j or 3+4j?" then you are asking about a completely different thing. The usual way of sorting arbitrary chunks of data within a list is by dictionary order, and in dictionary order 1+2j comes before 3+4j because 1 comes before 3. This suggests that perhaps sort needs a keyword argument "style", one of "dictionary", "numeric" or "datetime", which would modify how sorting would compare keys. Perhaps in Python 3.0. -- Steven. From peter at engcorp.com Tue Jun 14 20:54:20 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 20:54:20 -0400 Subject: collect data using threads In-Reply-To: References: <42aeeef3$1_1@newspeer2.tds.net> <4q2dneNoafbYljLfRVn-sQ@powergate.ca> Message-ID: Toby Dickenson wrote: > But it might not "show up" until too late. > > The consumer thread that called get_data presumably does something with that > list, such as iterating over its contents. It might only "show up" after that > iteration has finished, when the consumer has discarded its reference to the > shared list. I was going to point out that the consuming thread is the one calling get_data(), and therefore by the time it returns (to iterate over the contents), self.data has already been rebound to a new list. That was before Kent correctly analyzed this yet again and shows how the on_received call can itself be the source of the trouble, via the separate attribute lookup and append call. (I'm going to hand in my multi-threading merit badge and report to Aahz for another Queue "reprogramming" session for missing on this twice.) -Peter From onurb at xiludom.gro Tue Jun 7 04:33:01 2005 From: onurb at xiludom.gro (bruno modulix) Date: Tue, 07 Jun 2005 10:33:01 +0200 Subject: Question about Object Oriented + functions/global vars? In-Reply-To: <1118112887.825446.78870@g14g2000cwa.googlegroups.com> References: <1118022058.698975.73210@g47g2000cwa.googlegroups.com> <1118074376.475660.183950@g44g2000cwa.googlegroups.com> <1118112887.825446.78870@g14g2000cwa.googlegroups.com> Message-ID: <42a55bbe$0$24423$636a15ce@news.free.fr> gene tani wrote: > #include canonical design pattern advice > > longjmp(Borders or other_big_chain_bookstore) > > opt1=fopen("Oreilly's Head first design pattern","r") > opt2=fopen("design patterns book by Shalloway and trott (i think that's > their names)","r") > > another=poll("any other intro to DP books that people like?") another.append(what_about("GOF")) -- bruno desthuilliers ruby -e "print 'onurb at xiludom.gro'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@')" From david.van.mosselbeen at telenet.be Mon Jun 13 11:19:00 2005 From: david.van.mosselbeen at telenet.be (David Van Mosselbeen) Date: Mon, 13 Jun 2005 15:19:00 GMT Subject: Show current ip on Linux Message-ID: Hi, Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine man :-) My question is : How can i rwite a script that show my current ip. If i have more than one network card, the script must then show all used ip. It's important that this will work on a linux. i Have rwite some piece of code that realy work under Windows XP, but the same script wil not work on Linux. Verry thanks to all vulunteers. -- David Van Mosselbeen - DVM http://dvm.zapto.org:3333 --- Fedora Core 3 User From chad.hughes at pnl.gov Mon Jun 20 14:27:50 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Mon, 20 Jun 2005 11:27:50 -0700 Subject: Python choice of database Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B61A1@pnlmse27.pnl.gov> One db that is very much worth trying is Firebird. This is an open source Interbase 6.0 (Borland product) compatible db. It is a SourceForge project. There are three versions: the super server which is a client/server db, classic server (the one that I am very familiar with) which is also a client/server db, and the embedded server which is a standalone. In order to access the database you need the open source module KInterbasdb which is also a SourceForge project. KInterbasdb is a Python DB API 2.0 database driver. Firebird has a lot of documentation. Moreover it was made based on the Interbase 6.0, which is was made open source by Borland, so all of Borland's documentation and tools apply as well. Firebird can be found at: http://firebird.sourceforge.net/ KInterbasdb can be found at: http://kinterbasdb.sourceforge.net/ -----Original Message----- From: python-list-bounces+chad.hughes=pnl.gov at python.org [mailto:python-list-bounces+chad.hughes=pnl.gov at python.org] On Behalf Of Philippe C. Martin Sent: Monday, June 20, 2005 8:19 AM To: python-list at python.org Subject: Python choice of database Hi, I am looking for a stand-alone (not client/server) database solution for Python. 1) speed is not an issue 2) I wish to store less than 5000 records 3) each record should not be larger than 16K As I start with Python objects, I thought of using shelve, but looking at the restrictions (record size + potential collisions) I feel I should study my options a bit further before I get started. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list From hammer at maxwell.com Sat Jun 11 11:34:14 2005 From: hammer at maxwell.com (Maxwell Hammer) Date: Sat, 11 Jun 2005 11:34:14 -0400 Subject: Python Developers Handbook - Mistake done and corrected. References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> <1118399995.306455.161220@o13g2000cwo.googlegroups.com> <1118404332.349662.82650@g44g2000cwa.googlegroups.com> Message-ID: On Fri, 10 Jun 2005 04:52:12 -0700, wooks wrote: > > Your understanding of Usenet is that a post has to "appeal" (for the > want of a better word) to the majority of the NG readership. > > Look over a hundred people took a look (and the hits are steadily > going up whether despite or because of this thread). I am not going to > posit either way as to whether that amounts to vindication but it does > suggsest that I have not comitted the heinous crime against netiquette > that some people are making out. Actually you're making a mistake there: Maybe 100 people took a look at Wook's book, but a lot more than 100 people were pissed off at yet another Commercial post. Next time use the "announce" NG. Always ask youself...so if 2 billion people did what I'm about to do, will it make a big stink? Most times the answer is: a huge stink. Cheers. From darkpaladin79 at hotmail.com Tue Jun 7 16:18:08 2005 From: darkpaladin79 at hotmail.com (Ivan Shevanski) Date: Tue, 07 Jun 2005 16:18:08 -0400 Subject: Help with SMTP Message-ID: Ok, all my problems are solved except for one. . .If I want my program to send a message back to me do I need the from adress? Because I don't specifically know it for the person using the program. Any help is appreciated =D -Ivan _________________________________________________________________ FREE pop-up blocking with the new MSN Toolbar ? get it now! http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/ From here at there.net Sat Jun 11 11:12:46 2005 From: here at there.net (Drazen Gemic) Date: Sat, 11 Jun 2005 17:12:46 +0200 Subject: Dealing with marketing types... References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: On Fri, 10 Jun 2005 13:41:13 -0500, phil wrote: > >> >> What experiences have those in the Python community had in these kinds >> of situations? >> > Ive had lots of experience updating my resume and > > developing software at home. In Python. > > Java is a clumsy kludge. And the java environment has gone to hell. I am a freelance developer and I prefer to do job in Java over anything else. I love Python, and it is my favourite language, but there are some problems. With Java I depend very little on customers IT staff, sysadmins, etc. If I need additional functionality in form library, extension, whatever, all I need is to drop another JAR in, and that does it. With Python, the situation is different. Often, some kind of modules are required to be compiled, or packages installed. Generaly, I do not have sufficient privileges on customers system to do that. IT personell might be willing and capable to do that, and might be not. There could be some inter-department politics and/or friction involved at customers side which may turn into serious obstacle. Thnks, but I stick with Java. And considering Jython in the future. DG From philippe at philippecmartin.com Fri Jun 10 09:26:23 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 10 Jun 2005 13:26:23 GMT Subject: howto send html mails using smtplib References: Message-ID: <3ygqe.3180$%j7.1271@newssvr11.news.prodigy.com> Tim, You are most correct, replace_header did the trick. Thanks a bunch. Philippe Tim Williams wrote: > "Philippe C. Martin" wrote in message > news:sD3qe.2270$751.1207 at newssvr30.news.prodigy.com... >> I have the following problem: >> 1) I can use smtplib to send text messages >> 2) I can generate html >> 3) I want to email the html and want it to be seen by the email client as >> html. >> >> However, when I receive the message, the email client displays it as text >> (code hereunder) - I assume it has to do with the MIMEText call but since > I >> cannot see any MIMEhtml ..... > > > I suspect you need one of the following lines. > > msg.replace_header('Content-Type', 'text/html') > > msg.add_header('Content-Type', 'text/html') > > > HTH :) > From mwm at mired.org Sun Jun 12 04:24:17 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 12 Jun 2005 03:24:17 -0500 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42ABAB62.4040205@lexicon.net> Message-ID: <86ll5g2dam.fsf@guru.mired.org> John Machin writes: > Roy Smith wrote: >> "Philippe C. Martin" wrote: >>>Yet, many issues that a future software engineer should know are >>>mostly hidden by Python (ex: memory management) and that could be >>>detrimental. >> I know I'm going out on a limb by asking this, but why do you think >> future software engineers should know about memory management? > Perhaps we have a terminology problem here i.e. different meanings of > "software engineer". Philippe started talking about "CS" courses, > whereas you may be referring to people who have done an "IT" course or > achieved a certification in the use of app development tool X. While I agree with John - software engineers should know something about memory managment - I sort of agree with Roy as well, in that, like Peter, I think memory management is something that doesn't need to be taught immediately. A modern programming environment should take care of the details, but a software engineer will be cognizant of the details, and know enough to know when they have to worry about it and when they can safely ignore it. >> I used to worry about register allocation. Today, I don't even know >> how many registers any machine I work on has. I used to worry about >> word size, and byte order. I used to worry about whether stacks >> grew up or down and addressing modes and floating point formats. >> Sure, somebody's got to worry about those things, but most people >> who write software can be blissfully ignorant (or, at best, dimly >> aware) of these issues because somebody else (compiler writer, >> hardware designer, operating system writer, etc) has already done >> the worrying. > You would hope they'd done more than worry about it. However sometimes > one's fondest hopes are dashed. You must have noticed the anguish in > the timbot's posts that mention Windows 95 memory management. I think most of those things are indeed things that your average software engineer can ignore 90+% of the time. What makes someone a software engineer is that they know about those details, and know how they will affect the code they are writing - and hence when they have to worry about those details. Oddly enough, I find similar comments apply to a lot of the data structures I learned in school. I recently applied for a job that had a series of essay questions in the application. They had a series of problems with requests for solutions, and my immediate reaction to each was to reach for off-the-shelf software to solve the problem. While they wanted - and I provided - a discussion of data structures and big-O running time for various operations, all the things they wanted to do were essentially solved problems, and there was debugged and tuned code available to deal with things - and it's much faster to not write software if you can to solve the problem. For instance, one problem was "You have two files that have lists of 1 billion names in them. Print out a list of the names that only occur in one of the files." That's a one-line shell script: "comm -12 <(sort file_one) <(sort file_two)" I gave them that answer. I also gave them a pseudo-code solution, but frankly, in real life, I'd install the shell script and get on with things. If I were hiring someone, I'd hire the person who gave me the shell script. Rather than spending hours/days debugging a program to solve the problem, I get a solution in minutes. If it runs into problems, *then* it's time to start hand coding the solution. >> There used to be a time when you had to worry about how many tracks >> to allocate when you created a disk file. When's the last time you >> worried about that? > Seeing you asked: early 1970s, on an IBM 1800. But much more recently > it certainly helped if one were slightly more than dimly aware of the > difference between a FAT filesystem and an NTFS filesystem :-) For me it was the late 1970s, on an IBM 3081. But I was worried about disk sector sizes well into the 1990s. Since then I've worked on systems that didn't have a file system as such; it had a database of databases, and you queried the former to find the latter. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From __peter__ at web.de Sun Jun 26 02:45:54 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 26 Jun 2005 08:45:54 +0200 Subject: Big problem fetching members from dynamically loaded module References: Message-ID: Philippe C. Martin wrote: > Any clue would be quite welcome. I didn't recognize the pattern in the code you posted, but sometimes the order of imports matters: $ find . . ./package ./package/beta.py ./package/alpha.py ./package/__init__.py $ python Python 2.3.3 (#1, Feb 5 2005, 16:22:10) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from package.beta import * >>> from package import * >>> from package.alpha import * >>> alpha Traceback (most recent call last): File "", line 1, in ? NameError: name 'alpha' is not defined >>> beta The 'right' way to do the imports if you want both 'alpha' and 'beta' is of course from package import alpha from package import beta Peter From vincent at visualtrans.de Sun Jun 19 16:35:13 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 19 Jun 2005 22:35:13 +0200 Subject: tab 2 into tab 4 ? References: <1119205602.922944.204990@g44g2000cwa.googlegroups.com> Message-ID: schrieb im Newsbeitrag news:1119205602.922944.204990 at g44g2000cwa.googlegroups.com... | Hello, | | I have python code which use tab=2. Recently I would like to change it | into tab=4. | | Anyone has suggestion to convert easily and safely ? Look at "reindent.py" in Tools\Scripts. -- Vincent Wehren | | pujo | From jrastrick at student.usyd.edu.au Fri Jun 17 18:27:16 2005 From: jrastrick at student.usyd.edu.au (Jordan Rastrick) Date: 17 Jun 2005 15:27:16 -0700 Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? In-Reply-To: References: Message-ID: <1119047236.799404.215210@z14g2000cwz.googlegroups.com> Python's current scoping differs from that in versions 2.1 and earlier - statically nested (lexical) scoping was introduced under PEP 227. I don't know what differences, if any, remain between Python's and Perl's scoping rules, or if there is any tutorial concerning Python scoping thats aimed specifically at programmers with a Perl background. A pretty straightfoward explanation of the change to Python scoping rules can be found at: http://www.python.org/doc/2.2.3/whatsnew/node9.html From fperez.net at gmail.com Wed Jun 8 03:47:13 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 08 Jun 2005 01:47:13 -0600 Subject: Writing func_closure? Message-ID: Hi all, by reading through the docs, the func_closure attribute of function objects is listed as writable. Yet, nowhere does it say _how_ to write to it. I am trying to do a run-time modification of a function's closure, where I want to modify the value of one of the variables in the closure. But the closure appears as a tuple of 'cell' objects: In [21]: def wrap(x): ....: def f(y): ....: return x+y ....: return f ....: In [22]: f1=wrap('hello') In [23]: f1.func_closure Out[23]: (,) My question is, how can I create one of these cell objects to stuff into the closure (I want to do this from pure Python, not C extensions). The docs mention this as 'possible', but don't provide a single example (though they don't really specify if it can be done in python or only in C). The 'new' module is equally useless, since new.function() comes without any examples: In [25]: new.function? Type: type Base Class: String Form: Namespace: Interactive Docstring: function(code, globals[, name[, argdefs[, closure]]]) Create a function object from a code object and a dictionary. The optional name string overrides the name from the code object. The optional argdefs tuple specifies the default argument values. The optional closure tuple supplies the bindings for free variables. See that last line? Nowhere does it say what how the closure tuple is supposed to be constructed. I tried a bunch of things, and none of my shot-in-the-dark attempts got me anywhere. Any help on this would be much appreciated. Best, f From kent37 at tds.net Fri Jun 24 06:40:54 2005 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Jun 2005 06:40:54 -0400 Subject: trouble subclassing str In-Reply-To: References: <1119552587.363469.323580@g44g2000cwa.googlegroups.com> <1119554758.513632.87240@z14g2000cwz.googlegroups.com> Message-ID: <42bbe292$1_3@newspeer2.tds.net> Donn Cave wrote: > Left unexplained is ``true "is-a" relationships''. Sounds > like an implicit contradiction -- you can't implement > something that truly is something else. Without that, and > maybe a more nuanced replacement for "is-implemented-using-a", > I don't see how you could really be sure of the point. Try this article for an explanation of is-a: http://www.objectmentor.com/resources/articles/lsp.pdf IMO Robert Martin explains what good OO design is better than anyone else. His book "Agile Software Development" is excellent. Kent From benyang22 at yahoo.com Fri Jun 17 16:17:46 2005 From: benyang22 at yahoo.com (benyang22 at yahoo.com) Date: 17 Jun 2005 13:17:46 -0700 Subject: whos -- a function listing objects In-Reply-To: References: <1118948272.051392.323240@g14g2000cwa.googlegroups.com> Message-ID: <1119039466.023506.182260@g14g2000cwa.googlegroups.com> whos.py as a module would not work for global scope, as it hides the function whos in the module scope. I have fixed the string bug. From dela_f at excite.com Thu Jun 9 22:50:20 2005 From: dela_f at excite.com (Mark de+la+Fuente) Date: Thu, 9 Jun 2005 22:50:20 -0400 (EDT) Subject: Is pyton for me? Message-ID: <20050610025020.7B2FEBF76@xprdmailfe13.nwk.excite.com> I need to write simple scripts for executing command line functions. Up till now I've used C-Shell scripts for this, but I'm looking for a better alternative. And I keep reading about how ?easy? it is to program with python. Unfortunately after reading "diveintopython" and the python tutorial, I'm not sure how to do what I need to do. Here is an example of the type of thing I would like to be able to do. Can I do this with python? How do I get python to execute command line functions? >From the command prompt (not from the python interpreter ? running linux for example) I would type: gensky 3 21 12 > sky.rad This would call the non-python program ?gensky? which creates a computer model of a sky on march 21st at 12:00 PM and puts this information into a file called sky.rad. If I create a CSH script like the one below, I can automate tasks by building loops along the lines of: #!/bin/csh -fv # simple script to create multiple sky files. foreach hour (10 12 14) gensky 3 21 $hour > sky$hour.rad end If I try and do a gensky command from the python interpreter or within a python.py file, I get an error message: NameError: name ?gensky? is not defined So even if I get the python syntax correct, I can?t get these commands to execute. If anyone has any suggestions on how to get python scripts to execute this sort of thing, what I should be looking at, or if there is something else I might consider besides python, please let me know. Thanks for your help. Mark _______________________________________________ Join Excite! - http://www.excite.com The most personalized portal on the Web! From steve at REMOVETHIScyber.com.au Wed Jun 22 05:59:21 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Wed, 22 Jun 2005 19:59:21 +1000 Subject: Loop until condition is true References: Message-ID: On Wed, 22 Jun 2005 09:54:44 +0200, Fredrik Lundh wrote: >> [CENSORED] I keep for myself how stupid I found your post. > > so let's see if everyone who understands how embarrassingly stupid > your post is will keep that to themselves... Damn, did I fail some test? -- Steven. From tim.golden at viacom-outdoor.co.uk Wed Jun 29 05:00:59 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 10:00:59 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB944@vogbs009.gb.vo.local> [Greg Miller] | Hello again, I put the executable on the "virgin" PC today. | I am using | the wmi(b) that you gave me. The error that I am receiving now is: | | File "autoStart.pyc", line 241, in test | File "wmib.pyc", line 157, in ? | File "win32com\client\__init__.pyc", line 73, in GetObject | File "win32com\client\__init__.pyc", line 88, in Moniker | com_error: (-2147221020, 'Invalid syntax', None, None) | | any thoughts on this error? Thanks again for the help. Well that's a real pain! Is there any way you can run the un-py2exed script on the virgin PC. (I guess not, as I suppose the idea is not to have a Python installation). Perhaps you could do it with a non-installed Moveable Python? http://www.voidspace.org.uk/python/movpy/ In any case, what are the differences between the PC on which it works and the one on which it doesn't? Win2K vx WinXP? I'm trying to see if the problem is down to py2exe, or is to do with something in the module itself. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From gsakkis at rutgers.edu Tue Jun 21 20:28:06 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 21 Jun 2005 17:28:06 -0700 Subject: Compiling C++ extensions with distutils on Cygwin Message-ID: <1119400086.958159.182110@g44g2000cwa.googlegroups.com> I'm trying to build a C++ extension on Cygwin, but it fails because distutils invokes gcc instead of g++. Looking into distutils internals, it turns out that compilation is assumed to be independent of the target language, while linking is not (CCompiler.compile() doesn't take a target_lang argument but CCompiler.link() does). Is there a good reason for this ? George From averywarren at bellsouth.net Tue Jun 28 21:35:14 2005 From: averywarren at bellsouth.net (Avery Warren) Date: Tue, 28 Jun 2005 20:35:14 -0500 Subject: what is your opinion of zope? References: Message-ID: The real problem is that the version of wiki we currently use doesn't support any concept of workflow. That is fine for the company now but as it matures in its processes, a more mature solution will become more and more compelling. Various solutions include... 1. The current wiki implementation is open source, modify the freely available and unencumbered code to support workflow. 2. Convert the wiki files to plone documents that are already workflow enabled. 3. Write a new app that uses the current wiki docs but with the desired features. My inquiry to comp.lang.python is part of this investigation. I'm guessing that writing a zope application would be mandatory for option 2 and a desireable possibility for option 3. I'm also just curious as to the viability of zope from a developer's perspective. On Sun, 26 Jun 2005 23:14:48 -0500, Terry Hancock wrote: > However, I'm not sure why you want this information. If you are > trying to import data into Zope, you are more likely going to be > using Zope, not accessing ZODB directly. > > Without more specifics about what you are looking for, it would be > hard to reply further than this. > > Cheers, > Terry > > -- > Terry Hancock ( hancock at anansispaceworks.com ) > Anansi Spaceworks http://www.anansispaceworks.com From andreas at kostyrka.org Mon Jun 6 15:05:29 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon, 6 Jun 2005 21:05:29 +0200 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <20050602150655.GA30964@heaven.kostyrka.org> <86slzxa3bs.fsf@guru.mired.org> Message-ID: <20050606190529.GB17775@heaven.kostyrka.org> On Mon, Jun 06, 2005 at 06:08:36PM -0000, max wrote: > I guess my argument is that with multiple contributors, the gpl, in > comparison to say, a BSD style license, grants power to the code. If 3 > people work on a gpl project, they must agree to any changes. If 3 > people work on a BSD style project, they each can do whatever the hell > they like with the code. So, in my opinion, the gpl ends up giving > perhaps not rights, but certainly power, to the actual code base. Well, but it's not comparable: GPL without copyright assignment just leads to "community-owned" projects. Every part-owner owns his part. And it makes relicensing (taking the project closed-source) very difficult. That's a design feature, not a bug ;) Andreas From guy.lateurNNOOSSPPAAMM at pandora.be Tue Jun 14 15:44:54 2005 From: guy.lateurNNOOSSPPAAMM at pandora.be (guy lateur) Date: Tue, 14 Jun 2005 19:44:54 GMT Subject: Where is Word? References: Message-ID: > No, the subject is a good way to refer to past posts. I just meant > forcing us to dig back, when the post may no longer even be on our > servers, is not helpful. I agree, my bad. > (Perhaps I should ask why anyone would want to waste time putting > arbitrary fonts and colours and such around a simple directory listing, > but I won't. ) Please don't.. ;) g From news at NOwillmcguganSPAM.com Fri Jun 10 19:36:31 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Sat, 11 Jun 2005 00:36:31 +0100 Subject: Dealing with marketing types... In-Reply-To: References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <42a9a5c8$0$22628$da0feed9@news.zen.co.uk> Message-ID: <42aa2400$0$4095$db0fefd9@news.zen.co.uk> Diez B. Roggisch wrote: > Will McGugan wrote: > >> Marketing types need a bandwagon to jump on. Point out that Google is >> used by Google, ILM and NASA. > > > Certainly a true statement - but I've got the sneaky suspicion that the > first google was supposed to be python. > Indeed. D'oh. -- http://www.willmcgugan.com "".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in "jvyy*jvyyzpthtna^pbz") From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Fri Jun 24 07:42:39 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Fri, 24 Jun 2005 13:42:39 +0200 Subject: Sorting part of a list Message-ID: <3i29tfFjgph8U1@news.dfncis.de> Hello, I thought I understood list slices, but I don't. I want to sort only the last part of a list, preferably in place. If I do >>> ll = [3, 1, 4, 2] >>> ll[2:].sort() >>> ll [3, 1, 4, 2] ll isn't changed, because ll[2:] is a copy of the last part of the list, and this copy is sorted, not the original list. Right so far? But assignment to the slice: >>> ll[2:] = [2, 4] >>> ll [3, 1, 2, 4] _does_ change my original ll. What did I misunderstand? Thanks, Sibylle -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From p at ulmcnett.com Thu Jun 2 13:20:26 2005 From: p at ulmcnett.com (Paul McNett) Date: Thu, 02 Jun 2005 10:20:26 -0700 Subject: PYSH? (was:Re: calling ksh script from python) In-Reply-To: References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> Message-ID: <429F3FDA.3080402@ulmcnett.com> Cameron Laird wrote: > Infidel. While I sure feel that way about csh(1), it > surprises me you'd criticize ksh(1) so. 'Fact, 'mong > all the *sh-s, I *recommend* ksh for programming. May- > be the two of us see things differently. I keep wondering how difficult it would be to make a Python shell that exposes all of Python but also includes some builtin commands such as cd, mkdir, etc., that are just names bound to os.chdir, os.mkdir..., and is smart enough to take a given command from the user and try to do a os.system() on it based on the path. IOW, I'd love to have all of Python available as my unix shell, while still doing shell-type stuff such as traversing directories, launching applications, etc. There's likely a project that does this already that I'm just unaware of. -- Paul McNett http://paulmcnett.com From sjmachin at lexicon.net Tue Jun 21 22:42:07 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 22 Jun 2005 12:42:07 +1000 Subject: oddness in shelve module In-Reply-To: References: Message-ID: <42B8CFFF.5020101@lexicon.net> Michael P. Soulier wrote: > I'm trying to add objects to a shelve db object via hash assignment, but > I'm getting an odd exception. > > Traceback (most recent call last): > File "RemGui.py", line 117, in onMonitorButton > self.startMonitoring() > File "RemGui.py", line 163, in startMonitoring > self.monitor() > File "RemGui.py", line 181, in monitor > self.db.store_sample(dbentry) > File "C:\Documents and Settings\Michael Soulier\My > Documents\projects\rem\pysr > c\RemDBShelve.py", line 38, in store_sample > self.db[sample.timestamp] = sample > TypeError: object does not support item assignment > > The object itself is quite simple. > > I provide it below. AFAICT, wrong "it". The "item assignment" which is alleged not to be supported is of this form: an_object[some_key] = a_value I.e. "self.db" is the suspect, not "sample" From irmen.NOSPAM at xs4all.nl Mon Jun 13 21:11:08 2005 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 14 Jun 2005 03:11:08 +0200 Subject: Going crazy... In-Reply-To: <42ae2729$1@griseus.its.uu.se> References: <42ae2729$1@griseus.its.uu.se> Message-ID: <42ae2eaf$0$86164$e4fe514c@news.xs4all.nl> Jan Danielsson wrote: > Hello all, > > I'm 100% sure that I saw an example which looked something like this > recently: > > >>>>a=(1, 2, 3, 4, 5, 6) >>>>b=(2, 3, 6) >>>>a - b > > (1, 4, 5) > > The only new language I have been involved in lately is Python. Is my > memory failing me, or have I seen such an Python-example somewhere? If > so: Where; or more importantly: How does it work? > > I just tried typing the above in Python, and it - obviously - doesn't > work, so it must be some other syntax. Try sets: >>> a=set([1,2,3,4,5,6]) >>> b=set([2,3,6]) >>> a-b set([1, 4, 5]) >>> --Irmen From falcon3166 at hotmail.com Tue Jun 28 14:39:47 2005 From: falcon3166 at hotmail.com (Nathan Pinno) Date: Tue, 28 Jun 2005 12:39:47 -0600 Subject: I need help figuring out how to fix this code. Message-ID: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Hi all, I need help figuring out how to fix my code. I'm using Python 2.2.3, and it keeps telling me invalid syntax in the if name == "Nathan" line. Here is the code if you need it. #This program asks for a password, then asks for the user's name after the correct password has been supplied. The computers response will vary, # depending on the name inputted. print "Program Author: Nathan Pinno" print "ID# 2413448" print print "Program 3 - Loops and IF Conditions" print password = raw_input("Type in the password, please: ") while password != "hello": print "Incorrect password!" print "Welcome to the second half of the program!" name = raw_input("What is your name, please? ") if name == "Nathan": print "What a great name!" elif name == ["Madonna", "Cher"]: print "May I have your autograph please!" else print name,", that's a nice name!" What's wrong with the code? How do I fix it, so that it works? Thanks, Nathan Pinno http://www.npinnowebsite.ca/ -- ---------------------------------------------------------------- Posted via UsenetRevolution.com - Revolutionary Usenet ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** http://www.UsenetRevolution.com From donna at csquaredtech.com Sat Jun 4 15:03:03 2005 From: donna at csquaredtech.com (donna at csquaredtech.com) Date: Sat, 4 Jun 2005 12:03:03 -0700 (PDT) Subject: potluck for google meeting? In-Reply-To: <20050604183452.GA29448@panix.com> References: <20050604183452.GA29448@panix.com> Message-ID: <42728.10.5.1.104.1117911783.squirrel@mail.csquaredtech.com> I know that typically you all meet somewhere for dinner beforehand.. or afterhand.. but I'd like to propose we try a potluck at the meeting.. if google will allow it. I'm volunteering to coordinate the potluck for the july google meeting.. we can just see how it goes.. Best Regards, Donna M. Snow,Owner C Squared Technologies technology at the speed of innovation http://www.csquaredtech.com From http Wed Jun 1 17:01:24 2005 From: http (Paul Rubin) Date: 01 Jun 2005 14:01:24 -0700 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> Message-ID: <7xzmu94wrf.fsf@ruckus.brouhaha.com> "Thomas Bartkus" writes: > > Given that for the most part nobody in the Python community has a > > handle on any other Python person's paycheck, it's unlikely that > > enough of the community can be convinced that a VB-like > > development environment would be a "killer app" for Python and > > thus motivated to go produce one. > > Judging by the message traffic alluded to by the original poster, I'm hardly > the only one with this particular itch. AND there is clearly a substantial > development effort in this direction. Apparently, a few in the community are > convinced of the worth. Are we talking about a drag-and-drop GUI builder? What about Glade? Or do you mean a fancy IDE? There's a Python plug-in for Eclipse, but I haven't tried it yet. From rkern at ucsd.edu Wed Jun 1 04:14:58 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 01 Jun 2005 01:14:58 -0700 Subject: Software licenses and releasing Python programs for review In-Reply-To: <1117596415.792655.35320@o13g2000cwo.googlegroups.com> References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117324124.350474.136600@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <87ekbore1c.fsf@pobox.com> <1117596415.792655.35320@o13g2000cwo.googlegroups.com> Message-ID: poisondart wrote: [John J. Lee:] >>Secondly, do you think it's a bad thing for anybody to sell software >>that makes use of the *concepts* in your code (provided that the use >>of those concepts is not restricted by financial or other legal >>means)? If so, why? >> >>John > > To be honest. I'm not sure. The knowledge that I learnt was all given > to me freely, I just consolidated it into these programs. I feel that > it would be unfair that along this chain of knowledge passing, one > person decided to exploit the free system and harbour his knowledge for > profit. You can't copyright concepts and ideas. If someone wants to make commercial use of the knowledge, he can do so, and no license of yours can stop him. What you can copyright is your expression of that knowledge in code. So let's be a little clearer about exactly the actions that you can forbid: the redistribution of *your code*. Not the use of the knowledge contained therein. Your choice of license can't affect the issues you seem to be basing your decision on. As one academic to another, I am asking you to consider using an authentic Open Source license rather than one that forbids commercial redistribution (I don't think you've answered my question, yet, about whether you want to forbid commercial *use* as well, but I'm against that, too). You have every right to require that people redistributing your code to not profit thereby, but with an Open Source license, you have the opportunity to join a broader, more vibrant community. My experience with no-commercial-whatever academic projects is that they almost never develop a real community of code. The initial developer is the only developer, and the project languishes. Having a real Open Source license, especially one of the copyleft licenses like the GPL, encourages users to use the code, improve it, and gift the improvements back to the community. You end up with a community of people freely contributing their expertise to the world. That's a lot more than what you alone could provide. But you can get the process started. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Tue Jun 28 23:55:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 28 Jun 2005 23:55:47 -0400 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c3c3uipbjcg58@corp.supernews.com> Message-ID: Jarek Zgoda wrote: > Grant Edwards napisa?(a): > >>> To be blunt, I have no idea what this has to do with Python. >> >> >> Monty Python was mostly Brits? > > > Wasn't they all Brits? I think one was a lumberjack (but he's okay), which would make him a Canadian, eh? From joh12005 at yahoo.fr Thu Jun 30 02:19:50 2005 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 29 Jun 2005 23:19:50 -0700 Subject: multi regexp analyzer ? or how to do... Message-ID: <1120112390.387551.290770@z14g2000cwz.googlegroups.com> Hello, here is a trouble that i had, i would like to resolve it with python, even if i still have no clue on how to do it. i had many small "text" files, so to speed up processes on them, i used to copy them inside a huge one adding some king of xml separator : [content] content is tab separated data (columns) ; data are strings now here come the tricky part for me : i would like to be able to create some kind of matching rules, using regular expressions, rules should match data on one line (the smallest data unit for me) or a set of lines, say for example : if on this line , match first column against this regexp and match second column and on following line match third column -> trigger something so, here is how i had tried : - having all the rules, - build some kind of analyzer for each rule, - keep size of longest one L, - then read each line of the huge file one by one, - inside a "file", create all the subsets of length <= L - for each analyzer see if it matches any of the subsets - if it occurs... my trouble is here : "for each analyzer see if it matches any of the subset" it is really to slow, i had many many rules, and as it is "for loop inside for loop", and inside each rule also "for loop on subsets lines" i need to speed up that, have you any idea ? i am thinking of having "only rules for one line" and to keep traces of if a rule is a "ending one" (to trigger something) , or a "must continue" , but is still unclear to me for now... a great thing could also have been some sort of dict with regexp keys... (and actually it would be great if i could also use some kind of regexp operator to tell one can skip the content of 0 to n lines before matching, just as if in the example i had changed "following..." by "skip at least 2 lines and match third column on next line - it would be great, but i still have really no idea on how to even think about that) great thx to anybody who could help, best From tom at dtsam.com Wed Jun 1 17:00:05 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 1 Jun 2005 16:00:05 -0500 Subject: anygui,anydb, any opinions? References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> Message-ID: "Skip Montanaro" wrote in message news:mailman.347.1117656834.18027.python-list at python.org... > > Thomas> The Python world lacks the phenomenally successful development > Thomas> models enjoyed by the now ancient Turbo Pascal, Delphi and > Thomas> Visual Basic. > Thomas> AND > Thomas> If the likes of Visual Basic can have it, then it becomes > Thomas> really, *really* hard to convince the world that Python is a > Thomas> serious, professional system. > > Remember, in the open source community we all pretty much just scratch our > itches. I haven't forgotten! > Given that for the most part nobody in the Python community has a > handle on any other Python person's paycheck, it's unlikely that enough of > the community can be convinced that a VB-like development environment would > be a "killer app" for Python and thus motivated to go produce one. Judging by the message traffic alluded to by the original poster, I'm hardly the only one with this particular itch. AND there is clearly a substantial development effort in this direction. Apparently, a few in the community are convinced of the worth. I think we need to get over this "killer app" jazz. How about plain old productivity? How do we enjoy the rapid and effective algorithm production that Python affords us if one must pay back that productivity on an effective and tediously acquired user interface. I rather think reducing the code needed to produce a useful user interface frees up considerable effort better spent on the programming problems we use Python for. > Apparently, most Python people feel productive enough without such a tool. As did many with Fortran. Or Cobol. Are we now so productive that there is no longer an unmet need for new/better software? Do we stop here? Is Python a comfortable place for the Luddites hang out. I think not. Thomas Bartkus From d at e.f Mon Jun 13 22:53:19 2005 From: d at e.f (D H) Date: Mon, 13 Jun 2005 21:53:19 -0500 Subject: What is different with Python ? In-Reply-To: References: Message-ID: <9IKdncvD4f4_2zPfRVn-gg@comcast.com> Philippe C. Martin wrote: > Yet for the first time I get (most) of my questions answered by a language I > did not know 1 year ago. ^^^^^^^^^^ You're in the Python honeymoon stage. From kaka.hui at gmail.com Wed Jun 22 16:18:49 2005 From: kaka.hui at gmail.com (Cathy Hui) Date: 22 Jun 2005 13:18:49 -0700 Subject: Installing MySQL-Python In-Reply-To: References: <1119402324.019970.42590@g43g2000cwa.googlegroups.com> Message-ID: <1119471529.214471.178930@g47g2000cwa.googlegroups.com> but the gcc was installed on this system tho: gcc -v Reading specs from /export/home/local/bin/../lib/gcc/sparc-sun-solaris2.8/3.4.2/specs Configured with: ../configure --with-as=/usr/ccs/bin/as --with-ld=/usr/ccs/bin/ld --disable-nls Thread model: posix gcc version 3.4.2 From peter at engcorp.com Tue Jun 21 10:53:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Jun 2005 10:53:35 -0400 Subject: Python choice of database In-Reply-To: References: Message-ID: GMane Python wrote: > For my database, I have a table of user information with a unique > identifier, and then I save to the filesystem my bitmap files, placing the > unique identifier, date and time information into the filename. Why stick a > photo into a database? There are various possible reasons, depending on one's specific situation. A database allows you to store the date and time info, or other attributes, as separate fields so you can use standard SQL (or whatever your favourite DB supports) to sort, query, and retrieve. A database makes it possible to update or remove the photo in the same manner you use to access all your other data, rather than requiring you to deal with filesystem ideosyncracies and exceptional conditions. A database such as SQLite will store *all* your data in a single file, making it much easier to copy for archival purposes, to send to someone else, or to move to another machine. > Then save the bitmap with filename: > 0001_13:00:00_06-21-2005.bmp A database shouldn't make you jump through hoops to create "interesting" file names just to store your data. :-) > To make things faster, I also have a table of filenames saved, so I can know > exactly which files I want to read in. Oh yeah, databases can have indexes (or indices, if you will) which let you get that sort of speedup without having to resort to still more custom programming. :-) Not that a database is always the best way to store an image (or to do anything else, for that matter), but there are definitely times when it can be a better approach than simple files. (There are disadvantages too, of course, such as making it harder to "get at" the data from outside the application which created it. In the case of bitmaps, this might well be a deciding factor, but each case should be addressed on its own merits.) -Peter From tim.peters at gmail.com Tue Jun 14 15:57:49 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 14 Jun 2005 15:57:49 -0400 Subject: Thread priorities? In-Reply-To: <20050614150948.752489.8bacee83@goombah.com> References: <20050614150948.752489.8bacee83@goombah.com> Message-ID: <1f7befae05061412576d857fe5@mail.gmail.com> [Gary Robinson] > In the application we're writing (http://www.goombah.com) it would be > helpful for us to give one thread a higher priority than the others. We > tried the recipe here: > http://groups-beta.google.com/group/comp.lang.python/msg/6f0e118227a5f5de > and it didn't seem to work for us. If you need to fiddle thread priorities, then you'll need to do such platform-specific things, and fight with the OS documentation to figure out when and why they don't seem to work. > We don't need many priority levels. We just need one thread to > *temporarily* have a higher priority than others. > > One thing that occurred to me: There wouldn't by any chance be some way > a thread could grab the GIL and not let it go until it is ready to do > so explicitly? No, unless that thread is running in a C extension and never calls back into Python until it's willing to yield. > That would have the potential to solve our problem. > > Or maybe there's another way to temporarily let one thread have > priority over all the others? No way in Python, although specific platforms may claim to support relevant gimmicks in their native threads (and Python threads generally are native platform threads). A portable approach needs to rely on thread features Python supports on all platforms. For example, maybe this crude approach is good enough: """ import threading class Influencer(object): def __init__(self): self.mut = threading.Lock() self.proceed = threading.Event() self.proceed.set() self.active = None def grab(self): self.mut.acquire() self.active = threading.currentThread() self.proceed.clear() self.mut.release() def release(self): self.mut.acquire() self.active = None self.proceed.set() self.mut.release() def maybe_wait(self): if (self.proceed.isSet() or self.active is threading.currentThread()): pass else: self.proceed.wait() """ The idea is that all threads see an (shared) instance of Influencer, and call its .maybe_wait() method from time to time. Normally that doesn't do anything. If a thread T gets it into its head that it's more important than other threads, it calls .grab(), which returns at once. Other threads then block at their next call to .maybe_wait(), until (if ever) some thread calls .release(). Season to taste; e.g., maybe other threads are willing to pause no more than 0.1 second; etc. From grante at visi.com Tue Jun 28 16:18:06 2005 From: grante at visi.com (Grant Edwards) Date: Tue, 28 Jun 2005 20:18:06 -0000 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> Message-ID: <11c3c3uipbjcg58@corp.supernews.com> On 2005-06-28, Michael Hoffman wrote: > muldoon wrote: >> Americans consider having a "British accent" a sign of sophistication >> and high intelligence. Many companies hire salespersons from Britain to >> represent their products,etc. Question: When the British hear an >> "American accent," does it sound unsophisticated and dumb? >> >> Be blunt. We Americans need to know. > > To be blunt, I have no idea what this has to do with Python. Monty Python was mostly Brits? > Surely selecting the right forum to use indicates more > sophistication and high intelligence than the way one speaks. > ;-) Well, there is that... -- Grant Edwards grante Yow! Hello... IRON at CURTAIN? Send over a visi.com SAUSAGE PIZZA! World War III? No thanks! From steve at REMOVETHIScyber.com.au Sun Jun 12 05:26:02 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 12 Jun 2005 19:26:02 +1000 Subject: case/switch statement? References: Message-ID: On Sat, 11 Jun 2005 19:47:58 -0500, Skip Montanaro wrote: > If the case values are constants known to the compiler, it can generate O(1) > code to take the correct branch. (In fact, that could be done by the > compiler for if statements such as in your example today. It just isn't.) > It is precisely this behavior that is desired in many situations. See PEP > 275 for details: Agreed. I certainly don't object to sensible optimizations! But the number of if...elif statements which can be optimised are a vanishingly small subset of the number of possible if...elif statements. And you can bet your last dollar that many people will use case statements even when doing so gives no advantage, in a mistaken opinion that it will be somehow magically faster. In fact, some languages even encourage this: I recall the old 4GL (back in the early 1990s when developers actually used the term Fourth Generation Language unselfconsciously) used to develop the spreadsheet "Wingz". It included two different forms for case. By memory: case EXPR of: VALUE: SUITE VALUE: SUITE otherwise: SUITE (which could potentially be optimised) and a second form: case: EXPR of: SUITE EXPR of: SUITE otherwise: SUITE which was almost certainly nothing more than syntactic sugar for: if EXPR then: SUITE else if EXPR then: SUITE else: SUITE In any case, even when case statements can be optimized (and we all know the lesson about premature optimization), the original poster's complaint appeared to be purely a stylistic issue: he didn't relish using long if..elif statements. Who does? Not I. My comment, I hope, will remind folks that long pieces of branching code are ugly regardless of which syntax you use. -- Steven. From ods at strana.ru Tue Jun 14 05:20:27 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 14 Jun 2005 13:20:27 +0400 Subject: translating C++ exceptions to python In-Reply-To: <1118661783.702138.128880@g49g2000cwa.googlegroups.com> References: <1118661783.702138.128880@g49g2000cwa.googlegroups.com> Message-ID: <20050614132027.5629d6ab@ods.pravda.rfn.ru> On 13 Jun 2005 04:23:03 -0700 calin.hanchevici at gmail.com wrote: > Hi all, > > I have a C++ library I call from python. The problem is I have c++ > exceptions that i want to be translated to python. I want to be able to > do stuff like: > try: > my_cpp_function() > except cpp_exception_1: > do_stuff > except cpp_exception_2: > do_other_stuff > > any ideas how can i do the translation? 1. Create Python class for your exception. For simple case the code will be: static PyObject *YouExceptionClass; # and in module initialization function: YouExceptionClass = PyErr_NewException("YourModule.YourException", 0, 0); 2. Add it to module dictionary. 3. In wrapper for my_cpp_function use something like the following code: try { my_cpp_function_impl(); } catch (YouException &exc) { PyErr_SetString(YouExceptionClass, exc.what()); return 0; } -- Denis S. Otkidach http://www.python.ru/ [ru] From sjmachin at lexicon.net Thu Jun 2 22:19:12 2005 From: sjmachin at lexicon.net (John Machin) Date: Fri, 03 Jun 2005 12:19:12 +1000 Subject: optparse.py: FutureWarning error In-Reply-To: References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> Message-ID: <429FBE20.8020608@lexicon.net> Michael Hoffman wrote: > Terry Reedy wrote: > >> c) Check to see if Python has a startup option for suppressing warnings >> >> As to c) python -h gives a list indicating what I thought, that -W >> controls warnings, but gives insufficient info for me to use it, and I >> didn't find any more in the docs. I hope someone else chimes in. > > > man python. Search for -W. """ C:\junk>man python 'man' is not recognized as an internal or external command, operable program or batch file. """ Could someone please post a copy of the whole of the arg section of the "man python" output, for the benefit of Windows users? TIA, John From fperez.net at gmail.com Wed Jun 8 11:31:11 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 08 Jun 2005 09:31:11 -0600 Subject: Writing func_closure? References: Message-ID: Michael Hoffman wrote: > Fernando Perez wrote: > > > I am trying to do a run-time modification of a function's closure, > > where I want to modify the value of one of the variables in the closure. > > Out of curiosity, why? Oh, I was just trying to play a little trick inside a tight loop where I would modify on the fly the function's closure to change a parameter. I can do it in a million ways, but at creation time, the closure approach provides the cleanest syntax. But at runtime, I have an algorithm that needs to modify certain parameters many times, and the least-expensive way would be to be able to write directly into the closure. > Closer inspection of the docs > reveals that it is not writable after all. Therefore the only way I can Ah, the docs have improved. I'm using 2.3.4, and the same page: http://www.python.org/doc/2.3.4/ref/types.html only says: Of these, func_code, func_defaults, func_doc/__doc__, and func_dict/__dict__ may be writable; the others can never be changed. That's what led me to believe it could be done. Thanks for pointing me to the 2.4 docs, which are much less ambiguous. > see to do it without writing an extension is to generate some dummy > function and copy the func_closure attribute from it. Luckily, you have > already produced a factory for such a function: Yes, I knew of the new.function() approach, but the problem is that I don't know how to make a fresh closure for it. I can reuse the closure from a different function, but the docs don't say how to make a valid closure tuple. This is the typical problem of the stdlib docs, which under-specify what is supposed to go into a call and don't give at least a specific example. Many thanks though, I'll probably end up using a less dirty hack :) Cheers, f From simon.brunning at gmail.com Wed Jun 8 10:03:06 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 8 Jun 2005 15:03:06 +0100 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: <1118238280.678863.211490@g44g2000cwa.googlegroups.com> References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Message-ID: <8c7f10c6050608070399c4681@mail.gmail.com> On 8 Jun 2005 06:44:40 -0700, ajikoe at gmail.com wrote: > It means in windows we should use 'wb' to write and 'rb' to read ? > Am I right? It depends what you are trying to do with the file. If you are processing it as a text file, open it as a text file, and all will be well: my_file = open('my_file.txt') for line in my_file: # whatever... -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From n.20.e5ke at spamgourmet.com Thu Jun 23 00:18:47 2005 From: n.20.e5ke at spamgourmet.com (Esben Pedersen) Date: Thu, 23 Jun 2005 06:18:47 +0200 Subject: Does a function like isset() exist in Python? In-Reply-To: References: Message-ID: <42ba3892$0$18647$14726298@news.sunsite.dk> Patrick Fitzsimmons wrote: > Hi, > > I'm sure I should know this, but I can't find it in the manual. > > Is there a function in Python like the function in PHP isset()? It > should take a variable name and return True or False depending on > whether the variable is initialized. > > Thanks for any help, > Patrick try: doDomething(myVar) except NameError: print "myVar is not set" /Esben From nyamatongwe+thunder at gmail.com Thu Jun 23 20:38:49 2005 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 24 Jun 2005 00:38:49 GMT Subject: List of all installed applications (XP)? In-Reply-To: References: Message-ID: Not only is it difficult to tell which applications are installed, it is difficult to tell if an application is still installed as all too many applications do not remove all their registry keys upon uninstall. I was going to suggest using a commercial application due to the messiness of this problem but the one I tried "Tally Systems WebCensus" (now owned by Novell) failed to find NuMega BoundsChecker and it also believes Yahoo Messenger is still installed even though it was uninstalled. Neil From agriff at tin.it Fri Jun 17 17:37:28 2005 From: agriff at tin.it (Andrea Griffini) Date: Fri, 17 Jun 2005 21:37:28 GMT Subject: What is different with Python ? References: <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> <38s4b1hjs19lgoa8d8trht0m24i67j3a0g@4ax.com> <1118996729.063669.66530@g44g2000cwa.googlegroups.com> <1119011425.405165.186960@g44g2000cwa.googlegroups.com> Message-ID: On 17 Jun 2005 05:30:25 -0700, "Michele Simionato" wrote: >I fail to see the relationship between your reply and my original >message. >I was complaining about the illusion that in the old time people were >more >interested in programming than now. Instead your reply is about low >level >languages being more suitable for beginners than high level languages. >I don't see the connection. I've been told in the past that one reason for which is good to start from high-level languages is that you can do more with less. In other words I've been told that showing a nice image and may be some music is more interesting than just making a led blinking. But if this is not the case (because just 1% is interested in those things no matter what) then why starting from high level first then ? I would say (indeed I would *hope*) that 1% is a low estimate, but probably I'm wrong as others with more experience than me in teaching agree with you. Having more experience than me in teaching programming is a very easy shot... I never taught anyone excluding myself. About the 1%, I've two brothers, and one of them got hooked to programming before me... the other never got interested in computers and now he's just a basic (no macros) ms office user. So in my case it was about 66%, and all started with a programmable pocket RPN calculator ... but there were no teachers involved; may be this is a big difference. Andrea From dh47302 at yahoo.com Thu Jun 2 03:59:30 2005 From: dh47302 at yahoo.com (Klaus Alexander Seistrup) Date: Thu, 2 Jun 2005 07:59:30 +0000 (UTC) Subject: where to find the doc about python regular expression? References: Message-ID: ???????? wrote: > thanks Did you try Google: First hit is: -- Klaus Alexander Seistrup Magnetic Ink, Copenhagen, Denmark http://magnetic-ink.dk/ From tjreedy at udel.edu Sun Jun 5 23:27:02 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 5 Jun 2005 23:27:02 -0400 Subject: Destructive Windows Script References: Message-ID: "Chris Lambacher" wrote in message news:af37e9c5050605181211ac575b at mail.gmail.com... > The reason they are slow and tedious is that they need to write to > every byte on the disk. Depending on the size of the disk, there may > be a lot of data that needs to be written, and if they are older > computers, write speed may not be particularly fast. I would expect programs called killdisk, autoclave, etc to not only write every byte multiple times, but to also work at the lowest level to try to manipulate track alignment to wipe out any residual signals off the current tracks. That is *really* slow. (Note: the ultimate security is to shread or incenerate the disk platters. I believe this is now standard practice in super security areas.) OP: if you merely want to wipe the data enough to protect against a casual user, using casual access thru normal open and read, and not the FBI disk forensics/recovery lab (;-), one write would be enough. On *nix, one could open '/dev/rawdisk' (actual name depends on the *nix build) and write a tracks worth of garbage for as many tracks as there are. I don't how to programmaticly get the track size and number (if there is a standard way at all). For Windows, you would need the appropriate low-level system call, but I have no idea what it is or if it is the same for different versions. Same for other non *nix systems. Terry J. Reedy From deets at web.de Fri Jun 10 10:55:12 2005 From: deets at web.de (Diez B. Roggisch) Date: Fri, 10 Jun 2005 16:55:12 +0200 Subject: about accessing mysql In-Reply-To: References: Message-ID: sinan , wrote: > hi everybody, i have a small mysql connection code > > >>>>import MySQLdb >>>>db=MySQLdb.Connection(host="localhost",user="root",db="nux") > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/site-packages/MySQLdb/__init__.py", line > 66, in Connect > return Connection(*args, **kwargs) > File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line > 156, in __init__ > self.autocommit(0) > _mysql_exceptions.OperationalError: (1193, "Unknown system variable > 'AUTOCOMMIT'") > > > these command works at my computer but when i want to do in my server, > i get these messages as you seen, my both computer and server have > same python, same MySQLdb module and same database with same > priviliges.also how can i connect to remote database? is that work ? > db=MySQLdb.Connection(host="192.168.0.120",user="root",db="nux") > thank you. Are you aware that transactions are a very recent feature of mysql and that tables have to be created as InnoDB tables? I don't know much about that stuff but can imagine that on your server this has not been done properly. Diez From grahamd at dscpl.com.au Wed Jun 22 00:44:25 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 21 Jun 2005 21:44:25 -0700 Subject: need help with mod_python in RH 9 In-Reply-To: References: Message-ID: <1119415465.647652.221790@g47g2000cwa.googlegroups.com> Read: http://www.dscpl.com.au/projects/vampire/articles/modpython-001.html It addresses the more common problems and how to sort out what you may not have done right. Anyway, I don't seem to see any problems with what you have said you have done, so work through the referenced document. Especially look through the Apache logs as described to ensure that Apache has been restarted and mod_python loaded correctly. Graham From listserver at tdw.net Fri Jun 17 07:09:02 2005 From: listserver at tdw.net (Tim Williams) Date: Fri, 17 Jun 2005 12:09:02 +0100 Subject: Python & firewall control (Win32) Message-ID: <001c01c5732c$f851c1b0$ccbefea9@twilliams> On Thu, 16 Jun 2005, Tim Williams wrote: > Does anyone know of (personal/desktop) firewall that can be controlled > via Python, or a Python Firewall package, or even something like DAXFi > but not dormant ? http://wipfw.sourceforge.net/ import os def deny(src, dst, proto="all"): cmd = "ipfw add deny " + proto + " from " + src + " to " + dst os.system(cmd) ipfw for Windows is technically in beta, but ipfw itself is rock solid. tom ------------------------------ Tom, many thanks for that. I'm actually looking for a firewall (packet filter) I can control in realtime from a Python application, or even a Win32 equivalent of http://woozle.org/~neale/src/ipqueue/ . Though if I can stop & restart ipfw in a fraction of a second from within a Python app then the result would be the same I guess. I will have a play with it. Any other suggestions gratefully received too Cheers Tim From grante at visi.com Sat Jun 18 10:46:19 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 18 Jun 2005 14:46:19 -0000 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> Message-ID: <11b8ctrtmuo6g03@corp.supernews.com> On 2005-06-18, cpunerd4 wrote: > what I mean by secure is that no one can steal the code. Distributing bytecode (Java or Python) vs. source only makes little difference if your code is really worth stealing. Distributing compiled C code will make it a little more difficult, but if somebody wants to reverse engineer it, they can. > I want to create comercial applications eventually. Most commercial applications are "stolen" simply by copying the executable. -- Grant Edwards grante Yow! Either CONFESS now or at we go to "PEOPLE'S COURT"!! visi.com From mrmaple at gmail.com Thu Jun 16 10:05:28 2005 From: mrmaple at gmail.com (James Carroll) Date: Thu, 16 Jun 2005 10:05:28 -0400 Subject: dynamic In-Reply-To: <1118899468.786811.326800@g43g2000cwa.googlegroups.com> References: <1118830327.255757.262200@g47g2000cwa.googlegroups.com> <1118899468.786811.326800@g43g2000cwa.googlegroups.com> Message-ID: Oh, I see. Yeah, having the code look like you're instantiating one class, but really getting a different one is really horrible. Sorry I didn't catch on to the subtlety. I'm always complaining about code that looks like it does one thing, but really does another. -Jim On 15 Jun 2005 22:24:28 -0700, Michele Simionato wrote: > I think using __new__ when a plain old factory method would > work is horrible. But I am not saying that there no use cases for > __new__. I used it once, when I wanted a class working > for the final user as a factory function. I just wrote the class in > lower case and gave it a custom __new__ method. > > Michele Simionato > > -- > http://mail.python.org/mailman/listinfo/python-list > > From jabel at plus.net Tue Jun 28 11:34:09 2005 From: jabel at plus.net (John Abel) Date: Tue, 28 Jun 2005 16:34:09 +0100 Subject: building python 2.4.1 In-Reply-To: References: Message-ID: <42C16DF1.1020909@plus.net> Andreas Heiss wrote: >Hi ! >I am trying to build python 2.4.1 from source on a Linux system. >Everything seems fine, but tkinter seems not to work. >The file _tkinter.pyd is missing. >How can tell configure to build all necessary components ? > >Thanks >Andreas > > It looks to like Tcl/Tk is not installed on your system. You will need to have them installed for Tkinter to build. HTH J From rbt at athop1.ath.vt.edu Sun Jun 5 17:22:50 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 05 Jun 2005 17:22:50 -0400 Subject: mix up a string In-Reply-To: <3gh7k3Fce4qdU1@individual.net> References: <3gh7k3Fce4qdU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > rbt wrote: > >>What's the best way to take a string such as 'dog' and mix it up? You >>know, like the word jumble in the papers? ODG. I thought something like >>mix = random.shuffle('dog') would do it, but it won't. Any tips? > > > py> def shuffled(s): > ... l = list(s) > ... random.shuffle(l) > ... return ''.join(l) > > > Reinhold Thanks guys, this works great. I forgot that shuffle needs a sequence... duh ;) From peter at engcorp.com Sat Jun 18 20:55:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 20:55:33 -0400 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: Message-ID: <7rOdnWGkN-wFXynfRVn-tQ@powergate.ca> Bo Peng wrote: > I need to pass a bunch of parameters conditionally. In C/C++, I can do > func(cond1?a:b,cond2?c:d,.....) > > Is there an easier way to do this in Python? Please read the FAQ to learn the answer and much other useful information. In this case, the specific entry follows, but you'd do well to read all the entries: http://www.python.org/doc/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator -Peter From seefeld at sympatico.ca Fri Jun 17 16:36:07 2005 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Fri, 17 Jun 2005 16:36:07 -0400 Subject: Embedding Python In-Reply-To: <1119020326.409233.89120@g44g2000cwa.googlegroups.com> References: <1119020326.409233.89120@g44g2000cwa.googlegroups.com> Message-ID: S?bastien Boisg?rault wrote: > Hi, > > Imagine that you have a PyObject pointer 'object' > pointing to a Python integer ... let's say 42. > > How would do you attach the variable "answer" to > it so that the code > > PyRun_SimpleString("print answer"); > > works as expected ? > > My current solution is: > > __main__ = PyImport_ImportModule("__main__"); > PyObject_SetAttrString(__main__, "answer", object); > > Anything better ? You could use PyRun_String instead, which lets you pass global and local dictionaries as context. That may provide more fine-grained control, depending on what you want. Regards, Stefan From kasimov at i.com.ua Tue Jun 7 14:10:14 2005 From: kasimov at i.com.ua (Maksim Kasimov) Date: Tue, 07 Jun 2005 21:10:14 +0300 Subject: different time tuple format Message-ID: hi all, sorry if i'm reposting why time.strptime and time.localtime returns tuple with different DST (9 item of the tuple)? is there some of setting to fix the problem? Python 2.2.3 (#1, May 31 2005, 11:33:52) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.strptime("2005-06-07 21:00:00", "%Y-%m-%d %H:%M:%S") (2005, 6, 7, 21, 0, 0, 6, 1, 0) >>> time.localtime() (2005, 6, 7, 21, 2, 39, 1, 158, 1) >>> -- Best regards, Maksim Kasimov mailto: kasimov at i.com.ua From pdemb at gazeta.pl Sun Jun 12 17:39:19 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 12 Jun 2005 23:39:19 +0200 Subject: How to get/set class attributes in Python References: <42ac6b5b$0$27173$626a14ce@news.free.fr> <87k6kzgznf.fsf@hector.domek> Message-ID: <87is0jfe60.fsf@hector.domek> Chris Spencer writes: > Peter Dembinski wrote: >> Bruno Desthuilliers writes: >> >>> Nope. Python *is* typed. But it doesnt confuse implementation with >>> semantic. >> Python is typed. And its type system may look strange for anyone >> who did only Java or C++ programming before :> > > Of course, in that Python is dynamically typed as opposed to the > static typing of Java or C++. Please excuse my previous mis-wording :) Mis-wording? From jstroud at mbi.ucla.edu Sat Jun 25 21:44:12 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 25 Jun 2005 18:44:12 -0700 Subject: Favorite non-python language trick? In-Reply-To: References: Message-ID: <200506251844.12393.jstroud@mbi.ucla.edu> On Saturday 25 June 2005 11:08 am, Steven D'Aprano wrote: > The problem is, you have made colour (returning to English spelling > instead of foreign) into a class. If you need two colour variables, you > have to duplicate the code for the class (perhaps only changing the > numeric constants. You can't even make instances from the class, because > they all share the same RGB values, which is pretty useless if they are > meant to represent different colours. py> class color: ... pass ... py> def with(classname, **kwargs): ... classname.__dict__.update(kwargs) ... py> with(color, red=0, ... blue=255, ... green=255) py> py> color.blue 255 Is this what you want to do? > > Also avoids those stupid little colons. > > Using := and = for assignment and equality is precisely as stupid as using > = and == for assignment and equality. Perhaps less stupid: why do we use > == for equals, but not ++ for plus and -- for minus? The colons are to make it look more official or something. They are useless and hence stupid. The two equals signs for comparison could be argued to be redundant, but the colons are absolutely unecessary. I thought they were pointless 18 years ago when I learned pascal in highschool and after 20 years, I still think they are still pointless. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From gsakkis at rutgers.edu Fri Jun 10 21:31:46 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 10 Jun 2005 18:31:46 -0700 Subject: Structure function References: <1118451411.399121.275110@f14g2000cwb.googlegroups.com> Message-ID: <1118453506.202577.147590@g14g2000cwa.googlegroups.com> > Hello, > > Does anyone have an efficient Python routine for calculating the > structure function? > > > Thanks very much, > > > Daran > daranrifeNOS at PAMyahoo.com Read this first and come back: http://www.catb.org/~esr/faqs/smart-questions.html#beprecise George From gsakkis at rutgers.edu Sun Jun 12 11:06:18 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 12 Jun 2005 08:06:18 -0700 Subject: unittest: collecting tests from many modules? References: Message-ID: <1118588778.234523.112910@g14g2000cwa.googlegroups.com> "Jorgen Grahn" wrote: > I have a set of tests in different modules: test_foo.py, test_bar.py and so > on. All of these use the simplest possible internal layout: a number of > classes containing test*() methods, and the good old lines at the end: > > if __name__ == "__main__": > unittest.main() > > This is great, because each of the modules are runnable, and I can select > classes or tests to run on the commandline if I want to. However, running > all the tests from e.g. a Makefile is not that fun; I don't get a single > pass/fail summary across the modules. > > What's the best way of creating a test.py which > - aggregates the tests from all the test_*.py modules? > - doesn't require me to enumerate all the test classes in test.py > (forcing each module to define test_foo.theSuite or someting would > be OK though) > - retains the ability to select tests and verbosity (-q, -v) from the > command line? > > Something like: > > import unittest > import test_foo > import test_bar > > if __name__ == "__main__": > unittest.main(modules = ['test_foo', > 'test_bar']) > > Seems to me this should be possible, since all the logic for doing it /is/ > there for the local module; I'd assume there would be a way to make unittest > search additional modules for test classes. But my head starts spinning > when I read the source code ... I had written a script to do something close to this; currently it doesn't do any kind of aggregation, but it should be easy to extend it as you like. What I don't like is the way it currently works: it replaces sys.modules['__main__'] for each unit test and then it execfile()s it, which seems like a hack. I didn't look into unittest's internals in case there is a more elegant way around this; if there isn't, a future version of unittest should address the automatic aggregation of tests, as py.test does already. The link to the script is http://rafb.net/paste/results/V0y16g97.html. Hope this helps, George From desertgarden at netscape.com Wed Jun 29 13:01:32 2005 From: desertgarden at netscape.com (Brian) Date: Wed, 29 Jun 2005 17:01:32 GMT Subject: I need help figuring out how to fix this code. In-Reply-To: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: Hi Nathan, Please see my comments listed below. Nathan Pinno wrote: > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" At this point, you need to add the following statement again: password = raw_input("Type in the password, please: ") Otherwise, it just keeps stating "Incorrect password!" forever without giving the user the ability to re-enter another password attemp / try. > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" Remove the tab indentions in front of the "if", "elif", and "else" statements. This will cause an error in your program. The only time that you need to indent is the code following the if statements. if name == "Steven": print "Then I indent this code here." else: print "This is another coded statement here." > Thanks, > Nathan Pinno You're welcome, Nathan! Hope this helps (HTH), Brian --- From cam.ac.uk at mh391.invalid Wed Jun 29 04:29:09 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 29 Jun 2005 09:29:09 +0100 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: Peter Hansen wrote: > Elmo M?ntynen wrote: > >> Maybe funny, but a bit too cocky for my taste. Robert kern is propably >> right about what he really meant so don't be too hasty in the future, >> right?). > > Elmo, it's probably neither cocky nor funny, but before you pass > judgment you should Google this group for "time machine" and read > awhile. (I was merely attempting to parrot a traditional response that > is given around here when someone asks for something which is already > present in the language.) > > And whether I misinterpreted the (ambiguous) question or not, my > response provides the required information to put together a solution to > the OP's question. It would just require one extra level of > indirection, so to speak, to do what Robert suggests he might have wanted. I didn't understand the original question either until Robert Kern guessed what the OP was talking about. -- Michael Hoffman From gdamjan at gmail.com Wed Jun 22 09:34:00 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 22 Jun 2005 15:34:00 +0200 Subject: importing a package References: Message-ID: <42b968a8_1@x-privat.org> > I developed a package with a structure like this > src/ > tesfile.py > dir1/ > __init__.py > file1.py > dir2/ > __init__.py > file2.py Importing dir2/file2 from dir1/file1.py works here, because when yuo started the testfile script the src/ directory was added to the sys.path list. If you relocate dir1/ and dir2/ in a "package" directory here it will not work. -- damjan From andrewu1 at heller.co.nz Mon Jun 27 02:11:18 2005 From: andrewu1 at heller.co.nz (Andrew Gordon) Date: Mon, 27 Jun 2005 18:11:18 +1200 Subject: Using MSMQ on Windows (and Navision) Message-ID: I'm investigating getting Microsoft Navision to do stuff from a Python script. The recommended way seems to be to use message queues (MSMQ). I can get Navision to send a message to itself fine. I found a couple of code example in an ancient message in this newsgroup. The send.py one I changed to the following: from win32com.client import gencache msmq = gencache.EnsureModule('{D7D6E071-DCCD-11D0-AA4B-0060970DEBAE}', 0, 1, 0) qi = msmq.MSMQQueueInfo() qi.PathName = ".\\testqueue" try: myq = qi.Open(msmq.constants.MQ_SEND_ACCESS,0) except: qi.Create() myq = qi.Open(msmq.constants.MQ_SEND_ACCESS,0) if myq.IsOpen: msg = msmq.MSMQMessage() msg.Priority = 3 msg.Body = "Hello World!" msg.Label = "Navision MSMQ-BA" print len(msg.Body) print msg.BodyLength msg.Send(myq) myq.Close() -------------------- And the read one all I changed was the queue name. # read.py - reads from the queue # following bit generated via "makepy -i" ... # Use these commands in Python code to auto generate .py support from win32com.client import gencache msmq = gencache.EnsureModule('{D7D6E071-DCCD-11D0-AA4B-0060970DEBAE}', 0, 1, 0) qi = msmq.MSMQQueueInfo() qi.PathName = ".\PyQueueX" myq = qi.Open(msmq.constants.MQ_RECEIVE_ACCESS,0) if myq.IsOpen: msg = myq.Receive() print " body: %s" % msg.Body print "label: %s" % msg.Label myq.Close() --------------------- They can send messages to each other fine. The read.py can receive messages from Navision fine. But messages sent to Navision (after changing the msg.Label to "Navision MSMQ-BA") show up as empty messages (nothing in the body). I can only see two differences between messages generated from Navision and messages generated send.py. 1) Messages from Navision have something in the "Administration" bit when you look at the message's properties in computer management (Format name: PUBLIC=2bc802b2-7778-42c1-bc30-28caca20d974, Name: it2-new\nsadminreceivequeue). Where as ones from send.py don't. 2) Every character in the body of messages sent from send.py has a 0 value character after them (ie in hex 48 00 65 00 6C 00 6C 00 6F 00 20 00 57 00 00 6F 00 72 00 6C 00 64 00 21 00) Adding a print msg.BodyLength just before the msg.Send(myq) yields 24 for a 12 character message. I'm assuming it is 2), coz it's just weird (unicode?). Any ideas? From exogen at gmail.com Tue Jun 21 10:17:52 2005 From: exogen at gmail.com (Brian Beck) Date: 21 Jun 2005 07:17:52 -0700 Subject: How do I access avariable named "return"? In-Reply-To: References: Message-ID: <1119363472.631871.173590@g47g2000cwa.googlegroups.com> > I think this seems to be a problem due to the use of a forbidden word. But I > have no chance to change the WSDL definition, so: How can I get the > variable resp.return? Any suggestions? To get it: getattr(resp, 'return') To set it: setattr(resp, 'return', value) -- Brian Beck Adventurer of the First Order From noreply at gcgroup.net Wed Jun 29 10:04:45 2005 From: noreply at gcgroup.net (William Gill) Date: Wed, 29 Jun 2005 14:04:45 GMT Subject: tkinter radiobutton In-Reply-To: References: <1ygwe.532$Ox3.193@newssvr12.news.prodigy.com> Message-ID: <1Uxwe.901$Ox3.326@newssvr12.news.prodigy.com> I did some more digging based on your code, and discovered list comprehensions. They didn't register the first time I skimmed the language reference and tutorial. It's obvious the more I learn, the more I need to relearn what I think I know. I need to study comprehensions, but they open up lots of opportunities for simpler, clearer code. >> return row == var.get() Oops! I saw this as soon as I sent it, but knew you would get my point. > var.set(-1) Though both ways may seem roughly equivalent today, I'd bet that in 6 months ... var.set(-1) # initialize as no choice ... will be clearer. Thanks again! Bill Peter Otten wrote: > William Gill wrote: > > >>Also, does 'row == var.get() for var in self.variables' perform the >>comparison row == var.get() for each item in self.variables? I would >>have had to write: >> >>for var in self.variables: >> return row == var.get() > > > Or rather > > result = [] > for var in self.variables: > result.append(row == var.get()) > return tuple(result) > > This can be rewritten to a 'list comprehension' > > return tuple([row == var.get() for var in self.variables]) > > and, since Python 2.4, to the 'generator expression' that I used and which > avoids building the intermediate list. Both constructs also feature an > if-clause, see > > http://docs.python.org/tut/node7.html#SECTION007140000000000000000 > http://docs.python.org/tut/node11.html#SECTION00111100000000000000000 > > >>p.s. I tweaked >> >>rbn = tk.Radiobutton(self, text=text, variable=var, value=y) >>to >>rbn = tk.Radiobutton(self, text=text, variable=var, value=y+1) >> >>and >> >>return tuple(row == var.get() for var in self.variables) >>to >>return tuple(row+1 == var.get() for var in self.variables) >> >>so that the Radiogrid doesn't initialize w/row 1 selected, and >>accomodates cases where nothing is selected in any column. > > > Another option would have been to initialize the variables > > ... > var = tk.IntVar() > var.set(-1) > if trace_write: > ... > > Peter > From calfdog at yahoo.com Fri Jun 3 01:03:07 2005 From: calfdog at yahoo.com (calfdog at yahoo.com) Date: 2 Jun 2005 22:03:07 -0700 Subject: OpenSource Automation tool - Pamie 1.5 released Message-ID: <1117774987.682444.312500@g47g2000cwa.googlegroups.com> PAMIE 1.50 released!! Now with Frames suport Why wait, when you could be using this to Automate now!... It's Free!!! http://pamie.sourceforge.net ======================================================================== What is PAMIE? PAMIE stands for Python Automation module for Internet Explorer. Requirements: ------------ * Window 2000, WinNT, WinXP * Python 2.4. (I use Active State Python 2.4.x since it installs the needed win32all library) Optional tools for writing scripts: * Eclipse with pydev plugin ( great for writing, running and debugging scripts) - recommended!! * Emacs - for script writing * Notepad++ - for script writing * PythonWin IDE installed with Activestate Python - http://www.Activestate.org - for script writing and running ========================================================================== This was completely written in Python to be used as a QA/Development tool for Web testing. You will find this is one of the easiest automation tool to use for automating Internet Explorer. PAMIE is a class file (cPAMIE.py) that you import and you can calls its methods to write scripts that automate your IE browser client. Used with PY unit you can write complex Web testing frameworks. Uses: Web testing Use along with Jmeter for Performance testing. ========================================================================== New Enhancements: ---------------- Frames support improved report status Just a few of the methods available: ------------------------------------ _frameWait - waits for user specified frame document to load _wait - wait for document to load checkForFormName - check to see if a formname exists in the document checkForFrameName -- check to see if a framename exists ClickBtnImage - Clicks on an input type image button ClickButton - Click on a button ClickImage - clicks on an Image ClickLink - Clicks on a link ClickMenu - Clicks on an menu item,link ClickMenuImage - Clicks on an menu item that is a image. Click a Menu or Sub Menu Item ClickNthImage click on the Nth Image ClickNthLink - click on the Nth link ClickOuterLink - clicks on a link using outertext ClickPageLink - click on the page link GetTextBox - get tectbox value SettextBox - Sets texbox value GetNames - get the names of the form elements GetListbox - gets selected listbox item SetlistBox - sets selected listbox item GetRadioButton - Gets Radio button status SetRadioButton - Sets Radio button GetRadioButtonSet - same as above and much much more !!! Check it out! Thank you R.L. Marchetti From foundsabin at gmail.com Mon Jun 20 07:12:46 2005 From: foundsabin at gmail.com (Sabin) Date: 20 Jun 2005 04:12:46 -0700 Subject: dll files Message-ID: <1119265966.661838.186320@g44g2000cwa.googlegroups.com> How can i create dll files in Python? Is it possible? If yes, how to enclose image and font files in a dll ? Plis reply. SABIN. B'lore. From mwm at mired.org Sun Jun 12 20:53:29 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 12 Jun 2005 19:53:29 -0500 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> Message-ID: <86ekb713hy.fsf@guru.mired.org> Andrea Griffini writes: > On Sat, 11 Jun 2005 21:52:57 -0400, Peter Hansen > wrote: > Also concrete->abstract shows a clear path; starting > in the middle and looking both up (to higher > abstractions) and down (to the implementation > details) is IMO much more confusing. So you're arguing that a CS major should start by learning electronics fundamentals, how gates work, and how to design hardware(*)? Because that's what the concrete level *really* is. Start anywhere above that, and you wind up needing to look both ways. Admittedly, at some level the details simply stop mattering. But where that level is depends on what level you're working on. Writing Python, I really don't need to understand the behavior of hardware gates. Writing horizontal microcode, I'm totally f*cked if I don't understand the behavior of hardware gates. In short, you're going to start in the middle. You can avoid looking down if you avoid certain classes of problems - but not everyone will be able to do that. Since you can only protect some of the students from this extra confusion, is it really justified to confuse them all by introducing what are really extraneous details early on? You've stated your opinion. Personally, I agree with Abelson, Sussman and Sussman, whose text "The Structure and Interpretation of Computer Programs" was the standard text at one of the premiere engineering schools in the world, and is widely regarded as a classic in the field: they decided to start with the abstract, and deal with concrete issues - like assignment(!) later. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ldo at geek-central.gen.new_zealand Mon Jun 20 01:04:43 2005 From: ldo at geek-central.gen.new_zealand (Lawrence D’Oliveiro) Date: Mon, 20 Jun 2005 17:04:43 +1200 Subject: references/addrresses in imperative languages References: <1119220461.626477.56110@g49g2000cwa.googlegroups.com> Message-ID: In article <1119220461.626477.56110 at g49g2000cwa.googlegroups.com>, "Xah Lee" wrote: >A[n] easy way to see this, is to ask yourself: how come in mathematics >there's no such thing as "addresses/pointers/references". Yes there are such things in mathematics, though not necessarily under that name. For instance, in graph theory, edges can be considered as "pointers". After all, make a change to a node, and that change is visible via all edges pointing to that node. From FFROGG at gmail.com Sat Jun 4 04:34:28 2005 From: FFROGG at gmail.com (thinfrog) Date: 4 Jun 2005 01:34:28 -0700 Subject: [ANN] Snakelets 1.41 and Frog 1.6 References: <42a0a7f4$0$29628$e4fe514c@news.xs4all.nl> Message-ID: <5a446e4e.0506040034.60fa5950@posting.google.com> It's very interesting, i'm glad to try. And it can access data by MYSQL/SQL or other database software? From almad at include.cz Wed Jun 8 05:41:49 2005 From: almad at include.cz (Almad) Date: Wed, 08 Jun 2005 11:41:49 +0200 Subject: xsd2gui Message-ID: Hello, is there any way how to generate GUI form from given XML Schema? I mean, any lib which can do it? I think it's usable for "gui editing" of XML File. Google give me only completed standalone programs or non-python solutions. Thanks, -- Lukas "Almad" Linhart [:: http://www.almad.net/ ::] From trentm at ActiveState.com Wed Jun 29 12:11:05 2005 From: trentm at ActiveState.com (Trent Mick) Date: Wed, 29 Jun 2005 09:11:05 -0700 Subject: How to find Windows "Application data" directory?? In-Reply-To: <7xbr5pkdnb.fsf@ruckus.brouhaha.com> References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> <1120017647.696243.154880@f14g2000cwb.googlegroups.com> <7xbr5pkdnb.fsf@ruckus.brouhaha.com> Message-ID: <20050629161105.GA7804@ActiveState.com> [Paul Rubin wrote] > "Rune Strand" writes: > > You have the environment variable APPDATA. You can access it with > > os.environ(). > > Thanks!!!!!! Wow, I'd been hacking away at much messier approaches > than that. It's actually os.environ['APPDATA'] ;-) Note that the APPDATA environment variable is only there on *some* of the Windows flavours. It is there on Win2k and WinXP. It is not there on WinME. Dunno about Win95, Win98, WinNT... but you may not care about those old guys. Cheers, Trent -- Trent Mick TrentM at ActiveState.com From firstname.lastname at iki.fi-spam Mon Jun 27 15:50:45 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 27 Jun 2005 22:50:45 +0300 Subject: Python + Lisp integration - Part II Message-ID: <87vf3z7f56.fsf@sme.intra.citec.fi> I'm posting a self-followup to my post in last December about Python and Lisp integration: Now, just yesterday I just stumbled upon Lython: It's a bit edgy but it can be made to work :-). It does do simple macros and compiles to Python bytecode (via AST generation). So, effectively you could be writing your code in Lisp and then running it in the vast environment of Python standard library and modules. This was FYI, if interested. cheers, S -- firstname.lastname at iki.fi -- Today is the car of the cdr of your life. From hancock at anansispaceworks.com Tue Jun 14 00:40:51 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 23:40:51 -0500 Subject: How to get/set class attributes in Python In-Reply-To: <0001HW.BED3BE5000197B71F0488550@news.individual.de> References: <0001HW.BED3BE5000197B71F0488550@news.individual.de> Message-ID: <200506132340.51600.hancock@anansispaceworks.com> On Monday 13 June 2005 03:50 pm, Kalle Anke wrote: > On Mon, 13 Jun 2005 20:41:48 +0200, Terry Hancock wrote > (in article ): > > > 1) Assume the variables are of a sensible type (not > > necessarily the one you expected, though), and provide > > exception handling to catch the case where their interface > > does not match what you expect. > > The problem I have with this is that I might discover an error at runtime > instead of compile time, this means that I need to really exercise all > possible test cases to make sure that I've covered everything (which of > course is a good thing) but it would be easier to discover this at "compile > time". The Python solution to this problem is called "unittest". It is at least as easy to do unit testing in Python as it is to properly handle type-checking in C or Java. > > Let's face it -- should it matter if you "are a programmer" > > or only if you "can program"? This is the difference in > > philosophy behind a dynamically-typed language like > > Python and a statically typed one like Java. > > I don't really understand what you're meaning (English isn't my native > language as you probably already have discovered) (Actually no, you're quite fluent, AFAICT). I was making an analogy: Requiring a variable to be, say, a "float" is like insisting that only people with the job title "Programmer" be allowed to see the language documentation. In both situations, real life will confront you with situations where you will wish that you had been more tolerant. Lots of us are not "Programmers", but we do quite a bit of programming. Likewise, you'll be happier to discover that ints or complex numbers work with your code too, without having to jump through hoops to make it happen. I find the biggest problem coming to Python from a language like C, C++, or Java is that you overthink things and try to do them the hard way. A lot of times, you find out that the "Python way" to do the thing is so blindingly obvious that it just didn't occur to you that it could be that simple. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From kveretennicov at gmail.com Mon Jun 20 11:28:34 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Mon, 20 Jun 2005 18:28:34 +0300 Subject: JEP and JPype in a single process In-Reply-To: References: Message-ID: <4660fe30050620082811b3d49f@mail.gmail.com> On 6/20/05, skn wrote: > Hello, > > I have written a very simple java class file, which invokes a Python script > using JEP. . . . > Now inside this Python script I want to make Java calls using JPype. I am not familiar with either Jepp or JPype, but I spotted this snippet on Jepp page (http://jepp.sourceforge.net/): import jep FileInputStream = jep.findClass('java.io.FileInputStream') try: fin = FileInputStream('adsf') except jep.FileNotFoundException: print 'Invalid file' Are you sure you need to call JPype? - kv From dvanvliet at 3dna.net Thu Jun 30 15:58:29 2005 From: dvanvliet at 3dna.net (Derek van Vliet) Date: 30 Jun 2005 12:58:29 -0700 Subject: saving pre-compiled scripts Message-ID: <1120161509.096169.166730@o13g2000cwo.googlegroups.com> Hi, I'm working on an application that reads python scripts from XML elements and compiles them during my app's startup process using. The application then runs the resulting compiled PyCodeObjects using PyEval_EvalCode as they are needed. Now I'm wondering if its possible to pre-compile the scripts and save the PyCodeObjects in a binary file (or in CDATA in an XML element) and have them ready to run when the application starts up. My only constraint is that I need to be able to load the scripts from memory (which is why using Py_CompileString has worked well for me). Is there any way I can get the size of a PyCodeObject so that I could save it to a binary file? If I did that would it run correctly if I reloaded it and tried to Eval it? Can I load a pyc file from memory somehow? Any guidance would be greatly appreciated. Thanks, Derek From scrimp212 at yahoo.com Thu Jun 16 10:10:54 2005 From: scrimp212 at yahoo.com (scrimp) Date: 16 Jun 2005 07:10:54 -0700 Subject: Using PAMIE to upload and download files...is it possible? In-Reply-To: <1118436573.931101.78280@g44g2000cwa.googlegroups.com> References: <1118077246.115120.25220@g44g2000cwa.googlegroups.com> <1118256512.379934.292780@z14g2000cwz.googlegroups.com> <1118436573.931101.78280@g44g2000cwa.googlegroups.com> Message-ID: <1118931054.662163.221310@f14g2000cwb.googlegroups.com> Well, thanx to Erin I got everything I needed to do to work. I basically used 2 classes and wrote a driver using PAMIE 1 for the two File Download windows and 1 for the Save As window Here are the classes I used. I took out the comments, but its really not too hard to understand class FileDownloadDialog (threading.Thread): def __init__(self): threading.Thread.__init__(self) self.windowName = "File Download" self.hwnd = None def fetchWindows (self,attempts=20): tries = 0 while tries 0: wHwnd = hw self.hwnd = wHwnd oButtons = winGuiAuto.findControls(self.hwnd,"&Save","Button") time.sleep(0.5) for oButton in oButtons: winGuiAuto.clickButton(oButton) Heres the 2nd class I used class SaveAsZipDialog (threading.Thread): def __init__(self, docPath): threading.Thread.__init__(self) self.windowName = "Save As" self.hwnd = None self.document = docPath def fetchWindow (self,attempts=20): tries = 0 while tries < attempts: tries = tries + 1 try: self.hwnd = winGuiAuto.findTopWindow(self.windowName) return except: print 'Checking for window named "'+ self.windowName + '"', print 'Attempt ',tries time.sleep(1) def run (self): self.fetchWindow() fText = winGuiAuto.findControl(self.hwnd, None, "Edit") winGuiAuto.setEditText(fText,self.document) oButtons = winGuiAuto.findControls(self.hwnd,"Save") time.sleep(0.5) for oButton in oButtons: winGuiAuto.clickButton(oButton) I used PAMIE to get me through the web stuff and when it clicked on the link to download the zip file I wanted these two classes would kick in and take over from there. If anyone needs help feel free to email me or post up on here. Thanks again Erin! --Barry From lambacck at gmail.com Tue Jun 28 21:00:34 2005 From: lambacck at gmail.com (Chris Lambacher) Date: Tue, 28 Jun 2005 21:00:34 -0400 Subject: Problem building Python bindings for subversion In-Reply-To: <1119988764.695754.52530@g44g2000cwa.googlegroups.com> References: <1119988764.695754.52530@g44g2000cwa.googlegroups.com> Message-ID: You will probably get more help with this on subversion mailing list. -Chris On 28 Jun 2005 12:59:24 -0700, Arthur Chereau wrote: > Hi, > > I'm trying to setup viewcvs to work with subversion 1.2.0 on Linux with > Python 2.4.1. The last viewcvs (from CVS) needs subversion python > bindings. I installed swig and built subversion from source with it. > Everything works fine until I try to build the Python bindings. > > When I try "make swig-py" I get the following, Python related, error: > > # make swig-py > /bin/sh /usr/src/subversion-1.2.0/libtool --tag=CC --silent > --mode=compile gcc -DLINUX=2 -D_REENTRANT -D_XOPEN_SOURCE=500 > -D_BSD_SOURCE -D_SVID_SOURCE -D_GNU_SOURCE -DSWIGPYTHON -g -O2 -g -O2 > -pthread -DNEON_ZLIB -DNEON_SSL > -I/usr/src/subversion-1.2.0/subversion/bindings/swig > -I/usr/src/subversion-1.2.0/subversion/include > -I/usr/swig/share/swig/1.3.25 -DSVN_SWIG_VERSION=103025 > -DSWIG_TABLE_TYPE=subversion -I/usr/src/subversion-1.2.0/apr/include > -I/usr/src/subversion-1.2.0/apr-util/include > -I/usr/Python/include/python2.4 > -I/usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py > -I./subversion/include -I./subversion > -I/usr/src/subversion-1.2.0/neon/src -I/usr/subversion/include/neon > -I/usr/src/subversion-1.2.0/apr/include > -I/usr/src/subversion-1.2.0/apr-util/include -o > subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.lo -c > /usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.c > > In file included from /usr/Python/include/python2.4/Python.h:8, > from > /usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.c:20: > /usr/Python/include/python2.4/pyconfig.h:844: warning: `_XOPEN_SOURCE' > redefined > *Initialization*:1: warning: this is the location of the previous > definition > In file included from > /usr/src/subversion-1.2.0/subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.c:44: > /usr/swig/share/swig/1.3.25/runtime.swg:28: macro `SWIG_GetModule' used > without args > /usr/swig/share/swig/1.3.25/runtime.swg:34: macro `SWIG_GetModule' used > without args > make: *** > [subversion/bindings/swig/python/libsvn_swig_py/swigutil_py.lo] Error 1 > > Is there something I'm doing wrong ? > > Thanks, > > AC > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Christopher Lambacher lambacck at computer.org From riccardo_cut1 at cut2_sideralis.net Thu Jun 23 05:05:57 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Thu, 23 Jun 2005 11:05:57 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: On Wed, 22 Jun 2005 11:27:06 -0500, Jeff Epler wrote: > Why not just define the function yourself? Not every 3-line function > needs to be built in. Of course I can code such a function, and I agree with the second sentence, but I think that obtaining absolutes path is a task so commonly needed that adding a keyword to an existing function would give a plus to the library without adding complexity (speaking of number of modules). Usually when you use os.listdir do you end using os.path.join to obtain absolutes path? I'm interested to know if the task is so common as I think, or if I'm wrong. Thank you, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From richardlewis at fastmail.co.uk Mon Jun 20 07:37:42 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Mon, 20 Jun 2005 12:37:42 +0100 Subject: utf8 and ftplib Message-ID: <1119267462.32655.236736750@webmail.messagingengine.com> OK, I'm still not getting this unicode business. Given this document: ========================== aàáâã eèéêë iìíîï oòóôõ oùúûü ========================== (If testing, make sure you save this as utf-8 encoded.) and this Python script: ========================== import sys from xml.dom.minidom import * from xml.dom import * import codecs import string CHARACTERS = range(128,255) def unicode2charrefs(s): "Returns a unicode string with all the non-ascii characters from the given unicode string converted to character references." result = u"" for c in s: code = ord(c) if code in CHARACTERS: result += u"&#" + string.zfill(str(code), 3).decode('utf-8') + u";" else: result += c.encode('utf-8') return result def main(): print "Parsing file..." file = codecs.open(sys.argv[1], "r", "utf-8") document = parse(file) file.close() print "done." print document.toxml(encoding="utf-8") out_str = unicode2charrefs(document.toxml(encoding="utf-8")) print "Writing to '" + sys.argv[1] + "~' ..." file = codecs.open(sys.argv[1] + "~", "w", "utf-8") file.write(out_str) file.close() print "done." if __name__ == "__main__": main() ========================== Does anyone else get this output from the "print document.toxml(encoding="utf-8")" line: a???????? e???????? i???????? o???????? o???????? and, similarly, this output document: ========================== aàáâã eèéêë iìíîï oòóôõ oùúûü ========================== i.e., does anyone else get two byte sequences beginning with capital-A-with-tilde instead of the expected characters? I'm using the Kate editor from KDE and Konsole (using bash) shell on Linux (2.6 kernel). Does that make any difference? I've just tried it on the unicode-aware xterm and the "print document.toxml(encoding="utf-8")" line produces the expected output but the output file is still wrong. Any ideas whats wrong? Cheers, Richard From riccardo_cut1 at cut2_sideralis.net Thu Jun 23 12:48:52 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Thu, 23 Jun 2005 18:48:52 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: On Thu, 23 Jun 2005 09:21:55 -0600, Ivan Van Laningham wrote: > Mmmm, how about: > > # mylistdir.py > import os, os.path > import sys > > def mylistdir(dir, join=False): > for file in os.listdir(dir): > if join: > yield join(dir, file) > else: > yield file > > print list(mylistdir(sys.argv[1])) > > or > > print list(mylistdir(sys.argv[1],os.path.join)) > > That way I could def my own join and call it as > > print list(mylistdir(sys.argv[1],myjoin)) I think that the implementation of listdir is done in C, so the functionality would be added in C too. by the way, I think 'join' (cute keyword) should be a boolean and not a callable: the obvious way is that we join path using os.path.join, and not some sophisticated function. With a boolean keyword code is smaller and if we want to use our special join function we can do it simply. e.g def func(dir,join=False): return (join and join(dir,x) or x for x in os.listdir(dir)) os.listdir is actually supposed not to be a generator, like you suggested. Are there known future changes ? Bye, Riccardo -- Riccardo Galli Sideralis Programs http://www.sideralis.net From gsakkis at rutgers.edu Sat Jun 25 02:12:21 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 24 Jun 2005 23:12:21 -0700 Subject: How does one write a function that increments a number? References: <1119675183.833896.145710@g47g2000cwa.googlegroups.com> <1119676986.613202.315140@g47g2000cwa.googlegroups.com> <1119678060.774799.244920@g43g2000cwa.googlegroups.com> Message-ID: <1119679941.908466.127930@g44g2000cwa.googlegroups.com> wrote: > Wait... so this means it is impossible to write a function that > increments an integer without turning the integer into a list? The short answer is no you can't, because integers are immutable (as well as floats and strings among others). The longer answer is you can create a, say, MutableInt class whose instances behave as modifiable integers. Most probably you don't really need this, but if you think you do, others in the list will sketch out how. George From scrimp212 at yahoo.com Fri Jun 3 13:42:42 2005 From: scrimp212 at yahoo.com (scrimp) Date: 3 Jun 2005 10:42:42 -0700 Subject: saving .zip or .txt email attachments instead of deleting them In-Reply-To: <119v8ntj6bren91@news.supernews.com> References: <1117746435.769666.186810@z14g2000cwz.googlegroups.com> <119utnt1mvdue50@news.supernews.com> <1117748443.644449.30170@g43g2000cwa.googlegroups.com> <119v8ntj6bren91@news.supernews.com> Message-ID: <1117820562.085749.300710@z14g2000cwz.googlegroups.com> Here is the complete traceback..sorry about that though. I used the run button and entered in "C:\email.txt" for the msgfile parameter thats used for input This email.txt file has a zip file attached to it and is all in text, so hopefully I am working with the correct input file. I used the pop3 example given in the python documentation to pick up a message on the mail server and read and wrote the information to a file --> email.txt Traceback (most recent call last): File "C:\PYTHON23\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\My Documents\python scripts\EmailUnpack.py", line 83, in ? main() File "C:\My Documents\python scripts\EmailUnpack.py", line 71, in main ext = mimetypes.guess_extension(part.get_type()) File "C:\PYTHON23\lib\mimetypes.py", line 178, in guess_extension extensions = self.guess_all_extensions(type, strict) File "C:\PYTHON23\lib\mimetypes.py", line 157, in guess_all_extensions type = type.lower() AttributeError: 'NoneType' object has no attribute 'lower' Again, thanks! --Barry From Xavier.Decoret at imag.fr Mon Jun 13 12:06:45 2005 From: Xavier.Decoret at imag.fr (=?ISO-8859-1?Q?Xavier_D=E9coret?=) Date: Mon, 13 Jun 2005 18:06:45 +0200 Subject: Controlling assignation In-Reply-To: References: Message-ID: Xavier D?coret a ?crit : > I would like to know if there is for python's classes an equivalent of > the operator= that can be overidden. > > Let's say I have > >>> a=A() > and I want to write > >>> a=5 > and I want this to change some internal value of a instead of making a > point to a new object (an int 5) > > In other word, I would like to be able to use a=5 instead of a.set(5) > > Is that possible? Thanks anybody for the answers. It confirms what I understood of Python. What I wanted to do is something like this: def change(x,v): x = v class A(object): def __init__(self,v): self.x = v a = A(3) print a.x # displays 3 change(a.x,4) print a.x # still displays 3 It may seem weird, but I ensure there is a reason for doing this. In C++ (the language I am mot familiar with), I could define f to take a pointer to member function of a class, a pointer and a value and achieve what I want. In python, I cannot that way becauswe when change(a.x,4) is executed, a.x is "replaced" by ist value (returned by __getattribute__). Finally, here is how I hold the situation: class Handle: def __init__(self,v): self.__v = v def __call__(self): x = self.__v while callable(x): x=x() return x def set(self,v): self.__v = v class HandledProperty(object): def __init__(self,name=""): self.name = name def __get__(self,o,t): return o.__dict__[self] def __set__(self,o,v): o.__dict__[self] = Handle(v) class A(object): x = HandledProperty("x") def __init__(self,v): self.x = v def change(x,v): x.set(v) a = A(3) print a.x() # displays 3 (notice the () in the call) change(a.x,4) print a.x() # still displays 4 From dsa at unilestemg.br Wed Jun 8 05:00:00 2005 From: dsa at unilestemg.br (Douglas Soares de Andrade) Date: Wed, 8 Jun 2005 09:00:00 +0000 Subject: Binary numbers In-Reply-To: <1118223539.513060.229760@g49g2000cwa.googlegroups.com> References: <1118223539.513060.229760@g49g2000cwa.googlegroups.com> Message-ID: <200506080900.00244.dsa@unilestemg.br> Hi! Em Quarta 08 Junho 2005 09:38, Guyon Mor?e escreveu: > Don't know if this is what you mean, but: > > Binary to decimal: > >>> bin_num = '100001011' > >>> int(bin_num, 2) > > 267 Dont know this way of using it. Thanks for the teachings :) See ya ! -- Douglas Soares de Andrade http://douglasandrade.cjb.net - dsa at unilestemg.br UnilesteMG - www.unilestemg.br ICQ, MSN = 76277921, douglas at tuxfamily.org From tassilo.von.parseval at rwth-aachen.de Sat Jun 18 05:42:16 2005 From: tassilo.von.parseval at rwth-aachen.de (Tassilo v. Parseval) Date: Sat, 18 Jun 2005 11:42:16 +0200 Subject: Python documentation problem References: <1119080966.127916.284440@z14g2000cwz.googlegroups.com> <1119082311.658973.169610@o13g2000cwo.googlegroups.com> Message-ID: Also sprach Xah Lee: > i wanted to find out if Python supports eval. e.g. > > somecode='3+4' > print eval(somecode) # prints 7 > > in the 14 hundred pages of python doc, where am i supposed to find this > info? You are not going to find it in comp.lang.perl.misc. Tassilo -- use bigint; $n=71423350343770280161397026330337371139054411854220053437565440; $m=-8,;;$_=$n&(0xff)<<$m,,$_>>=$m,,print+chr,,while(($m+=8)<=200); From adonisv at DELETETHISTEXTearthlink.net Mon Jun 27 09:43:15 2005 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Mon, 27 Jun 2005 13:43:15 GMT Subject: Tkinter PhotoImage Question Message-ID: I have two classes one class inherits dict(), this class just takes in a path argument much like glob.glob() and loads the image using PhotoImage into itself, no biggie works fine. The other class inherits Frame and it implements an add(self, **kw) method passes all of its arguments to a Button. My question is that when I load the images with the first class and then use dict.get(name) as the image argument for the add method the image does not show up, mind you the variable holding the dict is seen by the whole class so its not a garbage collection issue, but if I put a command in the argument list it works just fine? Any help is greatly appreciated. Adonis From richardlewis at fastmail.co.uk Thu Jun 2 08:16:05 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Thu, 02 Jun 2005 13:16:05 +0100 Subject: DOM question Message-ID: <1117714565.3512.235483757@webmail.messagingengine.com> Hi there, I have an XML document which contains a mixture of structural nodes (called 'section' and with unique 'id' attributes) and non-structural nodes (called anything else). The structural elements ('section's) can contain, as well as non-structural elements, other structural elements. I'm doing the Python DOM programming with this document and have got stuck with something. I want to be able to get all the non-structural elements which are children of a given 'section' elemenent (identified by 'id' attribute) but not children of any child 'section' elements of the given 'section'. e.g.:
bar
baz
foo
Given this document, the working function would return "baz" for id='b' and "foo" for id='c'. Normally, recursion is used for DOM traversals. I've tried this function which uses recursion with a generator (can the two be mixed?) def content_elements(node): if node.hasChildNodes(): node = node.firstChild if not page_node(node): yield node for e in self.content_elements(node): yield e node = node.nextSibling which didn't work. So I tried it without using a generator: def content_elements(node, elements): if node.hasChildNodes(): node = node.firstChild if node.nodeType == Node.ELEMENT_NODE: print node.tagName if not page_node(node): elements.append(node) self.content_elements(node, elements) node = node.nextSibling return elements However, I got exactly the same problem: each time I use this function I just get a DOM Text node with a few white space (tabs and returns) in it. I guess this is the indentation in my source document? But why do I not get the propert element nodes? Cheers, Richard From scott at alussinan.org Tue Jun 28 13:45:31 2005 From: scott at alussinan.org (scott) Date: Tue, 28 Jun 2005 19:45:31 +0200 Subject: regulars expressions ? Message-ID: <42c18cc9$0$6342$636a15ce@news.free.fr> hi people ! i got some trouble with regular expressions i need to split a string like this on the ',' character : mystring = ""\test1, test2\", test, 42" i wanna get something (a list) like this (3 elements) : "test1, test2" test 42 but the only thing i get is a list like this (4 elements) : "test1" "test2" test 42 each element is separated by ',' but 1st element which is delimited by '"' may contain ',' character inside. so the regular expression i need is something like : split each element using ',' delimiter but if ',' delimiter is included between '"' please do not split 1st question is : does someone has understood the question ? 2nd question is : does someone has an answer ? thanks people scott From cjbottaro at alumni.cs.utexas.edu Mon Jun 6 14:50:32 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Mon, 06 Jun 2005 13:50:32 -0500 Subject: how to get name of function from within function? References: Message-ID: Christopher J. Bottaro wrote: > The problem is: >>>> c.func_b.__name__ > 'wrapper' > > That messes up SOAPpy's RegisterFunction() method which apparently depends > on the __name__ of the function to publish it as an available SOAP > function. > > Any suggestions on how to change the name of c.func_b to 'func_b' instead > of 'wrapper'? Nevermind, I looked at the SOAPpy source, they provide a way to manually specify the SOAP method name that is published. Thanks anyways, -- C From luismgz at gmail.com Wed Jun 29 18:34:11 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 29 Jun 2005 15:34:11 -0700 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> Message-ID: <1120084451.475909.19390@o13g2000cwo.googlegroups.com> Grant Edwards wrote: > That depends on the accent. I believe that's probably true for > the educated south of England, BBC, received pronunciation. I > don't think that's true for some of the other dialects from > northern areas (e.g. Liverpool) or the "cockney" accent. What's exactly the "cockney" accent? Is it related to some place or it's just a kind of slang? I'm not sure, but I think that I read somewhere that it is common in some parts of London, and that it is a sign of a particular social class, more than a regionalism. Is that true? From david.kettle at sympatico.ca Fri Jun 3 09:13:01 2005 From: david.kettle at sympatico.ca (david.kettle at sympatico.ca) Date: Fri, 3 Jun 2005 09:13:01 -0400 Subject: Question about 'wave' module Message-ID: <272040-220056531313128@M2W042.mail2web.com> Hello Python World! I've been playing with the 'wave' and 'audioop' modules in the library, and I have a question. When I tried to read a "wav" file with samples in 32-bit float, I got the following error: Traceback (most recent call last): File "Play.py", line 111, in ? playWAV(sys.argv[1]) File "Play.py", line 69, in playWAV f = wave.open(fname,'rb') File "D:\Python23\lib\wave.py", line 483, in open return Wave_read(f) File "D:\Python23\lib\wave.py", line 162, in __init__ self.initfp(f) File "D:\Python23\lib\wave.py", line 143, in initfp self._read_fmt_chunk(chunk) File "D:\Python23\lib\wave.py", line 264, in _read_fmt_chunk raise Error, 'unknown format: ' + `wFormatTag` wave.Error: unknown format: 3 Although the documentation doesn't explicitly say so, it appears that only 16-bit format is supported. I looked at the source code ('wave.py'), and I think my hunch is correct. On lines 245 (in method 'readframes') and 412 (in method 'writeframesraw'), a call is made to the array method 'byteswap' if the machine is "big- endian", without testing to see if the samples are 16-bit or 32-bit. I don't understand how this could work without knowing how many bytes to "swap", (ie, 2 or 4). Has anyone on this list used these modules? Am I missing something? BTW, I'm on version 2.3.2 for Windows. The 32-bit sound file was created with a program called "Audacity". I believe the format of the file is a valid wave file format, I'm able to play it with Windows Media Player. Thanks for your help. -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web.com/ . From clambin at die.spammers.die.easynet.be Sat Jun 18 05:59:55 2005 From: clambin at die.spammers.die.easynet.be (Christophe Lambin) Date: Sat, 18 Jun 2005 11:59:55 +0200 Subject: pygtk question References: <1118796035.754511.224780@o13g2000cwo.googlegroups.com> Message-ID: "RunLevelZero" wrote: > Hopefully someone can help me out here. It's probably super simple but > how do you select multiple items in a treeview? I have > gtk.SELECTION_MULTIPLE set but of course that was enough. It should be enough to do this: treeview.get_selection().set_mode(gtk.SELECTION_MULTIPLE) If it doesn't work, try posting a short example so someone can have a look. From sjmachin at lexicon.net Fri Jun 17 18:01:37 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 18 Jun 2005 08:01:37 +1000 Subject: Why is there no instancemethod builtin? In-Reply-To: References: Message-ID: <42B34841.9060001@lexicon.net> John Reese wrote: > Why hello there ha ha. [snip] Just looking through the types declared in types, the > following are builtins: > [snip] > ... NoneType, > NotImplementedType > > And the following are not: > [snip] > ... NoneType, NotImplementedType > > So for any in the latter batch, I have to import types after all. Plonk. From superprad at gmail.com Mon Jun 13 17:18:49 2005 From: superprad at gmail.com (PyPK) Date: 13 Jun 2005 14:18:49 -0700 Subject: Tiff Image Reader/writer In-Reply-To: References: <1118674504.342511.238000@g47g2000cwa.googlegroups.com> <1118692248.242717.63770@g49g2000cwa.googlegroups.com> <1118694007.688607.124530@z14g2000cwz.googlegroups.com> Message-ID: <1118697529.173406.134460@g44g2000cwa.googlegroups.com> One reason why I don't want to use PIL is it seems very slow for tiff images of very large sizes(2400x4800). So I am looking for a better tool than does the right job faster. From martin at v.loewis.de Mon Jun 13 00:55:03 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 13 Jun 2005 06:55:03 +0200 Subject: How to use 8bit character sets? In-Reply-To: References: Message-ID: <42ad11a7$0$24953$9b622d9e@news.freenet.de> copx wrote: > For some reason Python (on Windows) doesn't use the system's default > character set and that's a serious problem for me. I very much doubt this statement: Python does "use" the system's default character set on Windows. What makes you think it doesn't? > Is it possible to tell Python to use an 8bit charset (latin-1 in my case) > for textfile and string processing by default? That is the default. Regards, Martin From __peter__ at web.de Fri Jun 3 04:32:54 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Jun 2005 10:32:54 +0200 Subject: read input for cmd.Cmd from file References: Message-ID: Achim Domma (Procoders) wrote: > I'm writing a simple shell using cmd.Cmd. It would be very usefull if I > could read the commands as batchjob from a file. I've tried the following: [...] Your original approach should work too if you clear the use_rawinput flag and provide a do_EOF() method that handles the file end: import cmd class Cmd(cmd.Cmd): def do_this(self, arg): print "this>", arg def do_that(self, arg): print " References: <1117915995.759559.240730@g47g2000cwa.googlegroups.com> Message-ID: <9D3630C7-58D1-40BB-81CF-0D955A8B7F76@advfn.com> I'm thinking that with a decent dynamics engine (PyODE?) you could write a reasonably realistic simulator to test this sort of code on. Obviously it won't be as good as actually you know, driving a Jeep around by wire, but it'd be a tad cheaper and more time efficient for anyone interested in this sort of thing. There the time involved in actually writing a simulator which you can experiment on your DBW code on though. You could probably get one going within a year though I imagine. Unfortunately from what i've seen of it, the Open Dynamics Engine is less than accurate under some situations. Unfortunately I believe all the really awesome ones cost huge amounts of money. Just a thought. I don't have any actual experience with DBW stuff :P On 4 Jun 2005, at 21:13, igorcarron at gmail.com wrote: > Folks, > > In a previous post[*] we made an announcement about the release of the > drive-by-wire code for our entry in the DARPA Grand Challenge. We will > do more in the future (including more data and more code). With > regards > to our building the full autonomous code, things are going along well. > However, the somewhat large traffic on our web site had us thinking: > > Provided we give a good HOW-TO/API, would there be any interest from > anybody to try their code on our vehicle as long as it is in Python > and > safe to run ? > > Many people think of way to deal with the programming side of > road-following and collision avoidance at 60 mph, but very few have > the > time to build a vehicle that can make these concepts a reality. In > order to respond to this, I was thinking of a possibility where > somebody would submit a code, pay $200 and we would try it on a closed > circuit. Then the programmer would be getting all the data > attendant to > the vehicle driving itself through the course following their > programs? > > > The pros for us: > - raise some money for the vehicle > - identify potentially better algorithms -> identify people we would > like to associate ourselves with. > > The cons for us: > - this is time not dedicated to focusing on the race > - issues with proprietary code/IP > - issues with safety > - coordination with many parties > > Right now I am thinking the cons are overwhelming, what do y'all think > ? > > > Igor. > > [*] > http://groups-beta.google.com/group/comp.lang.python/browse_frm/ > thread/5f78e2ecb3e9139d/af28daca5e385af3#af28daca5e385af3 > > -- > http://mail.python.org/mailman/listinfo/python-list > > From nick at craig-wood.com Thu Jun 30 07:30:13 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Jun 2005 11:30:13 GMT Subject: Which kid's beginners programming - Python or Forth? References: <1119928572.088020.316240@g47g2000cwa.googlegroups.com> Message-ID: Rocco Moretti wrote: > So for Math you'd do something like: > > y = b + mx + cx^2 > > (Where ^2 is a superscript 2) > > For Python it would be: > > y = b + m*x + c*x**2 > > IIRC, for Forth it would be something like (please excuse the mistakes > in operator notation): > > x 2 ^ c * m x * + b + 'y' setvar In FORTH you don't generally use variables unless you really have to - that is what the stack is for, so you'd write a word like this... variable c 10 c ! variable m -2 m ! variable b 14 b ! : quad ( x -- b + m*x + c*x**2 ) dup dup ( x x x ) * c @ * swap ( cx**2 x ) m @ * + ( m*x + c*x**2 ) b @ + ( b + m*x + c*x**2 ) ; And now we test 7 quad . 490 ok Was that easy? Not really! Compared to python... >>> c = 10 >>> m = -2 >>> b = 14 >>> def quad(x): return b + m*x + c*x**2 ... >>> quad(7) 490 Was it fun? Well yes it was! FORTH is much lower level than python and you learn different things from it. At each step you have to worry about what is on the stack which attention to detail is important for a programmer. Its a lot of work to do even the simple stuff though. Its much easier to understand how FORTH works, and even implement your own from scratch. I learnt FORTH a long time ago, and I haven't used it for many many years! Its major pull back then was that it was fast, and easier to write than assembler. I don't think that really matters now though, Python is just as fast thanks to the 3 GHz machine I'm running it on (rather than the 4 MHz one I ran FORTH on then!) I think FORTH would be an interesting supplimentary language for anyone to learn though... *However* I reckon Python would make a much better first language than FORTH. The batteries included approach make a young programmers life much, much more fun, rather than starting from almost nothing (in modern terms) with FORTH. And like FORTH, Python has the interactive console which is essential when starting out. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sjmachin at lexicon.net Mon Jun 13 21:34:09 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 14 Jun 2005 11:34:09 +1000 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: References: Message-ID: <42ae3411@news.eftel.com> rbt wrote: > Here's the scenario: > > You have many hundred gigabytes of data... possible even a terabyte or > two. Within this data, you have private, sensitive information (US > social security numbers) about your company's clients. Your company has > generated its own unique ID numbers to replace the social security numbers. > > Now, management would like the IT guys to go thru the old data and > replace as many SSNs with the new ID numbers as possible. This question is grossly OT; it's nothing at all to do with Python. However .... (0) Is this homework? (1) What to do with an SSN that's not in the map? (2) How will a user of the system tell the difference between "new ID numbers" and SSNs? (3) Has the company really been using the SSN as a customer ID instead of an account number, or have they been merely recording the SSN as a data item? Will the "new ID numbers" be used in communication with the clients? Will they be advised of the new numbers? How will you handle the inevitable cases where the advice doesn't get through? (4) Under what circumstances will it not be possible to replace *ALL* the SSNs? (5) For how long can the data be off-line while it's being transformed? > You have a tab > delimited txt file that maps the SSNs to the new ID numbers. There are > 500,000 of these number pairs. And what is the source of the SSNs in this file??? Have they been extracted from the data? How? > What is the most efficient way to > approach this? I have done small-scale find and replace programs before, > but the scale of this is larger than what I'm accustomed to. > > Any suggestions on how to approach this are much appreciated. A sensible answer will depend on how the data is structured: 1. If it's in a database with tables some of which have a column for SSN, then there's a solution involving SQL. 2. If it's in semi-free-text files where the SSNs are marked somehow: ---client header--- surname: Doe first: John initial: Q SSN:123456789 blah blah or 123456789 then there's another solution which involves finding the markers ... 3. If it's really free text, like """ File note: Today John Q. Doe telephoned to advise that his Social Security # is 123456789 not 987654321 (which is his wife's) and the soc sec numbers of his kids Bob & Carol are .... """ then you might be in some difficulty ... google("TREC") AND however you do it, you need to be very aware of the possibility (especially with really free text) of changing some string of digits that's NOT an SSN. HTH, John From sjmachin at lexicon.net Tue Jun 14 08:15:20 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 14 Jun 2005 22:15:20 +1000 Subject: Hopefully simple regular expression question In-Reply-To: <1118746918.581184.5470@g49g2000cwa.googlegroups.com> References: <1118746918.581184.5470@g49g2000cwa.googlegroups.com> Message-ID: <42aeca58@news.eftel.com> peterbe at gmail.com wrote: > I want to match a word against a string such that 'peter' is found in > "peter bengtsson" or " hey peter," or but in "thepeter bengtsson" or > "hey peterbe," because the word has to stand on its own. The following > code works for a single word: > > def createStandaloneWordRegex(word): > """ return a regular expression that can find 'peter' only if it's > written > alone (next to space, start of string, end of string, comma, etc) > but > not if inside another word like peterbe """ > return re.compile(r""" > ( > ^ %s > (?=\W | $) > | > (?<=\W) > %s > (?=\W | $) > ) > """% (word, word), re.I|re.L|re.M|re.X) > > > def test_createStandaloneWordRegex(): > def T(word, text): > print createStandaloneWordRegex(word).findall(text) > > T("peter", "So Peter Bengtsson wrote this") > T("peter", "peter") > T("peter bengtsson", "So Peter Bengtsson wrote this") > > The result of running this is:: > > ['Peter'] > ['peter'] > [] <--- this is the problem!! > > > It works if the parameter is just one word (eg. 'peter') but stops > working when it's an expression (eg. 'peter bengtsson') No, not when it's an "expression" (whatever that means), but when the parameter contains whitespace, which is ignored in verbose mode. > > How do I modify my regular expression to match on expressions as well > as just single words?? > If you must stick with re.X, you must escape any whitespace characters in your "word" -- see re.escape(). Alternatively (1), drop re.X but this is ugly: regex_text_no_X = r"(^%s(?=\W|$)|(?<=\W)%s(?=\W|$))" % (word, word) Alternatively (2), consider using the \b gadget; this appears to give the same answers as the baroque method: regex_text_no_flab = r"\b%s\b" % word HTH, John From martin.witte at gmail.com Thu Jun 16 13:43:14 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 16 Jun 2005 10:43:14 -0700 Subject: How should threads be terminated? (related to 'Help with thread related tracebacks') In-Reply-To: References: Message-ID: <1118943794.041570.45670@o13g2000cwo.googlegroups.com> see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 for a useful recipe on how to do threading From peter at engcorp.com Fri Jun 24 21:26:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 21:26:52 -0400 Subject: Newbie question: SOLVED (how to keep a socket listening), but still some questions In-Reply-To: References: Message-ID: Giovanni Tumiati wrote: > However some of my questions still remain from earlier post: > (1) What is the difference between / how should they be used? > - setdefaulttimeout(timeout) > - settimeout(value) I think it's basically as you surmised. Calling socket.setdefaulttimeout() (where "socket" is the module itself) sets up the default timeout value for all subsequently created sockets. Calling sock.settimeout() (where "sock" is a specific socket object) changes the timeout value on that socket alone. > (2)Does one have to do a socket.shutdown() before one does a socket.close?? Not normally, AFAIK. -Peter From gregpinero at gmail.com Tue Jun 14 22:33:49 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 14 Jun 2005 22:33:49 -0400 Subject: MySQLDBAPI In-Reply-To: <312cfe2b05061419302497dd6@mail.gmail.com> References: <2tqln2-6c3.ln1@news.interplanet.it> <312cfe2b05061408481a3e7de0@mail.gmail.com> <3h939qFfvmjfU1@uni-berlin.de> <312cfe2b05061419302497dd6@mail.gmail.com> Message-ID: <312cfe2b05061419337d104ce6@mail.gmail.com> Here's a list of all the files from the RPM extraction, maybe that helps too? [gpinero at intel1 rpmmysql]$ dir -R .: usr ./usr: bin include lib ./usr/bin: comp_err mysql_config ./usr/include: mysql ./usr/include/mysql: chardefs.h m_ctype.h my_net.h mysql.h sslopt-case.h dbug.h m_string.h my_no_pthread.h mysql_version.h sslopt-longopts.h errmsg.h my_config.h my_pthread.h my_sys.h sslopt-usage.h history.h my_global.h mysql_com.h raid.h sslopt-vars.h keymaps.h my_list.h mysqld_error.h readline.h tilde.h ./usr/lib: mysql ./usr/lib/mysql: libdbug.a libmerge.a libmyisammrg.a libmystrings.a libnisam.a libheap.a libmyisam.a libmysqlclient.a libmysys.a From cappy2112 at gmail.com Thu Jun 9 13:26:06 2005 From: cappy2112 at gmail.com (Tony C) Date: Thu, 9 Jun 2005 10:26:06 -0700 Subject: Presentation for October meeting at Ironport In-Reply-To: <20050608134054.GA10909@panix.com> References: <20050608134054.GA10909@panix.com> Message-ID: <8249c4ac050609102622477048@mail.gmail.com> Tim Thompson has agreed to October at Ironport. Would someone pencil him in on the Web page? I will see if I can get a short abstract from him. If not, I've contacted Tim Thompsonhttp://nosuch.com/tjt/index.html , author of many interesting software projects, many of which are music-oriented. I've asked him if he would do a presentation on his "python-based software to do OpenGL graphics triggered by MIDI data from the drummer. See dudland.com . " -------------- next part -------------- An HTML attachment was scrubbed... URL: From rkern at ucsd.edu Mon Jun 6 10:10:56 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 06 Jun 2005 07:10:56 -0700 Subject: Destructive Windows Script In-Reply-To: <1118066666.704002.5720@g47g2000cwa.googlegroups.com> References: <1118063741.854716.183560@g14g2000cwa.googlegroups.com> <1118066666.704002.5720@g47g2000cwa.googlegroups.com> Message-ID: Michele Simionato wrote: > The problem is that Google gives me too many non-relevant hits. google("fat undelete") google("ext2 undelete") -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From simon.brunning at gmail.com Tue Jun 7 04:21:28 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 7 Jun 2005 09:21:28 +0100 Subject: SMTP help please In-Reply-To: References: Message-ID: <8c7f10c605060701213f30e562@mail.gmail.com> On 6/7/05, Ivan Shevanski wrote: > I really can't figure out anything about the SMTP module. . .I think I'm in > over my head( Im pretty new to python). Can someone show me a really(and I > mean REALLY) basic tutorial for smtp or explain it? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From philippe at philippecmartin.com Mon Jun 13 16:13:10 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 13 Jun 2005 20:13:10 GMT Subject: case/switch statement? References: <5DGqe.3570$%j7.3324@newssvr11.news.prodigy.com> <1118568352.029540.140260@o13g2000cwo.googlegroups.com> Message-ID: Any speed issue ? invalidemail at aerojockey.com wrote: > Philippe C. Martin wrote: >> Leif K-Brooks wrote: >> >> > Joe Stevenson wrote: >> >> I skimmed through the docs for Python, and I did not find anything >> >> like >> >> a case or switch statement. I assume there is one and that I just >> >> missed it. Can someone please point me to the appropriate document, >> >> or >> >> post an example? I don't relish the idea especially long if-else >> >> statements. >> > >> > If you really want one, you could use >> > . >> >> I _love_ Python! > > > Well, if you loved that, here's something even more evil. This was > Bengt Richter's original idea that Cliff Wells and I improved upon. > First define some functions and classes: > > . _cache = {} > . > . class _BaseCaseException(Exception): > . pass > . > . def switch(v): > . if v not in _cache: > . class _CaseException(_BaseCaseException): > . pass > . _cache[v] = _CaseException > . raise _cache[v] > . > . def case(v): > . if v not in _cache: > . class _CaseException(_BaseCaseException): > . pass > . _cache[v] = _CaseException > . return _cache[v] > . > . default = _BaseCaseException > > > Then you can define a switch statement like this: > > . x = 2 > . > . try: switch(x) > . > . except case(1): > . print "Case 1" > . > . except case(2): > . print "Case 2" > . > . except case(3): > . print "Case 3" > . > . except default: > . print "Default" > . > . except NameError: > . print "You can still catch regular exceptions like NameError" > > > > I-love-Python-too-but-this-isn't-why-ly yr's, > From dalke at dalkescientific.com Thu Jun 2 15:38:57 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 02 Jun 2005 19:38:57 GMT Subject: date and time range checking References: Message-ID: Maksim Kasimov wrote: > there are few of a time periods, for example: > 2005-06-08 12:30 -> 2005-06-10 15:30, > 2005-06-12 12:30 -> 2005-06-14 15:30 > > and there is some date and time value: > 2005-06-11 12:30 > what is the "pythonic" way to check is the date/time value in the given periods range? >>> import datetime >>> t1 = datetime.datetime(2005, 6, 8, 12, 30) >>> t2 = datetime.datetime(2005, 6, 10, 15, 30) >>> t = datetime.datetime(2005, 6, 9, 14, 00) >>> if t1 < t < t2: ... print "In range" ... In range >>> t = datetime.datetime(2005, 6, 8, 14, 00) >>> if t1 < t < t2: ... print "In range" ... In range >>> t = datetime.datetime(2005, 6, 7, 14, 00) >>> >>> if t1 < t < t2: ... print "In range" ... >>> If you want to use the "in" syntax >>> class InRange: ... def __init__(self, low, high): ... self.low = low ... self.high = high ... def __contains__(self, obj): ... return self.low < obj < self.high ... >>> r = InRange(t1, t2) >>> datetime.datetime(2005, 6, 7, 14, 00) in r False >>> datetime.datetime(2005, 6, 8, 14, 00) in r True >>> datetime.datetime(2005, 6, 9, 14, 00) in r True >>> datetime.datetime(2005, 6, 9, 18, 00) in r True >>> datetime.datetime(2005, 6, 10, 18, 00) in r False >>> Andrew dalke at dalkescientific.com From martin.witte at gmail.com Wed Jun 22 14:24:01 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 22 Jun 2005 11:24:01 -0700 Subject: timedelta comparision with gmtime() In-Reply-To: References: Message-ID: <1119464641.143076.298510@g47g2000cwa.googlegroups.com> martin at ubuntu:~ $ python Use now() from datetime class of datetime module instead of time module. Python 2.4.1 (#2, Mar 30 2005, 21:51:10) [GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> import datetime py> t = datetime.datetime.now() py> print t 2005-06-22 20:22:36.212142 py> d = datetime.timedelta(minutes = 2) py> print t + d 2005-06-22 20:24:36.212142 From grante at visi.com Thu Jun 16 12:44:04 2005 From: grante at visi.com (Grant Edwards) Date: Thu, 16 Jun 2005 16:44:04 -0000 Subject: 1980's Home Computer-style Package. References: Message-ID: <11b3b2kn7l1nlf2@corp.supernews.com> On 2005-06-16, Ralph Corderoy wrote: >> Wild-ass guess, but you might try googling for "turtle python". > > OK, I've done that but it didn't help; it wasn't tied in with > Turtle graphics, with which I'm familiar. Googling for '"python turtle" graphics programming' leads to http://mail.python.org/pipermail/edu-sig/2003-January/002657.html -- Grant Edwards grante Yow! Then, it's off to at RED CHINA!! visi.com From mr.jasontan at gmail.com Thu Jun 30 03:01:43 2005 From: mr.jasontan at gmail.com (jtan325) Date: 30 Jun 2005 00:01:43 -0700 Subject: python install settings... Message-ID: <1120114902.984046.239020@z14g2000cwz.googlegroups.com> hi, i am running Linux Ubuntu Hoary and am trying to build the Python numarray package, v. 1.3.2 by hand since ubuntu's repos won't be updated until breezy. i have python 2.4, and gcc 3.3.5 after unpacking the tar, i run "python setup.py install", as it says in the installation instructions. i get the following: [colfax 53] numarray-1.3.2 > python setup.py install Using EXTRA_COMPILE_ARGS = [] running install running build running build_py copying Lib/numinclude.py -> build/lib.linux-i686-2.4/numarray running build_ext Traceback (most recent call last): File "setup.py", line 222, in ? main() File "setup.py", line 213, in main setup(**p) File "/usr/lib/python2.4/distutils/core.py", line 149, in setup dist.run_commands() File "/usr/lib/python2.4/distutils/dist.py", line 946, in run_commands self.run_command(cmd) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/install.py", line 506, in run self.run_command('build') File "/usr/lib/python2.4/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/build.py", line 112, in run self.run_command(cmd_name) File "/usr/lib/python2.4/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.4/distutils/dist.py", line 966, in run_command cmd_obj.run() File "/usr/lib/python2.4/distutils/command/build_ext.py", line 254, in run customize_compiler(self.compiler) File "/usr/lib/python2.4/distutils/sysconfig.py", line 174, in customize_compiler cc_cmd = cc + ' ' + opt TypeError: cannot concatenate 'str' and 'NoneType' objects I had a similiar (but different) error earlier, but then I learned I had to set my "CC" environment variable. So I set that to "gcc". i have tried setting my "OPT" setting to something like "-g 02" (no idea what it means just found it somewhere, but it still didn't work. upon closer inspection of Python's distutils sysconfig.py, is the error being caused by the ' ' in "cc_cmd = cc + ' ' + opt"? Any ideas on this new error? Are there packages/settings I need to take care of before i can use Python's distutils to install stuff? Thanks, Jason From tjreedy at udel.edu Thu Jun 9 19:34:58 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 9 Jun 2005 19:34:58 -0400 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: "wooks" wrote in message news:1118336828.878458.202840 at z14g2000cwz.googlegroups.com... >I am somewhat nonplussed Since you reponded, I will mention a couple points of newsgroup ettiquete. First, a bare URL is or is close to being spam. It could have been spit out automatically by an seller program. It requires that readers go thru the bother of starting a browser, and possibly establishing a connection in order to decide whether they want to go to the bother of starting a browser and possibly establishing a connection. So URLs should be accompanied by the bare minimum of info needed to decide make such a decision. This applies even to posts announcing giveaways (of code, for instance). For a book, author, title, date, price (incl. shipping), and ship-from location should be about enough. Second, a person posting a sales link, even if such is allowed, should identify himself (truthfully) as the seller, a friend, or just an interested observer or reviewer. > I'm sorry if you took offence. Perhaps you have never seen a newgroup ruined by commercial announcements like I have. Terry J. Reedy From jtanis at pycoder.org Mon Jun 13 11:49:06 2005 From: jtanis at pycoder.org (James Tanis) Date: Mon, 13 Jun 2005 11:49:06 -0400 (EDT) Subject: Show current ip on Linux In-Reply-To: <42ADA78A.8030609@gmail.com> References: <42ADA78A.8030609@gmail.com> Message-ID: Previously, on Jun 13, Qiangning Hong said: # David Van Mosselbeen wrote: # > Hi, # > Im a newbie in Python, and also in Fedora Core 3. (Yes, Linux is fine # > man :-) # > # > My question is : How can i rwite a script that show my current ip. If i have # > more than one network card, the script must then show all used ip. # > # > It's important that this will work on a linux. i Have rwite some piece of # > code that realy work under Windows XP, but the same script wil not work on # > Linux. # > # > Verry thanks to all vulunteers. # > # # How about use the shell command "ifconfig | grep inet" ? # I think you mean ifconfig -a|grep 'inet ' He needs to see all the interfaces, no options will only print a help message. 'inet ' will get get rid of the inet6 addresses assuming he doesn't need those. # # -- # Qiangning Hong # # _____________________________________________________________ # ( so when I do a chroot /path /bin/bash, i can ) # ( see the processes ) # ( ) # ( outside of the chroot and i can kill those processes ) # ( * klieber claps for zhen oh go die ) # ------------------------------------------------------------- # o \_______ # v__v o \ O ) # (OO) ||----w | # (__) || || \/\ # # -- # http://mail.python.org/mailman/listinfo/python-list # --- James Tanis jtanis at pycoder.org http://pycoder.org From noreply at gcgroup.net Tue Jun 28 14:20:45 2005 From: noreply at gcgroup.net (William Gill) Date: Tue, 28 Jun 2005 18:20:45 GMT Subject: tkinter radiobutton In-Reply-To: References: Message-ID: <1ygwe.532$Ox3.193@newssvr12.news.prodigy.com> I thought the problem was practical, not philosophical, but what do I know I'm the one asking for help. I have radiobuttons arranged in 4 rows of 4 buttons each ( 4 rows and 4 columns ) The user can select no more than 1 choice in any column, but any number in any row. Restated: columns can have 0 or 1 selection rows can have 0,1,2,3, or 4 selections. Columns can be restricted to 0 or 1 selection through the use of an intVar. So we now have 4 intVars (control variables) The app needs to examine the buttons and aggregate the selections for each row, efectively converting columnar information to row information. one solution: Create 4 intVars Column0 = intVar() Column1 = intVar() Column2 = intVar() Column3 = intVar() Assign 0, 1, 2, 3 and 4 to values to correspond to the row number. Row1rb1 = Radiobutton(self, variable = Column0, value = 1) Row1rb2 = Radiobutton(self, variable = Column1, value = 1) Row1rb3 = Radiobutton(self, variable = Column2, value = 1) Row1rb4 = Radiobutton(self, variable = Column3, value = 1) Row2rb1 = Radiobutton(self, variable = Column0, value = 2) Row2rb2 = Radiobutton(self, variable = Column1, value = 2) ? ? Row4rb4 = Radiobutton(self, variable = Column3, value = 4) to 'read' the user's response: Loop through the 4 intVars 4 times; compare their value to the value for the row being processed; if they are the same bitor a value to a rowVariable i.e. convert the column information (intVar values) to row information. Bill Peter Otten wrote: > William Gill wrote: > > >>The radiobutton widget knows if it is selected or unselected, or it >>wouldn't be able to display correctly, but based on what I'm seeing, >>that information is inaccessable to the app. Instead the app must >>evaluate an associated control variable. That doesn't make sence to me, >>but even trying to look at the code for the radiobutton class didn't help. > > > I guessed you wanted to solve a practical problem, but the thoughts > expressed above suggest, err, philosophical qualms. So, for the sake of the > argument and since we both don't know the implementation details, be it in > C or TCL, let's assume that the individual radiobuttons do *not* /know/ > whether they are selected or not but instead compare their associated > 'variable' with their 'value' every time they are /asked/ to draw > themselves. That would avoid duplicate state and require only log N instead > of N bits. Wouldn't that be an elegant implementation, at least in theory? > > So why bother about the layers below when you have all the information to > write code that works? > > Peter > > From mwm at mired.org Thu Jun 23 11:38:16 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 23 Jun 2005 11:38:16 -0400 Subject: Loop until condition is true References: Message-ID: <86u0jpytg7.fsf@guru.mired.org> Stelios Xanthakis writes: > Michael Hoffman wrote: >> Stelios Xanthakis wrote: >> >>> Magnus Lycka wrote: >> > >> >>>> Right. Silly me. Maybe in some future Python version, True and False >>>> will be constants, like None is since Python 2.4. >>> >>> >>> Actually, there is support in marshal to write True and False objects so >>> I don't understand why this isn't in 2.4 >> Because it would break existing code. > > Yes. Code that has variables named 'True' and 'False'. Making None a constant broke existing code (and I just saw old code that assigned to None). Are True and False that much more common as variable names than None? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From onurb at xiludom.gro Mon Jun 13 04:30:12 2005 From: onurb at xiludom.gro (bruno modulix) Date: Mon, 13 Jun 2005 10:30:12 +0200 Subject: How to test if an object IS another object? In-Reply-To: <1118609353.934316.109870@g49g2000cwa.googlegroups.com> References: <1118604889.538762.309830@o13g2000cwo.googlegroups.com> <42ac8f0e$0$17478$636a15ce@news.free.fr> <1118607204.001609.25310@g47g2000cwa.googlegroups.com> <1118608093.758427.280220@g49g2000cwa.googlegroups.com> <1118609353.934316.109870@g49g2000cwa.googlegroups.com> Message-ID: <42ad4415$0$27145$626a14ce@news.free.fr> eloff777 at yahoo.com wrote: > > Tuples (which are immutable) also appear to be reused > > >>>>foo = () >>>>bar = () >>>>foo is bar > > True Not always: foo = (1,) bar = (1,) foo is bar => False -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tzot at sil-tec.gr Tue Jun 14 09:18:19 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 14 Jun 2005 16:18:19 +0300 Subject: sudo open() ? (python newbee question) References: <42aea8cd$0$9912$636a15ce@news.free.fr> Message-ID: On 14 Jun 2005 08:12:17 -0400, rumours say that Dan Sommers might have written: >On Tue, 14 Jun 2005 11:52:13 +0200, >Denis WERNERT wrote: > >> The script could be SUID Root, and you could use os.setuid immediately >> after having performed the task to switch to a non-priviledged >> user. May be a big security risk, if someone can alter the script, he >> gains root access to the system... >I am *not* advocating suid scripts, and *ESPECIALLY NOT* suid Python >programs, but if a user can modify an unwriteable suid script owned by >root in a an unwriteable directory, then they already have root access >to the system (unless there's' a kernel or filesystem bug, in which case >all bets are off anyway). I believe that the suid bit on scripts (either *sh or python) is completely ignored on most *nix systems. Try this in a shell (bash or ksh) as a sudo-capable user: echo hello >/tmp/tmp sudo chown root /tmp/tmp sudo chmod 600 /tmp/tmp cat >/tmp/ax.py <<@ #!/usr/bin/env python x = open("/tmp/tmp", "w") x.write("there") x.close() @ sudo chown root /tmp/ax.py sudo chmod a=rx,u+s /tmp/ax.py ls -l /tmp/ax.py /tmp/tmp /tmp/ax.py I get: -r-sr-xr-x 1 root users 75 2005-06-14 16:15 /tmp/ax.py -rw------- 1 root users 6 2005-06-14 16:15 /tmp/tmp Traceback (most recent call last): File "/tmp/ax.py", line 2, in ? x = open("/tmp/tmp", "w") IOError: [Errno 13] Permission denied: '/tmp/tmp' -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fredrik at pythonware.com Tue Jun 14 01:57:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 07:57:42 +0200 Subject: \r\n or \n notepad editor end line ??? References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com><1118238280.678863.211490@g44g2000cwa.googlegroups.com> <42ae242a@news.eftel.com> Message-ID: John Machin wrote: > Many people don't appear to want to know why; they only want a solution > to what they perceive to be their current problem. and many people can identify a short HOWTO when they see it, and look things up in the documentation when they want the full story. reposting the documentation in response to every question is, in most cases, a waste of time and bandwidth... From lee_cullens at mac.com Thu Jun 9 00:25:16 2005 From: lee_cullens at mac.com (Lee Cullens) Date: Thu, 9 Jun 2005 00:25:16 -0400 Subject: OO re-factoring (was Pythonese/Efficiency/Generalese critique [on Tutor]) In-Reply-To: References: Message-ID: <82EB5FC7-8423-4EF1-B59E-01FB5026C1BC@mac.com> Thanks for the comment Dan, Yes, that much I'm aware of. I just thought I'd refactor my little utility in an OO approach as an exercise. What I've learned so far is that my non-OO approach is in this situation very efficient, succinct and non-duplicative. Except for avoiding multiple argument passing (globals not even considered ;') there seems little to be gained. Even so, one learns best by doing and I'm gaining a better understanding of OOP (and where to apply such). The oak trees are hard on this old head though :~) Thanks again, Lee C On Jun 8, 2005, at 11:40 PM, python-list-request at python.org wrote: > Subject: Re: OO re-factoring (was Pythonese/Efficiency/Generalese > critique [on Tutor]) > > > Dan Sommers wrote: > > >> I don't remember the original post, but methods and recursion are >> *not* >> mutually exclusive (e.g., an Integer class with a factorial >> method, or a >> binary tree class whose nodes are also binary trees). >> > > Also, don't think that you have to make everything OO. > OO isn't necessarily better than non-OO. It's a means > to an end, not an end in itself. > > -- > Greg Ewing, Computer Science Dept, > University of Canterbury, > Christchurch, New Zealand > http://www.cosc.canterbury.ac.nz/~greg > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at nospam.nospam Sun Jun 12 06:54:54 2005 From: nospam at nospam.nospam (Steve Jorgensen) Date: Sun, 12 Jun 2005 03:54:54 -0700 Subject: How to get/set class attributes in Python References: Message-ID: On Sun, 12 Jun 2005 03:15:27 -0700, Steve Jorgensen wrote: ... >>Is this the "Pythonic" way of doing it or should I do it in a different >>way or do I have to use setX/getX (shudder) > >I'm totally new to Python myself, but my understanding is that ... Oops - I thought I cancelled that post when I relized I was saying nothing, but somehow, it got posted. From tjreedy at udel.edu Mon Jun 13 23:56:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Jun 2005 23:56:12 -0400 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net><3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com><1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: "Roy Smith" wrote in message news:roy-2FFE63.20274513062005 at reader1.panix.com... > Andrea Griffini wrote: >> Hehehe... a large python string is a nice idea for modelling >> memory. > > Actually, a Python string is only good for modelling ROM. If you want to > model read-write memory, you need a Python list. or array from the array module. From grante at visi.com Fri Jun 24 21:36:56 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Jun 2005 01:36:56 -0000 Subject: Newbie question: SOLVED (how to keep a socket listening), but still some questions References: Message-ID: <11bpd9on9phitad@corp.supernews.com> On 2005-06-25, Giovanni Tumiati wrote: > However some of my questions still remain from earlier post: > (1) What is the difference between > - setdefaulttimeout(timeout) That sets the timeout for any sockets created in the future. > - settimeout(value) That sets the timeout for an individual socket. > how should they be used? Use the former if you want the same timeout for all sockets. Use the latter if if you want to set them individually for each socket. Is the documentation unclear? > (2)Does one have to do a socket.shutdown() before one does a > socket.close?? No. [I've never figured out why one would do a shutdown RDWR rather than close the connection, but I haven't put a lot of thought into it.] -- Grant Edwards grante Yow! -- I love KATRINKA at because she drives a visi.com PONTIAC. We're going awaynow. I fed the cat. From fargo_01 at hotmail.com Mon Jun 13 11:24:03 2005 From: fargo_01 at hotmail.com (fargo) Date: Mon, 13 Jun 2005 17:24:03 +0200 Subject: string formatting using the % operator In-Reply-To: References: Message-ID: <42ada513$0$6082$636a15ce@news.free.fr> William Gill wrote: > I am using the % operator to create queries for a db app. It works fine > when exact strings, or numbers are used, but some queries need partial > matching that use the '%' as a wildcards. So for example the resultant > string should be 'WHERE name LIKE %smith%' (would match silversmith, > smithy, and smith). Is there any way to get something like > > searchterm = 'smith' > sql += 'WHERE name LIKE %s' % searchterm > > to return 'WHERE name LIKE %smith%' I have tried using escapes, > character codes for the % sign, and lots of other gyrations with no > success. The only thing that works is if I modify searchterm first: > > searchterm = 'smith' > searchterm ='%'+'smith'+'%' > sql += 'WHERE name LIKE %s' % searchterm > > Any Ideas? try this : sql += 'WHERE name LIKE %%%s%%' % searchterm From eric_brunel at despammed.com Thu Jun 9 03:01:15 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 09 Jun 2005 09:01:15 +0200 Subject: Fast text display? References: <7xu0k8ekm0.fsf@ruckus.brouhaha.com> <7xll5ka7mv.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 09 Jun 2005 02:22:08 +0200, Riccardo Galli wrote: > Using tkinter doesn't need downloading and installing only in Windows. > In *nix is not so common to have tcl/tk installed (and probably in Mac too) > > GUI cross platform need external support, in a OS or in another. Even if tcl/tk is not installed by default on your system, doing it is usually not a pain, since the guys making it insist on keeping its required dependencies minimal: IIRC, to install tcl/tk on any Unix, you just need to have X and a C compiler. This may be a slight advantage over most other toolkits, that usually require other libraries that you may not have installed on your system, or installed at the wrong version. I was sometimes caught in such a dependency hell when trying to install a toolkit that I eventually gave up... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])" From john106henry at hotmail.com Tue Jun 14 19:01:32 2005 From: john106henry at hotmail.com (John Henry) Date: 14 Jun 2005 16:01:32 -0700 Subject: Opening a drive folder from Python Message-ID: <1118790092.280400.54930@z14g2000cwz.googlegroups.com> Can somebody please tell me how to pop open a drive folder from a Python script? Thanks. -- John From richardlewis at fastmail.co.uk Tue Jun 14 04:31:42 2005 From: richardlewis at fastmail.co.uk (Richard Lewis) Date: Tue, 14 Jun 2005 09:31:42 +0100 Subject: windows directory Message-ID: <1118737902.7080.236313775@webmail.messagingengine.com> On Tue, 14 Jun 2005 15:32:02 +0800, "Austin" said: > I would like to write a program which creates the folders in specific > directory. > For example, I want to create folder in Program Files. How do I know > which > is in C:\ or D:\ > Is there any function to get the active path? > You can find the current working directory with os.getcwd() If you want to know where a particular directory is (on a Windows 'drive') you could use: for drive_label in ["C", "D"]: if "Program Files" in os.listdir(drive_label + ":/"): return drive_label Or something similar. Cheers, Richard From petr at tpc.cz Mon Jun 20 07:03:40 2005 From: petr at tpc.cz (McBooCzech) Date: 20 Jun 2005 04:03:40 -0700 Subject: subprocess.call(*args **kwargs) on Linux Message-ID: <1119265420.031534.29250@g49g2000cwa.googlegroups.com> Hi all, I am trying to use subprocess module on Linux/Python-2.4.1, but I can't dig throught. I need to call executable which needs two parameters to be ginven (the serial port and the file name). It looks like /root/dex/dex /dev/ttyS0 blabla.txt in the shell. This is easy. Subprocess function "call" looks: returncode = subprocess.call(["/root/dex/dex","/dev/ttyS0", "blabla.txt"]) and it runs smoothly. The problem starts when I am trying to add 1>/dev/null 2>/dev/null parameters to suppres output sendings. In the Shell it looks like: /root/dex/dex /dev/ttyS0 blabla.txt 1>/dev/null 2>/dev/null I am not able to find the propper "call" syntax to do this. Any suggestions? Thanks a lot. Petr From frankabel at tesla.cujae.edu.cu Mon Jun 6 14:48:53 2005 From: frankabel at tesla.cujae.edu.cu (Frank Abel Cancio Bello) Date: Mon, 6 Jun 2005 14:48:53 -0400 Subject: About size of Unicode string In-Reply-To: <42A48B19.5030201@geochemsource.com> Message-ID: <20050606184435.840F03182FF@newton.cujae.edu.cu> Well I will repeat the question: Can I get how many bytes have a string object independently of its encoding? Is the "len" function the right way of get it? Laci look the following code: import urllib2 request = urllib2.Request(url= 'http://localhost:6000') data = 'data to send\n'.encode('utf_8') request.add_data(data) request.add_header('content-length', str(len(data))) request.add_header('content-encoding', 'UTF-8') file = urllib2.urlopen(request) Is always true that "the size of the entity-body" is "len(data)" independently of the encoding of "data"? > -----Original Message----- > From: Laszlo Zsolt Nagy [mailto:gandalf at geochemsource.com] > Sent: Monday, June 06, 2005 1:43 PM > To: Frank Abel Cancio Bello; python-list at python.org > Subject: Re: About size of Unicode string > > Frank Abel Cancio Bello wrote: > > >Hi all! > > > >I need know the size of string object independently of its encoding. For > >example: > > > > len('123') == len('123'.encode('utf_8')) > > > >while the size of '123' object is different of the size of > >'123'.encode('utf_8') > > > >More: > >I need send in HTTP request a string. Then I need know the length of the > >string to set the header "content-length" independently of its encoding. > > > >Any idea? > > > > > This is from the RFC: > > > > > The Content-Length entity-header field indicates the size of the > > entity-body, in decimal number of OCTETs, sent to the recipient or, in > > the case of the HEAD method, the size of the entity-body that would > > have been sent had the request been a GET. > > > > Content-Length = "Content-Length" ":" 1*DIGIT > > > > > > An example is > > > > Content-Length: 3495 > > > > > > Applications SHOULD use this field to indicate the transfer-length of > > the message-body, unless this is prohibited by the rules in section > > 4.4 . > > > > Any Content-Length greater than or equal to zero is a valid value. > > Section 4.4 describes how to determine the length of a message-body if > > a Content-Length is not given. > > > Looks to me that the Content-Length header has nothing to do with the > encoding. It is a very low levet stuff. The content length is given in > OCTETs and it represents the size of the body. Clearly, it has nothing > to do with MIME/encoding etc. It is about the number of bits transferred > in the body. Try to write your unicode strings into a StringIO and take > its length.... > > Laci > > From dcrespo at gmail.com Mon Jun 20 00:14:25 2005 From: dcrespo at gmail.com (dcrespo) Date: 19 Jun 2005 21:14:25 -0700 Subject: New WYSIWYG Python IDE in the works In-Reply-To: References: Message-ID: <1119240865.711476.274520@g49g2000cwa.googlegroups.com> wxDesigner + XRCed = The best. I would like the Boa approach but with xrc exports. It would reaaaaaally be the best of the best! And don't get me wrong too, but "to be better than the competition you need to be better than the competition" - Christoph Rackwitz Daniel From martin.witte at gmail.com Thu Jun 30 07:54:53 2005 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 30 Jun 2005 04:54:53 -0700 Subject: sys.ps2 In-Reply-To: References: Message-ID: <1120132493.771305.119360@g47g2000cwa.googlegroups.com> You should be in interactive mode to see those, otherwise you get the error From lycka at carmen.se Thu Jun 23 03:47:17 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 23 Jun 2005 09:47:17 +0200 Subject: create a pdf file In-Reply-To: References: <42C7E766869C42408F0360B7BF0CBD9B014B61B4@pnlmse27.pnl.gov> Message-ID: Alberto Vera wrote: > Hello: > > I found a script that convert a file to PDF format , but it was made in PHP > > Do you know any script using Python? What do you mean by "convert a file to PDF format"? The solution obviously depends on what the file you start with looks like. If you want to create PDF yourself via API calls, ReportLab is what you need. If you want to convert an existing file in a format such as PS or MS Word, there are a lot of solutions out there, but I don't know of any Python based, and I don't see a point in using a Python based solution for that kind of task. The simplest would probably be to invoke a command line tool such as ps2pdf from your Python script. From xah at xahlee.org Tue Jun 21 18:16:56 2005 From: xah at xahlee.org (Xah Lee) Date: 21 Jun 2005 15:16:56 -0700 Subject: tree functions daily exercise: Table In-Reply-To: References: <1118613810.165265.26470@g49g2000cwa.googlegroups.com> <1118616178.259864.187180@g44g2000cwa.googlegroups.com> <1119075715.004033.169450@g14g2000cwa.googlegroups.com> <1119344080.480368.161850@o13g2000cwo.googlegroups.com> Message-ID: <1119392216.168822.314580@f14g2000cwb.googlegroups.com> Very very nice! I don't know scheme well... but oh the macros, such a wonderful facility... Functional lang never let me down. I haven't worked on a Java version yet... but i wonder what pain i'll have to endure for a lang that lacks eval. Since i'm not Java expert... i wonder if i can even do it in a few days. Xah xah at xahlee.org ? http://xahlee.org/ David Van Horn wrote: > Xah Lee wrote: > > here's the Python spec for the Table function: > ... > > References: > > > > ? for a context of this message, see: http://xahlee.org/tree/tree.htm > > Here is a Scheme implementation of Table. As noted on your web page and the > Mathematica documentation, the first argument of Table "evaluates in a > non-standard way". Thus we use Scheme macros to control the evaluation of > this expression. The first three clauses in this syntax definition take care > to fill in the default values for i, imin, and di when they are not provided. > The fourth clause iterates over one variable constructing a list. Notice > this is done tail-recursively. The last clause handles the multiple variable > case by rewriting the term into a simpler form. > > (define-syntax table > (syntax-rules () > ((table exp (imax)) > (table exp (i 1 imax 1))) > > ((table exp (i imax)) > (table exp (i 1 imax 1))) > > ((table exp (i imin imax)) > (table exp (i imin imax 1))) > > ((table exp (i imin imax di)) > (let loop ((n imin) (accum '())) > (if (< imax n) > (reverse accum) > (loop (+ n di) (cons ((lambda (i) exp) n) accum))))) > > ((table exp i j ...) > (table (table exp j ...) i)))) > > > ;; Examples > > (table #t (0)) ;; => '() > (table #t (5)) ;; => '(#t #t #t #t #t) > (table i (i 5)) ;; => '(1 2 3 4 5) > (table i (i 2 5)) ;; => '(2 3 4 5) > (table i (i 2 5 2)) ;; => '(2 4) > (table i (i 2 6 2)) ;; => '(2 4 6) > (table (add1 i) (i 2 6 2)) ;; => '(3 5 7) > (table (- i j) (i 2) (j 2)) ;; => '((0 -1) (1 0)) > > (table (list i j k) (i 2) (j 100 200 100) (k 5 6)) > ;; => > '((((1 100 5) (1 100 6)) ((1 200 5) (1 200 6))) > (((2 100 5) (2 100 6)) ((2 200 5) (2 200 6)))) From Joost.Jacob at gmail.com Tue Jun 21 10:18:15 2005 From: Joost.Jacob at gmail.com (Joost Jacob) Date: 21 Jun 2005 07:18:15 -0700 Subject: use a regex or not? Message-ID: <1119363495.274573.131630@g14g2000cwa.googlegroups.com> I am looking for a function that takes an input string and a pattern, and outputs a dictionary. # @param s str, lowercase letters # @param p str, lowercase and uppercase letters # @return dict def fill(s, p): d = {} .... return d String s has characters from the lowercase letters. String p is a pattern, a string of characters from the lowercase and uppercase letters. The idea is to match s with p, where lowercase letters have to match exactly, and to fill variables (with an uppercase letter name) with the rest of s. The variables are collected in a dictionary with the resulting bindings. A variable that occurs in more than one place in p must bind to the same substring of s. Tests: >>> fill('ab', p='aA') {'A': 'b'} >>> fill('ab', p='Ab') {'A': 'a'} >>> fill('bb', p='Ab') # no match {} >>> fill('aa', p='Aa') {'A': 'a'} >>> fill('aa', p='Ab') # no match {} >>> fill('abb', p='aA') {'A': 'bb'} >>> fill('aba', p='aAa') {'A': 'b'} >>> fill('abb', p='aAa') # no match {} >>> fill('abab', p='aAaA') # A-matches must be equal {'A': 'b'} >>> fill('abac', p='aAaA') # no match {} >>> fill('abac', p='aAaB') {'A': 'b', 'B': 'c'} Can you do it? Is trying a solution with a regex a good idea? From greg_miller at nexpress.com Tue Jun 28 12:33:49 2005 From: greg_miller at nexpress.com (Greg Miller) Date: 28 Jun 2005 09:33:49 -0700 Subject: COM problem .py versus .exe References: Message-ID: <1119976429.676707.139820@g47g2000cwa.googlegroups.com> Hello again, I put the executable on the "virgin" PC today. I am using the wmi(b) that you gave me. The error that I am receiving now is: File "autoStart.pyc", line 241, in test File "wmib.pyc", line 157, in ? File "win32com\client\__init__.pyc", line 73, in GetObject File "win32com\client\__init__.pyc", line 88, in Moniker com_error: (-2147221020, 'Invalid syntax', None, None) any thoughts on this error? Thanks again for the help. From jjl at pobox.com Tue Jun 7 19:06:13 2005 From: jjl at pobox.com (John J. Lee) Date: 07 Jun 2005 23:06:13 +0000 Subject: method = Klass.othermethod considered PITA References: <87oeallp44.fsf@pobox.com> <6qmdnR7ry4wF0D_fRVn-hA@speakeasy.net> <5bqdnUeNoYXMqz7fRVn-gw@speakeasy.net> Message-ID: <87psuxdaxm.fsf@pobox.com> Erik Max Francis writes: [...] > requesting. In my particular case, there isn't much need to make sure > things are properly overridden in subclasses, since functionality > tends to get added, rather than modified. (The "Why would you want to [...] Well done, have this gold star: *. John From reinhold-birkenfeld-nospam at wolke7.net Mon Jun 27 02:07:58 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 27 Jun 2005 08:07:58 +0200 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: <1119850812.545438.187700@g47g2000cwa.googlegroups.com> References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> Message-ID: <3i9jdvFkhd21U1@individual.net> vdavidster at gmail.com wrote: > Hi, > > Thanks for your reply! A new thing learned.... > > Allow me to follow that up with another question: > > Let's say I have a result from a module called pyparsing: > > Results1 = ['abc', 'def'] > Results2 = ['abc'] > > They are of the ParseResults type: > >>>> type(Results1) > >>>> type(Results2) > > > I want to convert them into Python lists. list() will work fine on > Results1, but on Results2, it will return: > > ['a', 'b', 'c'] > > Because 'abc' is a string. But I want it to return ['abc']. > > In short, my question is: how do I typecast an arbitrary object, > whether a list-like object or a string, into a Python list without > having Python split my strings into characters? This seems like a glitch in pyparsing. If a ParseResults class emulates a list, it should do so every time, not only if there is more than one value in it. Reinhold From ikang at MIT.EDU Sun Jun 19 21:23:54 2005 From: ikang at MIT.EDU (In Han Kang) Date: Sun, 19 Jun 2005 21:23:54 -0400 Subject: calling subclass constructor question Message-ID: <42B61AAA.10701@mit.edu> So each of the sub classes plots a different type of graph. The superclass defines methods that are the same for all the plots. I want to be able to pick some points and be able to generate a more plots. What I was wondering if I could define in a method in the superclass of an object the ability to make a brand new subclass (new plot). So basically, one plot makes another plot, but it'd be nice if i could put all the code in the superclass. Thank you again for all your thoughts and helps. From aahz at pythoncraft.com Thu Jun 9 19:51:29 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Jun 2005 16:51:29 -0700 Subject: Python Developers Handbook References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> Message-ID: In article , Lucas Raab wrote: >Terry Reedy wrote: >> >> Perhaps you have never seen a newgroup ruined by commercial announcements >> like I have. > >O wise one, we bow to you with your deep knowledge. If that's sarcasm, I suggest you reconsider your attitude. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From edvard+news at majakari.net Fri Jun 3 09:24:13 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Fri, 03 Jun 2005 16:24:13 +0300 Subject: RRArray for Python? Message-ID: <877jhb1sle.fsf@titan.staselog.com> I was wondering if there is already some 'official' module for round robin arrays. Of course, it is relatively easy to implement your own if you need it, but IMHO it feels like there should be one, because they are so general-purpose. Here's my implementation, if someone needs one. If there are enough people supporting it's release, I could add it to some static web address. """ Round-robin array module This module contains class for a round-robin array and associated round-robin array database to contain long-time spanning sample values (cf. rrdtool). Arrays can be arbitrary length, and default slot values can be defined by the user. Edvard Majakari """ class RRArrayError(Exception): pass class RRArray: """Simple round-robin class for arbitrary items""" def __init__(self, slots, default=None): """Instantiate RRArray object @param default: value to fill empty slots with >>> r = RRArray(10) # creates a round-robin array of length 10 >>> len(r) 10 """ self.default = default self._slots = slots self._array = [default]*slots self._next = 0 # points to next free index in array self._array_full = False def clear(self): """Erase array by setting all values to default fill value""" self._array = [self.default]*self._slots self._next = 0 self._array_full = False def contents(self): """Return contents of RRArray object as a list so that most recent item is the last position. >>> r = RRArray(3, 0) >>> r.contents() [0, 0, 0] >>> r.insert(2) >>> r.contents() [0, 0, 2] """ retval = self.latest(self._slots) retval.reverse() return retval def insert(self, item): """Insert an item to object >>> r = RRArray(3) >>> r.insert(42) >>> r.most_recent() == 42 and r.used_slots() == 1 True """ self._array[self._next % self._slots] = item if self._next == self._slots - 1: self._array_full = True self._next = 0 # wrap-around else: self._next += 1 def latest(self, count): """Return count most recent items Note that it is possible to receive default values which were never inserted, eg. r = RRArray(5) r.insert(2), r.latest(3) # would return [2, None, None] >>> r = RRArray(3) >>> r.insert(42) >>> r.insert(5) >>> r.insert(7) >>> r.insert(11) >>> r.latest(2) [11, 7] >>> r.contents() [5, 7, 11] """ if count > self._slots: err = "attempted to get %d items from rra of size %d" raise RRArrayError(err % (count, self._slots)) latest_idx = self._latest_index() head = self._array[0:latest_idx+1] head.reverse() if count >= len(head): tail = self._array[latest_idx+1:self._slots] tail.reverse() head.extend(tail) return head[0:count] def most_recent(self): """Return most recent item inserted. An IndexError is raised if no items have been inserted yet. """ if self._next == 0 and not self._array_full: raise IndexError("no items inserted yet") return self._array[(self._next - 1) % self._slots] def used_slots(self): """Return number of used slots.""" if self._next < self._slots and not self._array_full: return self._next else: return self._slots ### private and special methods def __len__(self): """Return number of slots in the object.""" return self._slots def _latest_index(self): return (self._next - 1) % self._slots def _test(): import doctest, rrarray doctest.testmod(rrarray) if __name__ == '__main__': _test() -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! "Debugging is twice as hard as writing the code in the firstplace. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." -- Brian W. Kernighan From fredrik at pythonware.com Wed Jun 15 15:03:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Jun 2005 21:03:21 +0200 Subject: Tkinter question References: <23B7F3E89F1D424C96B13402B5F514D3048A55F6@ntm007.apsc.com> Message-ID: Peter Otten wrote: > Change the above function to > > def callback(text=text): > self.pressed(text) argh! From fredrik at pythonware.com Tue Jun 14 12:15:17 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 18:15:17 +0200 Subject: Using httplib to read a file online References: <9D1BA87B48D4F440A0D9E371471F45A51BF741@cernxchg21.cern.ch> Message-ID: Oyvind Ostlund wrote: > There is a server called noteme.com and a file called > index.php on it, but why doesn't it work. If I changed > it to 'vbforums.com' and 'index.php' then it worked. server.putrequest('GET', filename) # send request andheaders + server.putheader('Host', servername) # identify server server.putheader('Accept', 'text/html') # POST requests workhere too server.endheaders() # as do cgi script file names From claird at lairds.us Wed Jun 22 16:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Wed, 22 Jun 2005 20:08:03 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> <3tiue.27$jv6.1568@news.uswest.net> Message-ID: In article <3tiue.27$jv6.1568 at news.uswest.net>, Dan wrote: >On 6/22/2005 1:14 PM, Dave Cook wrote: >> On 2005-06-22, Cameron Laird wrote: >> >> >>>Are you saying that Python-based applications are particularly >>>vulnerable in this all-too-common scenario? If so, I'm not >>>getting it; why is the architecture described more fragile than >>>more traditional Windows-oriented development patterns? If not, >>>then, ... well then I truly don't get your point. >> >> >> Maybe the point is the downside of depending on installed DLLs rather than >> shipping your own. >> >> Dave Cook > >Yes, DLL hell. ? OK, I'm with you part of the way. Typical "Access" developers are *always* involved with DLL hell, right? You're surely not saying that Python worsens that frustration, are you? From fredrik at pythonware.com Mon Jun 27 07:35:33 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 27 Jun 2005 13:35:33 +0200 Subject: noob question References: Message-ID: Alan Gauld wrote: > In Python Hungarian notation is meaningless since variables > aren't typed anyway. in real-life Python code, variables tend to be 'typed' in the hungarian sense: http://msdn.microsoft.com/library/en-us/dnvs600/html/hunganotat.asp "/.../ the concept of 'type' in this context is determined by the set of operations that can be applied to a quantity. The test for type equivalence is simple: could the same set of operations be meaningfully applied to the quantities in questions? If so, the types are thought to be the same. If there are operations that apply to a quantity in exclusion of others, the type of the quantity is different." From eurleif at ecritters.biz Sat Jun 18 03:04:24 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 18 Jun 2005 07:04:24 GMT Subject: Overcoming herpetophobia (or what's up w/ Python scopes)? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > The language is *always* spelt without the "a", and usually all in > lower-case: perl. The language is title-cased (Perl), but the standard interpreter is written in all lowercase (perl). Sort of like the distinction between Python and CPython. From pdemb at gazeta.pl Sun Jun 5 06:40:44 2005 From: pdemb at gazeta.pl (Peter Dembinski) Date: Sun, 05 Jun 2005 12:40:44 +0200 Subject: Scope References: <87k6laatxi.fsf@hector.domek> Message-ID: <87ll5p3x3n.fsf@hector.domek> Steven Bethard writes: > Peter Dembinski wrote: >> AFAIK inc is builtin function. And builtin functions doesn't have >> to be real functions, they can be just aliases to Python's VM >> bytecodes or sets of bytecodes. > > Wrong on both counts. ;) Yup. My mistake. [snap] > And while builtin functions may not have to be real *functions*, > they do have to be real *callables*: Yes. I discovered it yesterday. [snap] > Note that both and > have a __call__ method, which means they are callable objects. > They're not just bytecodes; they're real objects, just like > everything else in Python. =) Yup. True. -- http://www.peter.dembinski.prv.pl From skromta at gmail.com Sat Jun 18 11:34:44 2005 From: skromta at gmail.com (Kalle Anke) Date: Sat, 18 Jun 2005 17:34:44 +0200 Subject: Migrating from Windows to OS X References: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> <0001HW.BED99CB20042B4FEF0407550@news.individual.de> <1119107224.205327.127150@g49g2000cwa.googlegroups.com> Message-ID: <0001HW.BEDA0BB40052BD0BF0407550@news.individual.de> On Sat, 18 Jun 2005 17:07:04 +0200, ladasky at my-deja.com wrote (in article <1119107224.205327.127150 at g49g2000cwa.googlegroups.com>): > How are the development tools for the Mac? I'll use IDLE if it's > available, but I like Scintilla better. Don't know ... I think that MacPython is perhaps what you're looking for. Personally, I use BBEdit jem From rkern at ucsd.edu Tue Jun 28 09:18:22 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 28 Jun 2005 06:18:22 -0700 Subject: CAB files manipulation API (again). In-Reply-To: <1119963834.244244@hqnntp01.autodesk.com> References: <1119963834.244244@hqnntp01.autodesk.com> Message-ID: Isaac Rodriguez wrote: > Hi, > > I am sorry to post this question again, but when I did it the other day, my > news reader got stucked downloading new messages, and it has been that way > for a few days. It still gets stucked if I try to download old messages. Google is your friend. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e9a2237d820a4964 -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tim.golden at viacom-outdoor.co.uk Thu Jun 23 06:39:55 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Jun 2005 11:39:55 +0100 Subject: List of all installed applications (XP)? Message-ID: <9A28C052FF32734DACB0A288A3533991EBB928@vogbs009.gb.vo.local> [Guy Lateur] | I'm trying to generate a (exhaustive) list of all the | applications that are | installed on a user's machine. I've written some code that reads the | registry ('App Paths'): [.. snip code ..] | Can I be sure it lists *all* the applications? What -- from your point of view -- is an "application"? I can pretty much guarantee that by no means does every app install an AppPath: it's merely a convenience. Neither does every app have an Add/Remove Program entry. (And some things have entries which aren't apps). And where do you draw the line between some arbitrary executable and an app? Just asking, because I don't think you can do anything exhaustive until you know the scope you're trying to exhaust. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From robin at alldunn.com Sat Jun 4 19:39:03 2005 From: robin at alldunn.com (Robin Dunn) Date: Sat, 04 Jun 2005 16:39:03 -0700 Subject: No subject Message-ID: <42A23B97.6070800@alldunn.com> Announcing ---------- The 2.6.1.0 release of wxPython is now available for download at http://wxpython.org/download.php. Anybody keeping track will probably notice that the prior release (2.6.0.1) was released just about a week ago. This short turn-around time is because I was slow getting the last release done, and the wxWidgets team was uncharacteristically early with the 2.6.1 release! This release consists of a few bug fixes made since 2.6.0.1. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK or GTK2, and Mac OS X. Changes in 2.6.1.0 ------------------ wx.ListCtrl: patch #1210352, fixes editing in generic wx.ListCtrl with wx.LC_EDIT_LABELS. Applied patch #208286, MediaCtrl DirectShow rewrite. DocView patches from Morgan Hua: bug fixes, and additional SVN commands, also added a default template that uses the text editor for any unknown file type. wxMSW: Use the system IDC_HAND cursor for wx.CURSOR_HAND and only fallback to the strange wxWidgets version if the system one is not available. wx.grid.Grid: Merge the cell size attribute the same way that other attributes are merged, e.g., if it is already set to a non-default value in the current GridCellAttr object then don't merge from the other. wx.lib.evtmgr: Fixed to use wx._core._wxPyDeadObject wx.lib.gridmovers: Don't scroll when the mouse is dragged outside of the grid, unless the mouse is kept in motion. wxMSW: Applied patch #1213290 incorrect logic in wx.TopLevelWindow.ShowFullScreen. Applied patch #1213066 correct device names for Joystick in Linux. wxGTK: Applied patch #1207162 wx.TextCtrl.SetStyle fix for overlapping calls. wx.FileConfig: fixed DeleteEntry to set the dirty flag properly so the change will get written at the next flush. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From alexrait1 at yahoo.com Fri Jun 10 15:40:26 2005 From: alexrait1 at yahoo.com (alexandr) Date: Fri, 10 Jun 2005 19:40:26 -0000 Subject: using python from c/c++ Message-ID: Is it possible to create a library from my python module that can be used from c/c++ application? From eprint10108 at yahoo.com Wed Jun 1 20:23:05 2005 From: eprint10108 at yahoo.com (eprint10108 at yahoo.com) Date: 1 Jun 2005 17:23:05 -0700 Subject: * * * Please Read And/Or Print This! * * * Press [Ctrl][P] Keys On Your Keyboard To Print >> June 1, 2004 8:23:43 pm >> http://115639.aceboard.net/forum2.php?rub=158&cat=61&login=115639&page=0#id96 << * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Message-ID: <1117671785.262410.76790@o13g2000cwo.googlegroups.com> * * * Please Read And/Or Print This! * * * Press [Ctrl][P] Keys On Your Keyboard To Print >> June 1, 2004 8:23:46 pm >> http://115639.aceboard.net/forum2.php?rub=158&cat=61&login=115639&page=0#id96 << * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * From kent37 at tds.net Tue Jun 7 20:56:39 2005 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Jun 2005 20:56:39 -0400 Subject: Binary numbers In-Reply-To: References: Message-ID: <42a641f8$1_2@newspeer2.tds.net> Douglas Soares de Andrade wrote: > Hi ! > > How to work with binary numbers in python ? Is there a way to print a number > in its binary form like we do with oct() or hex() ? This is a popular topic in the Python Cookbook, maybe one of these recipes will suit you: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65212 Kent From harold.fellermann at upf.edu Tue Jun 28 14:56:13 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 28 Jun 2005 20:56:13 +0200 Subject: I need help figuring out how to fix this code. In-Reply-To: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: Hi, > I need help figuring out how to fix my code. I'm using Python 2.2.3, > and > it keeps telling me invalid syntax in the if name == "Nathan" line. The problem is that you indent the if statement. the if/elif/else statements are part of the outer block, so they do not need indentation. > Here is the code if you need it. > #This program asks for a password, then asks for the user's name > after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" name = raw_input("What is your name, plase? ") if name == "Nathan" : print "What a great name!" elif name in ["Madonna","Cher"] : # in better than == here :) print "May I have your autograph please!" else : # don't forget the ":" print name, ", thats a nice name!" cheers, - harold - -- You can imagine the opposite -- Maurizio Nannucci From fredrik at pythonware.com Mon Jun 13 05:53:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Jun 2005 11:53:25 +0200 Subject: \r\n or \n notepad editor end line ??? References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Message-ID: wrote: > It means in windows we should use 'wb' to write and 'rb' to read ? > Am I right? no. you should use "wb" to write *binary* files, and "rb" to read *binary* files. if you're working with *text* files (that is, files that contain lines of text separated by line separators), you should use "w" and "r" instead, and treat a single "\n" as the line separator. From skip at pobox.com Wed Jun 1 23:26:48 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Jun 2005 22:26:48 -0500 Subject: anygui,anydb, any opinions? In-Reply-To: References: <5uGdnfiX3aSnRADfRVn-1Q@telcove.net> <7xzmu94wrf.fsf@ruckus.brouhaha.com> Message-ID: <17054.31864.979895.403269@montanaro.dyndns.org> >> Are we talking about a drag-and-drop GUI builder? Thomas> I am! >> What about Glade? Thomas> Dying to try that. Ask me again in a week. I use Glade at work on a regular basis. Took me a few days to get proficient, and it has some warts, but it sure beats the heck out of manually creating all those widgets in my Python code. Skip From guy at NOSPAM.r-e-d.co.nz Fri Jun 24 08:05:54 2005 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Sat, 25 Jun 2005 00:05:54 +1200 Subject: howto load and unload a module In-Reply-To: References: Message-ID: > > Why would you want to? Doing what you describe doesn't require that you > "unload" a module, unless that means something more to you than, say, > merely releasing the memory used by it (which is likely insignificant to > you). > Hi Peter, I have an application with Python embedded. I'm parsing a script directory to build a dictionary of script names with descriptions of what the scripts etc extracted from each script. The user then selects one of these scripts to execute by the embedded python. Some of these scripts could potentially be quite large. Also the list of scripts could be quite large. So the main reason for unloading modules is to save memory. Regards, Guy From theller at python.net Mon Jun 27 14:12:51 2005 From: theller at python.net (Thomas Heller) Date: Mon, 27 Jun 2005 20:12:51 +0200 Subject: Modules for inclusion in standard library? References: <3ian37Fkjle0U1@individual.net> Message-ID: Reinhold Birkenfeld writes: > Hello, > > at the moment python-dev is discussing including Jason Orendorff's path module > into the standard library. I have never used the path module before, although I've heard good things about it. But, it seems to have problems with unicode pathnames, at least on windows: C:\>mkdir sp?m C:\sp?m>py24 Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from path import path >>> path.getcwd() Traceback (most recent call last): File "", line 1, in ? File "C:\TSS5\components\_Pythonlib\path.py", line 97, in getcwd return path(os.getcwd()) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 5: ordinal not in range(128) >>> Although it seems this could be fixed by adding this constructor to the path class: def __new__(cls, init=u""): if isinstance(init, unicode): return _base.__new__(cls, init) return _base.__new__(cls, init, sys.getfilesystemencoding()) I would really appreciate if Python's unicode support would be better ;-), and maybe it's easier to add this to the path module than to os.path. Thomas From hancock at anansispaceworks.com Mon Jun 13 14:28:34 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 13 Jun 2005 13:28:34 -0500 Subject: Dealing with marketing types... In-Reply-To: <4pOdncP8_6NTEDDfRVn-jQ@telcove.net> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <4pOdncP8_6NTEDDfRVn-jQ@telcove.net> Message-ID: <200506131328.34335.hancock@anansispaceworks.com> On Monday 13 June 2005 08:46 am, Thomas Bartkus wrote: > "Steve Jorgensen" wrote in message > news:cr3oa11uutgn2et585r8q85i5s7o6kelli at 4ax.com... > > On Sat, 11 Jun 2005 11:51:02 -0500, tom wrote: > > > > ... > > >Let me add an Item #3 - > > >If you have some entrepeneurial savvy and can keep your emotions out of > > >it tou can simply tell them you have decided strike out on your own and > > >tell them that you will be available. They will be happy to hear you are > > >leaving and happier still to hear you can be available for backup. > > >Their goals and fears are addressed at the same time. AND there is a > very > > >high possibility that they will *need* you at a later date for which you > > >can charge them dearly. > > > > > >That last item #3 has actually worked for me with (2) prior employers. > > >I did have to eat my indignation and keep it friendly but it did pay off > > >in the end. > > >Thomas Bartkus > > > > I have to say that, although I have yet to write a line of Python code for > > money, I've found that this concept basically works. When you realize > that > > your employer is cutting you out to save the cost of paying you, funny > enough, > > they'll be willing to -really- pay you as a consultant later when they get > > stuck, and one or more paying customers are impacted. > > Yup! It's theold stupid + greedy double whammy that means they end up paying > more. > Your not feeling sorry for them, are you? > > > They also win't mind > > figuring out how to have you come in after hours so it won't conflict with > > your new day job if you have one. In my case, the work was in VB/VBA, but > the > > same principle should apply to any technology. > > > > Do make sure that your contract with any new employer allows you to do at > > least small amounts of moonlighting - they probably won't object. They > will > > insist that any moonlighting shall not compete with their line of > business, > > and you should agree to that stipulation. > > How much of *my* time are they buying with a salary? 40Hrs a week? 24/7 ? > You want to see that your contract as an employee doesn't somehow forbid you > from earning extra on your own time. Unless, of course, they are paying > enough to make you happy to sell them *all* your time. Sometimes you are > hired mainly to keep your skills unavailable to their competitors. Thats ok > as long as they pay you enough to keep you happy with this. Unless they are > paying for it, your own free time is none of their business. You might be interested to know that California state law forbids anti-moonlighting clauses, provided that no company resources are used by the employee in the conduct of their own business (which means of course, you'd better not take your business calls at work). Not sure how many other jurisdictions have implemented something like this, but it sounds like a very good thing to me. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From steve at REMOVETHIScyber.com.au Wed Jun 8 19:18:45 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 09 Jun 2005 09:18:45 +1000 Subject: Annoying behaviour of the != operator References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118251198.426673.108180@g49g2000cwa.googlegroups.com> Message-ID: On Wed, 08 Jun 2005 11:01:27 -0700, Mahesh wrote: > No, why should Python assume that if you use != without supplying a > __ne__ that this is what you want? Without direction it will compare > the two objects which is the default behavior. Why should Python assume that != means "not is" instead of "not equal"? That seems like an especially perverse choice given that the operator is actually called "not equal". > So, s != t is True because the ids of the two objects are different. > The same applies to, for example s > t and s < t. Do you want Python to > be smart and deduce that you want to compare one variable within the > object if you don't create __gt__ and __lt__? I do not want Python to > do that. That is an incorrect analogy. The original poster doesn't want Python to guess which attribute to do comparisons by. He wants "!=" to be defined as "not equal" if not explicitly overridden with a __ne__ method. If there are no comparison methods defined, then and only then does it make sense for == and != to implicitly test object identity. I'm all for the ability to override the default behaviour. But surely sensible and intuitive defaults are important? -- Steven From __peter__ at web.de Sat Jun 25 15:37:38 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 25 Jun 2005 21:37:38 +0200 Subject: Big problem fetching members from dynamically loaded module References: Message-ID: Philippe C. Martin wrote: > l?=?inspect.getmembers(eval('BC'))?#THIS?CRASHES?-?the?class?exists Care to provide the traceback? > In [23]:from SC.CARDS.BC import * > > In [24]:l = inspect.getmembers(eval('BC')) What happened in lines 1 through 22? My guess would be In [13]:from SC.CARDS import * Be that as is may, eval("BC") can be simplified to BC, from module import * is the last roadhouse en route to chaos and an unqualified try ... except shows you are willing to drive with defunct brakes. By introducing exec and eval() you are throwing the steering wheel out of the window. Seriously, try to make do with __import__() and getattr() to clean up your code a bit. Driving-analogies-well-beyond-the-abyss-ly yours Peter From bokr at oz.net Sun Jun 26 18:15:37 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 22:15:37 GMT Subject: Favorite non-python language trick? References: <42bdcd82.194023771@news.oz.net> Message-ID: <42bf201e.280707125@news.oz.net> On Sun, 26 Jun 2005 14:30:15 +1000, Steven D'Aprano wrote: >On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote: > [...] >> >> The single line replacing >> """ >> with colour do begin >> red := 0; blue := 255; green := 0; >> end; >> """ >> follows: >> >>> vars(color).update(red=0, blue=255, green=0) > > >The point is that a hypothetical "with" block would have to allow >arbitrary access to dotted names: getting, setting, deletion, and method >calling, not just one very limited form of keyword assignment. Point taken. > >I understand how to manipulate __dict__ as an more complicated (dare I say >obfuscated?) way of assigning to object attributes. > Yes, it's a bit obfuscated. > >[snip] > >> We can clear those attributes from the instance dict: >>>>> vars(colour).clear() >>>>> vars(colour) >> {} > >Which has the unfortunate side effect of also destroying any other >instance attributes. You wouldn't do something unfortunate, would you? ;-) I just wanted to clear them all at that point in the interaction. > > >>>you might do this: >>> >>>with myobject: >>> # read a class attribute >>> print .__class__.myattribute >>> # set an instance attribute >>> .widget.datapoints[.collector] = .dispatcher(.widget.current_value) >>> >> >> def mywith(o=myobject): >> # read a class attribute >> print o.__class__.myattribute >> # set an instance attribute >> o.widget.datapoints[o.collector] = o.dispatcher(o.widget.current_value) >> mywith() > >[snip] > >> Is a one-character prefix to the dot objectionable? > >That's a good workaround, subject to namespace pollution issues, and one >that I'm aware of. Although do you really want to be creating a unique >function definition every time you want to use the with idiom? The only thing, ISTM, that would not also be unique in the with construct is the function name, and you snipped the anonymnous def version that would eliminate that. The main question in my mind would be binding of non-leading-dot names. Would they work as in the suite of an "if" (i.e., binding in the same scope) or as in a function with a new local scope that disappears on exit? A function solves the alias name pollution problem, but prevents rebinding anything external except explicitly declared globals, and closure cell vars can't be rebound currently. > >I'm not about to stop using Python because of the lack of Pascal-like >"with" blocks. It is a nice feature to have, but I'm aware that Guido >prefers explicit to implicit and "with" is extremely implicit. > I wonder what happens when you have multiple withs, e.g., with obj_a: .x = 1 with obj_b: .x = 2 .y = 3 (I guess you would have to have a stack with only the latest with effective). whereas a simple aliasing syntax like (a=obj_a, b=obj_b): a.x = 1 b.x = 2 b.y = 3 is unambigous and concise and the scope of the namescan be limited to prevent name pollution at compile time. OTOH, what should (a=obj_a): a = 123 # XXX ?? mean? Should it mean obj_a=123 and rebind in that scope, like a macro substitution of names at compile time? I guess the corresponding with thing would be with obj_a: . = 123 Regards, Bengt Richter From mwm at idiom.com Mon Jun 20 19:19:00 2005 From: mwm at idiom.com (Mike Meyer) Date: 20 Jun 2005 16:19:00 -0700 Subject: What is different with Python ? References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <86ekb713hy.fsf@guru.mired.org> <86mzpuzqyq.fsf@guru.mired.org> <1s8sa1pii8k86ff4lktego0s03rs9qhilk@4ax.com> <863brlzmy9.fsf@guru.mired.org> <86ekb4y5ut.fsf@guru.mired.org> Message-ID: <5jvf48liqj.fsf@idiom.com> Andrea Griffini writes: > On Tue, 14 Jun 2005 16:40:42 -0500, Mike Meyer wrote: > > >Um, you didn't do the translation right. > > Whoops. > > So you know assembler, no other possibility as it's such > a complex language that unless someone already knows it > (and in the specific architecture) what i wrote is pure > line noise. > > You studied it after python, I suppose. Nope. I don't think I've learned any assemblers since I learned Python. Of course, I'd been writing code for 20 years before I learned Python. > >> or, even more concrete and like what I learned first > >> > >> lda $300 > >> clc > >> adc $301 > >> sta $302 > >> > >> is simpler to understand. > > > >No, it isn't - because you have to worry about more details. > > In assembler details are simply more explicit. Unfortunately > with computers you just cannot avoid details, otherwise your > programs will suck bad. When I wrote in an high level language > or even a very high level one the details are understood even > if I'm not writing down them. After a while a programmer will > even be able to put them at a subconscius level and e.g. by > just looking at O(N^2) code that could be easily rewritten as > O(N) or O(1) a little bell will ring in you brain telling you > "this is ugly". But you cannot know if something is O(1) or > O(N) or O(N^2) unless you know some detail. If you don't like > details then programming is just not the correct field. I've never argued otherwise. > Think that "a = b + c" in computes the sum of two real > numbers and your program will fail (expecting, how fool, > that adding ten times 0.1 you get 1.0) and you'll spend > some time wondering why the plane crashed... your code > was "correct" after all. Especially if b and c aren't floats. I've always used "real" as a mathematical term, since they had it first. Computers don't deal with reals. > >For instance, whitesmith had a z80 assembler that let you write: > > > > a = b + c > > > >and it would generate the proper instructions via direct > >translation. > > To use that I've to understand what registers will be > affected and how ugly (i.e. inefficient) the code could > get. Programmin in assembler using such an high level > feature without knowing those little details woul be > just suicidal. The assembler lets you specify which registers to use. You either name them in place of variables, or variables that are labels for the registers. > >> But saying for example that > >> > >> del v[0] > >> > >> just "removes the first element from v" you will end up > >> with programs that do that in a stupid way, actually you > >> can easily get unusable programs, and programmers that > >> go around saying "python is slow" for that reason. > > > >That's an implementation detail. It's true in Python, but isn't > >necessarily true in other languages. > > Yeah. And you must know which is which. Otherwise you'll > write programs that just do not give the expected result > (because the user killed them earlier). Actually, it isn't always true in Python. What if v is a dictionary (in which case the description is wrong), or a class that maps an SQL table's row id's to objects holding the data for that row? In either case, the statement will be O(1). You do need to know which is which. > >Yes, good programmers need to know that information - or, > >as I said before, they need to know that they need to know > >that information, and where to get it. > > I think that a *decent* programmer must understand if the > code being written is roughly O(n) or O(n^2). Without > at least that the possibility of writing useful code, > excluding may be toy projects, is a flat zero. > Looking that information later may be just "too" late, > because the wrong data structure has already been used > and nothing can be done (except rewriting everything). I don't think those two statements contradict each other. A decent programmer will know the O() of the code they write - or where to find that information. And they'll check it beforehand. The advantage of using an HLL is that rewriting everything to try other data structures (after all, the constants that O() notation ignore matter as well, so that the fastest O() notation may not be the fastest solution for the problem in hand). > >That may well be true of the standard C++ library - I don't write > >it. But it certainly doesn't appear to be true of, for instance, > >Python internals. I've never seen someone explain why, for instance, > >string addition is O(n^2) beyond the very abstract "it creates a new > >string with each addition". No concrete details at all. > The problem is that unless you really internalized what > that means you'll forget about it. Don't ask me why, > but it happens. Our mind works that way. You just cannot > live with a jillion of unrelated details you cannot place > in a scheme. It doesn't work. One would do thousand times > the effort that would be done using instead a model able > to justify those details. Again, you're generalizing from "your mind" to "everyone's mind". My experience indicates that's not true for me. For instance, I find that learning a typical assembler involves learning a jillion unrelated details - because it's not at all uncommon for the opcode mnemonics to be seemingly random strings of characters. Or random words. Architectures with irregular register usages seem to have little rhyme or reason behind those irregularities (though I did avoid those architectures, so may have missed the reason(s) behind some of them). Even on architectures with symmetric register usage, register usage conventions are pretty much arbitrary. > >> The problem with designing top down is that when > >> building (for example applications) there is no top. > > > >This is simply false. The top of an application is the > >application-level object > > Except that the marketing will continuosly shift what > you application is supposed to do. And this is good, and > essential. This is "building". Sometimes marketing will > change specifications *before* you complete the very > first prototype. For complex enough projects this is more > the rule than the exception. In the nice "the pragmatic > programmer" book (IIRC) is told that there's no known > complex project in which specification was changed less > than four times before the first release... and the only > time they were changed just three times it was when the > guy running with the fourth variations was hit by a > lightning on the street. Except that those specification changes rarely change the top-level object/method/whatever. At least, all the ones I dealt with wound up changing things that were in the middle of the design. The easiest ones were the ones that were anticipated, and so the changes were all in data, and not in code. > >> Unfortunately sometimes there > >> is the OPPOSITE problem... we infer general rules > >> that do not apply from just too few observations. > > > >Your opposite problem is avoided by not teaching the details until > >they are needed, and making sure you teach that those are > >implementation details, so they student knows not to draw such > >conclusions from them. > > What you will obtain is that people that will build > wrong models. Omitting details, if they can really > affect the result, is not a good idea. Well, the "result" largely depends on why the project is being built. If you're doing exploratory programming, the "result" is a better understanding of the objects in the problem domain. The details that affect that result are radically different from the details that affect the result if you're building a production application, which is again different from the details that affect the result if you're teaching people how to program. Again, the critical thing is teaching students what details matter, and which ones don't. > >>>The critical things a good programmer knows about those > >>>concrete details is which ones are platform specific and which aren't, > >>>and how to go about learning those details when they go to a new > >>>platform. > >> > >> I never observed this problem. You really did ? > > > >As mentioned, you see it all the time in c.l.python. People come from > >other languages, and try to write Python as if the rules for that > >other language apply. > > That's exactly because they don't know the details of > any of the languages you used. Someone knowing the > details would be curious to know *how* "del v[0]" > is implemented in python. Actually it could be changed > easily in an O(1) operation with just a little slowdown > in element access (still O(1) but with a bigger constant). > This is a compromise that has not been accepted and > this very fact is important to know if you plan to > use python seriously. Actually, you don't need to know *anything* about the compromise if you plan on using python seriously. You do need to know that "del v[0]" on list is O(n). > >It can be fixed from the start by teaching the student the difference > >between abstract programming concepts and implementation details. > > Sorry, but I really don't agree that big O is a "detail" > that could be ignored. Only bubble-and-arrow powerpoint > gurus could think that; I'm not in that crew. > Ignore those little details and your program will be > just as good as ones that don't even compile. I've never argued that you should treat O() behavior as a detail that can be ignored. I've argued that it's an implementation detail. As such, you worry about it when you do the implmentation. If you need to delete from both ends of an ordered set of objects, you can't use a python list and get reasonable performance. > >It tackled abstract problems like "sorting". The students I'm talking > >about never dealt with anything that abstract. > Sorting is abstract ? Yeah. Remember, I'm talking about m.e., chem.e, etc. engineering students here. Not software engineers or any other type of cs types. > >> Pairing this with that teaching > >> abelian groups first to kids (why not fiber spaces then ?) > >> and that TAOCP is too "abstract" tells me that apparently > >> you're someone that likes to talk just for talking, or > >> that your religion doesn't allow you to type in smileys. > > > >Now you're resorting to straw men and name-calling. That's an > >indication that you no longer have any real points. > > I'll blame my bad english for understanding that you If you wish. But since you posted your list of misconceptions about what I said, I'm going to correct them. > said that abelian groups should be taught before > relative numbers (somehow I crazily thought the point > of discussion was what's the correct order of learning > how to program), Again, I never said that. I said *I* understood them better than relative numbers, because *you* asked whether or not I did. That says *nothing* about how I think they should be taught. I'm not so egotistical as to think that every body thinks they same way I do. > that TAOCP is too abstract (a book > where every single code listing is in assembler!) I said it was too abstract for a specific group - one that deals with concrete problems. In FORTRAN, usually. > and that big-o when programming is a detail that can > be safely ignored (good luck, IMO you'll need hell a > lot of it). No, I said it was an implementation detail. I've maintained all along that good programmers need to know those details. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From future_retro at yahoo.co.uk Thu Jun 23 08:39:40 2005 From: future_retro at yahoo.co.uk (future_retro at yahoo.co.uk) Date: 23 Jun 2005 05:39:40 -0700 Subject: python create WMI instances In-Reply-To: References: Message-ID: <1119530380.024970.75810@z14g2000cwz.googlegroups.com> I've got as far as this. I don't get any errors but still no printer???? >>> import win32com.client >>> WBEM = win32com.client.GetObject(r"winmgmts:{impersonationLevel=impersonate}!\\" + "." + r"\root\cimv2") >>> printer = WBEM.Get("Win32_Printer").SpawnInstance_() >>> printer.Properties_('DeviceID').Value = 'myprinter' >>> printer.Properties_('DriverName').Value = 'HP 2000C' >>> printer.Properties_('Location').Value = 'myoffice' >>> printer.Properties_('Network').Value = 'True' >>> printer.Properties_('Shared').Value = 'True' >>> printer.Properties_('ShareName').Value = 'myprintershare' >>> printer.Put_ Do I need to specify any flags with Put_ ? Thanks for all your help, I can almost taste victory! MW. Tim Golden wrote: > [future_retro at yahoo.co.uk] > | Win32_Printer doesn't work with the Create method and > | AddPrinterConnection only lets me add a connection to a share. I'll > | try and work out how to set the printer object properties in > | the format > | suggested; > | > | oPrinter.Properties_ ("DriverName").Value = strDriver > | > | Cheers, MW. > > I'm sorry my module won't have been much use to you > in this, but it would be *really* helpful if you > could post [a fragment of] the code you come up with > so I can see what changes I need to make to help our > future instance-spawners. It's just that I've never > had the need to do this, and don't have any time to > experiment at present. > > Thanks > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From danb_83 at yahoo.com Tue Jun 7 20:34:41 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 7 Jun 2005 17:34:41 -0700 Subject: Binary numbers References: Message-ID: <1118190881.484857.122970@f14g2000cwb.googlegroups.com> Douglas Soares de Andrade wrote: > Hi ! > > How to work with binary numbers in python ? Is there a way to print a number > in its binary form like we do with oct() or hex() ? > > Im doing a project that i have to work with binaries and i tired of convert > numbers to string all the time to perform some operations. > > I searched about it in many places like python.org and google, but not found > anything useful. Search for "itoa". From benji at benjiyork.com Tue Jun 21 08:33:46 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 21 Jun 2005 08:33:46 -0400 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <42B8092A.5060003@benjiyork.com> Cyril BAZIN wrote: > Another question could be: why is there not a statement "whileTrue" or > "loop"? I don't think the saving of a single space to transform "while True:" into "WhileTrue:" is really worth it. The same goes for "loop", the added complexity to the language (as little as it is) isn't rewarded by a large enough improvement to make it worth it. > It could be an economy of one unuseful test by loop. If by "economy" you mean "optimization", then I would suggest that the difference would be unnoticeable. -- Benji York From gry at ll.mit.edu Thu Jun 23 12:48:34 2005 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 23 Jun 2005 09:48:34 -0700 Subject: suggestions invited In-Reply-To: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> Message-ID: <1119545314.216605.305340@z14g2000cwz.googlegroups.com> Aditi wrote: > hi all...i m a software engg. student completed my 2nd yr...i have been > asked to make a project during these summer vacations...and hereby i > would like to invite some ideas bout the design and implementation of > an APPLICATION MONITORING SYSTEM....i have to start from scrach so > please tell me how to go bout it rite from the beggining this is the > first time i m making a project of this complexity... > i have to make a system used by the IT department of a company which > contains 31 applications and their details which are being used in a > company ...the details are... > Application sub application catagory platform language version IT > owner functional owner remarks source code documentation last updated > dates > i want to design a system such that it lets the it employee enter the > name of the application and gives him all the details about it...please > suggest an appropriate design and the language which you think would be > best to use...as i have enouf time with me and i can learn a new > language as well...i currently know c and c++...your advise is welcomed > Aditi I suggest you first learn a bit of python: go to www.python.org and download/install the current release; go through the online tutorial: http://docs.python.org/tut/tut.html . Then you might look at xml as a means for storing the data. Xml is structured, readable without special software(very helpful for debugging), and easy to use for simple data. Try the xml module from http://pyxml.sourceforge.net/topics/download.html [look at the demos for simple usage] Don't be intimidated by complex formal definitions of XML, what you need is not hard to use. -- George From skip at pobox.com Tue Jun 14 08:41:18 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 14 Jun 2005 07:41:18 -0500 Subject: Resume after exception In-Reply-To: References: Message-ID: <17070.53358.455506.983815@montanaro.dyndns.org> >> Is it possible to have an 'except' case which passes control back to >> the point after the exception occurred? Peter> Basically no, although I could imagine some gross hack with the Peter> frame info and some bytecode hacks that effect a "goto". Someone (I forget who) posted an autoload module (appended) awhile ago for Python that does a reasonable job of recovery in the case of use-before-import. I modified it slightly and use it on my laptop. Examples: % python Python 2.5a0 (#77, May 14 2005, 14:47:06) [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> time.time() found time in xmlrpclib module 1118752288.5277729 >>> datetime.datetime.now() found datetime in xmlrpclib module datetime.datetime(2005, 6, 14, 7, 31, 43, 136432) >>> math.sin(7) autoloading math 0.65698659871878906 Note that it's far from perfect (to wit: the weird fact that "time" and "datetime" are found in the xmlrpclib module). Skip -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/octet-stream Size: 1637 bytes Desc: not available URL: From roy at panix.com Sun Jun 26 08:37:51 2005 From: roy at panix.com (Roy Smith) Date: Sun, 26 Jun 2005 08:37:51 -0400 Subject: Favorite non-python language trick? References: Message-ID: Steven D'Aprano wrote: > Using := and = for assignment and equality is precisely as stupid as using > = and == for assignment and equality. On the other hand, == is easier to type than := (two taps on the same key vs two different keys, and at least on a US/English keyboard, no shift key required). Not only that, but := is more likely to be turned into some bizarre smiley face by brain-dead IM clients :-) From wuwei23 at gmail.com Wed Jun 1 23:23:41 2005 From: wuwei23 at gmail.com (alex23) Date: 1 Jun 2005 20:23:41 -0700 Subject: any macro-like construct/technique/trick? References: <1117665421.812299.82040@o13g2000cwo.googlegroups.com> Message-ID: <1117682621.608102.317300@f14g2000cwb.googlegroups.com> Mac wrote: > * using > def debug_emit(obj): > if debug: > emit_dbg_obj(obj) > is a poor solution, because it *always* instantiates DbgObj*, even when > not needed; I want to avoid such unnecessary waste Rather than passing in an instantiated object and only operating on it if the debug flag is set, how about passing in the class & initialisation parameters and only creating the object if necessary? >>> def debug_emit(cls, args): ... if debug: emit_dbg_obj(cls(*args)) Then your calls will just be a single line: >>> debug_emit(DbgObjFoo,(a,b,c)) Does that help at all? -alex23 From tprimke at interia.pl Fri Jun 24 05:04:35 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jun 2005 02:04:35 -0700 Subject: A tool for Python - request for some advice References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> <5jvf464maf.fsf@idiom.com> Message-ID: <1119603875.247425.158910@g47g2000cwa.googlegroups.com> > (...) I've seen the claim that every Linux > distro comes with Python installed, but can't verify it. So have I. And I think it might be truth. The only problem is that different distros might be released with different versions of Python. > Then again, the same comments apply to bash. Distributions that have > their roots in AT&T Unix probably don't come with bash by default, > with Mac OS X being an exception. This makes depending on bash a bad > idea if you want to write a script that portable across Unix distros. Good to know. So my script written in bash will be primary targeted for Linux distros. OK, I can live with that. > If your target platform is Linux, indications are that python is as > portable as bash. I've thought about it for a few days and I disagree with you. Python isn't as portable as bash because of one reason. The problem is that development of Python is much more dynamic than development of bash. If I wrote my script in Python it would be possible that this script wouldn't run on the same distro with _different_ version of Python. (This is problem because someone has sugested that he'd like to run this script on RH 9. So older distros must be considered as well as newer.) As long as I'm using bash, I'll deal with a tool that has the same features on different distros (well... _almost_ the same features) (This is about portability, of course. There are also another advantages of using bash.) > If your target platform is Unix, then the same is true - except you > shouldn't be writing bash if you want portability. Well, my primary goal is Linux. I'm working on Linux and I have no access to any *BSD system (or another flavour of Unix). I thought that bash scripts are portable, but now I can see I was wrong. Thanks for all your help. From peter at engcorp.com Tue Jun 21 08:13:47 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 21 Jun 2005 08:13:47 -0400 Subject: eval() in python In-Reply-To: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> References: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > the doc seems to suggest that eval is only for expressions... it says > uses exec for statements, but i don't seem to see a exec function? Because it's a statement: http://docs.python.org/ref/exec.html#l2h-563 From grobinson at goombah.com Wed Jun 1 23:10:09 2005 From: grobinson at goombah.com (Gary Robinson) Date: Wed, 1 Jun 2005 23:10:09 -0400 Subject: dictionaries and threads Message-ID: <20050601231009.396072.becbe514@goombah.com> Hi, I know the Global Interpreter Lock ensures that only one python thread has access to the interpreter at a time, which prevents a lot of situations where one thread might step on another's toes. But I'd like to ask about a specific situation just to be sure I understand things relative to some code I'm writing. I've got a dictionary which is accessed by several threads at the same time (that is, to the extent that the GIL allows). The thing is, however, no two threads will ever be accessing the same dictionary items at the same time. In fact the thread's ID from thread.get_ident() is the key to the dictionary; a thread only modifies items corresponding to its own thread ID. A thread will be adding an item with its ID when it's created, and deleting it before it exits, and modifying the item's value in the meantime. As far as I can tell, if the Python bytecodes that cause dictionary modifications are atomic, then there should be no problem. But I don't know that they are because I haven't looked at the bytecodes. Any feedback on this would be appreciated. For various reasons, we're still using Python 2.3 for the time being. Gary -- Gary Robinson CTO Emergent Music, LLC grobinson at goombah.com 207-942-3463 Company: http://www.goombah.com Blog: http://www.garyrobinson.net From pwatson at redlinepy.com Sun Jun 19 23:57:13 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Sun, 19 Jun 2005 22:57:13 -0500 Subject: Using print with format to stdout generates unwanted space Message-ID: <3hmt4rFhnn89U1@individual.net> #!/usr/bin/env python # Using a print statement to stdout results in an # unwanted space character being generated at the # end of each print output. Same results on # DOS/Windows and AIX. # # I need precise control over the bytes that are # produced. Why is print doing this? # import sys # If this is a DOS/Windows platform, then put stdout # into binary mode so that only the UNIX compatible newline # will be generated. # try: import msvcrt, os msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) except: print 'This is not an msvcrt platform.' pass # Using print with newline suppressed generates a space at the # end of each print statement. # for i in range(3): print '%d,60,' % (i), for j in range(10): print '%d,' % (j), print '' # Using a list and doing a join does not result in the space # character being generated. # for i in range(3): alist = [] alist.append('%d,60,' % (i)) for j in range(10): alist.append('%d,' % (j)) print ''.join(alist) sys.exit(0) From no.spam Fri Jun 24 12:45:27 2005 From: no.spam (Christophe Delord) Date: Fri, 24 Jun 2005 18:45:27 +0200 Subject: Two questions on lambda: References: Message-ID: <20050624184527.03e38d0e.no.spam@box> hello, On Fri, 24 Jun 2005 14:48:16 +0200, Xavier D?coret wrote: > Hi, > > In the same spirit, how can I do to compute intermediary values in the > > body of a lambda function. Let's say (dummy example): > > f = lambda x : y=x*x,y+y > > > In languages like Caml, you can do: > > let f = function x -> let y=x*x in y+y;; > > Does the lambda : syntax in python allow for the same kind of > constructs? You can define another lambda function with a default value for the y parameter. For instance: f = lambda x: (lambda y=x*x: y+y)() > > Thanks. From be_veronic at yahoo.com Wed Jun 8 09:30:51 2005 From: be_veronic at yahoo.com (Veronica Tomescu) Date: Wed, 8 Jun 2005 06:30:51 -0700 (PDT) Subject: windows processes Message-ID: <20050608133051.29804.qmail@web32502.mail.mud.yahoo.com> I am using Trent's process.py but I have a problem with killing the processes in windows. For example : import process,time p=process.ProcessOpen('C:\Program Files\Windows Media Player\wmplayer') time.sleep(3) p.kill() will start Media Player without terminating it. Any suggestions? Thanks in advance. Veronica --------------------------------- Discover Yahoo! Find restaurants, movies, travel & more fun for the weekend. Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: From mandus at gmail.com Wed Jun 29 07:44:02 2005 From: mandus at gmail.com (Mandus) Date: Wed, 29 Jun 2005 11:44:02 +0000 (UTC) Subject: map vs. list-comprehension References: <42c27238$0$26269$626a14ce@news.free.fr> Message-ID: 29 Jun 2005 10:04:40 GMT skrev F. Petitjean: > Le Wed, 29 Jun 2005 09:46:15 +0000 (UTC), Mandus a ?crit : >> Hi there, >> >> inspired by a recent thread where the end of reduce/map/lambda in Python was >> discussed, I looked over some of my maps, and tried to convert them to >> list-comprehensions. >> >> This one I am not sure how to conver: >> >> Given three tuples of length n, b,i and d, I now do: >> >> map(lambda bb,ii,dd: bb+ii*dd,b,i,d) >> >> which gives a list of length n. > > res = [ bb+ii*dd for bb,ii,dd in zip(b,i,d) ] aha - thanks! I wasn't aware of zip. Guess I have to put python in a nutshell on my nightstand (again) :-) seem to be a tad slower than the map, but nothing serious. Guess it's the extra zip. > > Hoping that zip will not be deprecated. hopefully not... -- Mandus - the only mandus around. From lycka at carmen.se Thu Jun 30 08:40:09 2005 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 30 Jun 2005 14:40:09 +0200 Subject: Add methods to string objects. In-Reply-To: <2fdabf19.0506300201.5fb56b59@posting.google.com> References: <2fdabf19.0506300201.5fb56b59@posting.google.com> Message-ID: <42C3E829.9010709@carmen.se> Negroup wrote: > Hi all. > I'm writing a simple Python module containing functions to process > strings in various ways. Actually it works importing the module that > contains the function I'm interested in, and calling > my_module.my_function('mystring'). > > I was just asking if it is possible to "extend" string objects' > behaviour so that it becomes possible to invoke something like > 'anystring'.my_method(). The proper way is to extend the string type by subclassing it: class S(str): def my_method(self): ... Then you can do "S('anystring').my_method()" etc. Example: >>> class S(str): ... def lowers(self): ... return filter(lambda x:x!=x.upper(), self) ... def uppers(self): ... return filter(lambda x:x!=x.lower(), self) ... >>> s = S('Hello World!') >>> print s.uppers() HW >>> print s.lowers() elloorld This means that your additional behaviour isn't available to plain string literals. You need to instanciate S objects. This is much less confusing for other programmers who read your code (or for yourself when you read it a few years from now). From wookiz at hotmail.com Fri Jun 10 04:01:02 2005 From: wookiz at hotmail.com (wooks) Date: 10 Jun 2005 01:01:02 -0700 Subject: Python Developers Handbook In-Reply-To: References: <1118318436.192627.320820@g49g2000cwa.googlegroups.com> <1118336828.878458.202840@z14g2000cwz.googlegroups.com> <7xk6l33r2j.fsf@ruckus.brouhaha.com> <1118372596.003161.290690@g49g2000cwa.googlegroups.com> Message-ID: <1118390462.698504.43650@z14g2000cwz.googlegroups.com> If I had posted or invited the group to look at my full list of items rather than just the python book link then I could see where you are coming from. If my intention was to "spam" this NG then the complaints as they were phrased would only have served to make me more determined. Maybe we will all learn something from each other. From roccomoretti at hotpop.com Thu Jun 23 09:37:26 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 23 Jun 2005 08:37:26 -0500 Subject: how to use more than 1 __init__ constructor in a class ? In-Reply-To: References: <42b99d7b$0$21804$626a14ce@news.free.fr> Message-ID: Steven D'Aprano wrote: > On Wed, 22 Jun 2005 12:34:21 -0500, Rocco Moretti wrote: > > >>You could also turn __init__ into a dispatch fuction: >> >>#-- >>class myPointClass: >> def __init__(self, *args): >> if len(args) <= 2: >> self.__init_two(*args) >> if len(args) == 3: >> self.__init_three(*args) > > > Oh wow, so that's what I've been doing for years. Dispatching. > > And I thought I was just calling other functions :-) I think the distinction between just calling other functions and dispatching is that with dispatching, the function doesn't do any actual work by itself, but just hands off the work to a different function. http://www.c2.com/cgi/wiki?DispatchingForDummies > That's the joys of a mostly self-taught programming knowledge: you miss > out on all the buzzwords. Being mostly self taught myself, I have a tendancy to use infrequently encountered terms in related but technically inappropriate contexts, confusing the better informed people I deal with. ;-) From hancock at anansispaceworks.com Thu Jun 9 23:58:17 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 9 Jun 2005 22:58:17 -0500 Subject: Any way to not create .pyc files? In-Reply-To: <1118350114.634141.95920@g49g2000cwa.googlegroups.com> References: <1118337243.321804.284910@g14g2000cwa.googlegroups.com> <8cGdnaHABLhlEzXfRVn-oQ@powergate.ca> <1118350114.634141.95920@g49g2000cwa.googlegroups.com> Message-ID: <200506092258.17437.hancock@anansispaceworks.com> On Thursday 09 June 2005 03:48 pm, Lonnie Princehouse wrote: > At one point last week, users started reporting that they were > encountering problems running our Python application (the one that uses > the package on the network drive). The admins noticed that lots of > .pyc files had been inadvertantly created when someone with write > access had run the application. The admins deleted all of the .pyc > files, and users were once again able to run the application. > I suspect this hadn't come up before because very few people have write > access, and those who do are not usually users. I don't know the > nature of the problems encountered. Well, if most users are using an older version of Python, but the user with write access was using a new version, I can see this happening. The user with write access would run the script, causing the pyc files to be generated for that interpreter. Then a normal user, running an older Python tries to load the modules. Since a .pyc file exists, it gets used instead, but *oops* it's for a later version of the interpreter and stuff breaks. A better solution than getting rid of the pyc files would be to put good ones there --- use the version of python that users are expected to be using and generate them. If you delete the pyc files, you create an unnecessary drag on performance and the hazard remains to mess you up again. If the pyc files are generated, though, I *think* they will be used and work for both the expected python and (fingers crossed) the later version. If the later version doesn't work, your "unusual" person with write access ought to be smart enough to use the right version, right? It's the usual user you should be designing for. I hope I'm not totally off-base here --- I've had relatively little experience with mixed versions and pyc files, so my assumptions may be a little off, but hopefully someone will correct me if that's so. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From listserver at tdw.net Wed Jun 22 06:28:40 2005 From: listserver at tdw.net (Tim Williams) Date: Wed, 22 Jun 2005 11:28:40 +0100 Subject: need to strip stuff off email References: <11bhc9u7925cv38@news.supernews.com> <003701c5770f$855f7e90$ccbefea9@twilliams> Message-ID: <006901c57715$31d3a660$ccbefea9@twilliams> ----- Original Message ----- From: "Tim Williams" To: Sent: Wednesday, June 22, 2005 10:48 AM Subject: Re: need to strip stuff off email > > > > "nephish" wrote in message > > news:mailman.723.1119399951.10512.python-list at python.org... > > > hey there, > > > i have a script that retrieves my email, but i need it to > > > be able to strip all the stuff off except the body (the message itself) > > > so i can later write it to a text file. > > > > > > anyone know how to accomplish this? > > > thanks > > The body is: The rest of the email after "the first blank line after the > subject header". In practice it is the first blank line. > > If you get the message into a string it can sometimes be easier to just > RSPLIT the string at '\r\n\r\n', if the message is in a list then the body > = '\r\n'.join(msg[x:]) where x = that blank line +1 , that way if you > don't need any of the header info, you don't have to decode the message and > rebuild it in a file. > > if you *are* using the email module, eg > > msg = email.message_from_file(a_file) > > then rsplit the msg to get the same result. > > As someone will no doubt point out, some emails are broken and parts of > the headers will end up in the body (even when you view the email it in a > client), this is very rare though. Ah, trying to do anything before my first cup of coffee in the morning is always a mistake - substitute RSPLIT with LSPLIT for both occurrences above !!! :( From benji at benjiyork.com Thu Jun 30 10:49:25 2005 From: benji at benjiyork.com (Benji York) Date: Thu, 30 Jun 2005 10:49:25 -0400 Subject: When someone from Britain speaks, Americans hear a "British accent"... In-Reply-To: <1120141667.753928.40750@f14g2000cwb.googlegroups.com> References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <1120141667.753928.40750@f14g2000cwb.googlegroups.com> Message-ID: <42C40675.4050101@benjiyork.com> Graham Fawcett wrote: > keep-your-stick-on-the-ice'ly yours, Is that a Red Green reference? Man, I didn't think this could get any more off-topic. :) python-needs-more-duct-tape'ly yours, Benji From cpunerd4 at gmail.com Sat Jun 18 09:50:44 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 06:50:44 -0700 Subject: extreme newbie In-Reply-To: <11b88ier7jled7@corp.supernews.com> References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <11b88ier7jled7@corp.supernews.com> Message-ID: <1119102644.048879.258100@g47g2000cwa.googlegroups.com> what is this py2exe thing? I think its what i've been looking for...(and inno setup was in my plans (or maby null soft installer...)). Another reason I was thinging java was because you can run it in the browser. Is py2exe included? Where can I find it? thanks, cpunerd4 From gene.tani at gmail.com Thu Jun 30 19:25:30 2005 From: gene.tani at gmail.com (gene tani) Date: 30 Jun 2005 16:25:30 -0700 Subject: Seeking IDE In-Reply-To: <42c4592d$0$7668$636a15ce@news.free.fr> References: <42c4592d$0$7668$636a15ce@news.free.fr> Message-ID: <1120173930.372352.79820@g43g2000cwa.googlegroups.com> I encourage NOPs (non-original posters) to paste their thoughts into the wiki for posterity/FAQing, e.g. currently no info on synEdit: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments From Sivakumar.Bhaskarapanditha at abaqus.com Thu Jun 30 14:21:46 2005 From: Sivakumar.Bhaskarapanditha at abaqus.com (Sivakumar Bhaskarapanditha) Date: Thu, 30 Jun 2005 14:21:46 -0400 Subject: %g and fpformat.sci() Message-ID: <20050630182144.BFFBD37466@postoffice.hks.com> Hi, How can I control the number of digits after the decimal point using the %g format specifier. I am not able to get more than 3 digits as shown below. >>> a = 1.234e-5 >>> '%g' % a '1.234e-005' >>> '%.2g' % a '1.2e-005' >>> '%.4g' % a '1.234e-005' >>> '%.5g' % a '1.234e-005' >>> '%.6g' % a '1.234e-005' >>> '%.7g' % a '1.234e-005' >>> import fpformat >>> fpformat.sci(a,7) '1.2340000e-005' >>> In the above example there are only 3 digits after decimal. If I set a=1.234567e-8 I can control part of it but I am trying to find a way of filling the rest with zeros as given by the fpformat. Ofcourse I can use the fpformat or do some checks. But is there any direct way (I need a something that doesn't affect performance). Thanks a bunch for your help. Regards, Siva -------------- next part -------------- An HTML attachment was scrubbed... URL: From gijs at globaltrack.com Thu Jun 2 03:50:48 2005 From: gijs at globaltrack.com (Gijs Korremans) Date: Thu, 2 Jun 2005 09:50:48 +0200 Subject: pointers in com object functions Message-ID: <200506020754.j527smLp006472@rrba-146-94-166.telkomadsl.co.za> Hi, One of the functions in the com object I need to use has a pointer in one of it's functions (object.function(string input, struct * output)) I've tried to use the id() function but then Python gives me a message that it's an int, not a tructure and when I just give the object without a pointer, the object is still empty afterwards. I've created the struct with win32com.client.Record("structure", object) Kind regards, Gijs -- This message has been scanned for viruses and dangerous content by Network Sentry, and is believed to be clean. http://www.networksentry.co.za From steven.bethard at gmail.com Wed Jun 29 20:50:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Jun 2005 18:50:40 -0600 Subject: aligning text with space-normalized text Message-ID: I have a string with a bunch of whitespace in it, and a series of chunks of that string whose indices I need to find. However, the chunks have been whitespace-normalized, so that multiple spaces and newlines have been converted to single spaces as if by ' '.join(chunk.split()). Some example data to clarify my problem: py> text = """\ ... aaa bb ccc ... dd eee. fff gggg ... hh i. ... jjj kk. ... """ py> chunks = ['aaa bb', 'ccc dd eee.', 'fff gggg hh i.', 'jjj', 'kk.'] Note that the original "text" has a variety of whitespace between words, but the corresponding "chunks" have only single space characters between "words". I'm looking for the indices of each chunk, so for this example, I'd like: py> result = [(3, 10), (11, 22), (24, 40), (44, 47), (48, 51)] Note that the indices correspond to the *original* text so that the substrings in the given spans include the irregular whitespace: py> for s, e in result: ... print repr(text[s:e]) ... 'aaa bb' 'ccc\ndd eee.' 'fff gggg\nhh i.' 'jjj' 'kk.' I'm trying to write code to produce the indices. Here's what I have: py> def get_indices(text, chunks): ... chunks = iter(chunks) ... chunk = None ... for text_index, c in enumerate(text): ... if c.isspace(): ... continue ... if chunk is None: ... chunk = chunks.next().replace(' ', '') ... chunk_start = text_index ... chunk_index = 0 ... if c != chunk[chunk_index]: ... raise Exception('unmatched: %r %r' % ... (c, chunk[chunk_index])) ... else: ... chunk_index += 1 ... if chunk_index == len(chunk): ... yield chunk_start, text_index + 1 ... chunk = None ... And it appears to work: py> list(get_indices(text, chunks)) [(3, 10), (11, 22), (24, 40), (44, 47), (48, 51)] py> list(get_indices(text, chunks)) == result True But it seems somewhat inelegant. Can anyone see an easier/cleaner/more Pythonic way[1] of writing this code? Thanks in advance, STeVe [1] Yes, I'm aware that these are subjective terms. I'm looking for subjectively "better" solutions. ;) From bwallis at NoSpAm.fathen.net Fri Jun 10 19:12:21 2005 From: bwallis at NoSpAm.fathen.net (Brian Wallis) Date: Sat, 11 Jun 2005 09:12:21 +1000 Subject: Saving/retrieving user preferences References: <42a78012@dnews.tpgi.com.au> <42a7e05c@dnews.tpgi.com.au> Message-ID: <42aa1e55@dnews.tpgi.com.au> Brian Wallis wrote: > I want to save user preferences, window sizes, recently opened file names, > etc for a python application and I am looking for a package that does this > in a way that is portable across unix/linux and windows (and mac would be > nice as well). Thank you all for the replies. I have a few options to try now. I'm using wxPython so might investigate wxConfigBase for a start. thansks, -- brian... From alexs at advfn.com Sat Jun 4 20:02:50 2005 From: alexs at advfn.com (Alex Stapleton) Date: Sun, 5 Jun 2005 01:02:50 +0100 Subject: Sorted List (binary tree) why no built-in/module? Message-ID: <7AA3576E-AE6E-4C0D-AF69-253B28968646@advfn.com> Unless I've totally missed it, there isn't a binary tree/sorted list type arrangement in Python. Is there a particular reason for this? Sometimes it might be preferable over using a list and calling list.sort() all the time ;) On a somewhat unrelated note, does anyone know how python searches lists when you do things list list.index(n), is it a binary search, or does it just scan the list? From steve at REMOVETHIScyber.com.au Sun Jun 26 00:36:42 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 14:36:42 +1000 Subject: Rebindings [was Re: Favorite non-python language trick?] References: <42bdcd82.194023771@news.oz.net> Message-ID: On Sat, 25 Jun 2005 23:08:10 +0000, Bengt Richter wrote: >>Using := and = for assignment and equality is precisely as stupid as using >>= and == for assignment and equality. Perhaps less stupid: why do we use >>== for equals, but not ++ for plus and -- for minus? >> > I agree, but I think := would be nice in python for RE-binding an existing > binding, wherever it is seen from the local context. Thus you could > write > > def foo(): x:=123 > > and > x = 456 > def bar(): > x = 789 > foo() # finds and rebinds local x > print x > bar() # -> 123 > print x # -> 456 > foo() # finds and rebinds the global x > print x # -> 123 > > but > del x > foo() #-> NameError exception, can't find any x to rebind > > hm, wandered a bit OT there, ;-/ Given how much the use of global variables are discouraged, is it a good idea to allow even more inter-namespace interactions? -- Steven. From gregpinero at gmail.com Wed Jun 15 21:00:27 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Wed, 15 Jun 2005 21:00:27 -0400 Subject: MySQLDBAPI In-Reply-To: <312cfe2b05061419583bdeab0b@mail.gmail.com> References: <2tqln2-6c3.ln1@news.interplanet.it> <312cfe2b05061408481a3e7de0@mail.gmail.com> <3h939qFfvmjfU1@uni-berlin.de> <312cfe2b05061419302497dd6@mail.gmail.com> <312cfe2b05061419337d104ce6@mail.gmail.com> <312cfe2b05061419583bdeab0b@mail.gmail.com> Message-ID: <312cfe2b0506151800111eb83@mail.gmail.com> Ok, I finally got it working! I just did these two commands: $export mysqlclient=mysqlclient $export mysqlstatic=True Thanks for all the help everyone. -Greg On 6/14/05, Gregory Pi?ero wrote: > One other note, the few searches I've made that seem somewhat relevant > talk about turning off something thread-safe? Is this something I can > try even though I have very limited permissions on the server? > > > On 6/14/05, Gregory Pi?ero wrote: > > Here's a list of all the files from the RPM extraction, maybe that helps too? > > > > > > [gpinero at intel1 rpmmysql]$ dir -R > > .: > > usr > > > > ./usr: > > bin include lib > > > > ./usr/bin: > > comp_err mysql_config > > > > ./usr/include: > > mysql > > > > ./usr/include/mysql: > > chardefs.h m_ctype.h my_net.h mysql.h sslopt-case.h > > dbug.h m_string.h my_no_pthread.h mysql_version.h sslopt-longopts.h > > errmsg.h my_config.h my_pthread.h my_sys.h sslopt-usage.h > > history.h my_global.h mysql_com.h raid.h sslopt-vars.h > > keymaps.h my_list.h mysqld_error.h readline.h tilde.h > > > > ./usr/lib: > > mysql > > > > ./usr/lib/mysql: > > libdbug.a libmerge.a libmyisammrg.a libmystrings.a libnisam.a > > libheap.a libmyisam.a libmysqlclient.a libmysys.a > > > From giles_brown at hotmail.com Fri Jun 3 03:51:02 2005 From: giles_brown at hotmail.com (Giles Brown) Date: 3 Jun 2005 00:51:02 -0700 Subject: odbc and python In-Reply-To: References: Message-ID: <1117785062.654497.192330@g44g2000cwa.googlegroups.com> MM wrote: > Are there any other odbc packages other than the win32all and mxodbc > ones? The win32all odbc.pyd can't access table structure info like > SQLColumns, and mxobdc requires a commercial license which is > unjustifiable for this tiny project. Any other OS alternatives for > win32?. Thanks. You could potentially make the ODBC calls using ctypes a la: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303667 Not tried this myself and imagine it could be a bit tedious. Cheers, Giles From cpunerd4 at gmail.com Sat Jun 18 08:23:20 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 05:23:20 -0700 Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> Message-ID: <1119097400.061145.247190@z14g2000cwz.googlegroups.com> thanks all for the advice. The reason I was thinking about using java (or C or something) was that it is a little more secure than distributing the source code isn't it? And also, from what I know, the Java virtual machine is more popular (and installed on more computers). Although it might take me awhile to get to that stage. once again thanks for your advice. The Dive into Python book looks promising. cpunerd4 From rrr at ronadam.com Tue Jun 14 00:09:19 2005 From: rrr at ronadam.com (Ron Adam) Date: Tue, 14 Jun 2005 04:09:19 GMT Subject: "also" to balance "else" ? In-Reply-To: <11asi5cps42vfe5@news.supernews.com> References: <11asi5cps42vfe5@news.supernews.com> Message-ID: John Roth wrote: > > "Ron Adam" wrote in message > news:H6pre.131217$IO.122689 at tornado.tampabay.rr.com... > >> Currently the else block in a for loop gets executed if the loop is >> completed, which seems backwards to me. I would expect the else to >> complete if the loop was broken out of. That seems more constant with >> if's else block executing when if's condition is false. > > > Actually, it makes sense if you look at it correctly. > > In an unadorned loop, exits via break and via the > loop condition becoming false go to the same place. > To distinguish requires some kind of a switch. > > In a loop with an else, exits via break skip the else > clause, while an exit via the loop condition takes > the else clause. You don't need a special exit on > break since you can put any amount of logic after > the if and in front of the break. Where you need it > is on exit via the loop condition. > > The difficulty you're having with this is that else > is a very bad keyword for this particular construct. > I'd prefer something like "on normal exit" as > a keyword. It's not a difficulty. This is the point I was making. :) My suggestion is to use, also as the keyword to mean "on normal exit" 'also' do this. Ron From tzot at sil-tec.gr Wed Jun 22 08:02:15 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 22 Jun 2005 15:02:15 +0300 Subject: getting an object name References: Message-ID: <5mkib1lukd7ouc6mdpmqdi73klils4bhjg@4ax.com> On Wed, 22 Jun 2005 09:00:23 +0100, rumours say that Simon Brunning might have written: >> Let's say I have a list called, alist. If I pass alist to a function, >> how can I get the name of it? > >The effbot put it beautifully: And IMO it should be in the FAQ: (http://www.python.org/doc/faq/general.html) "How do I get the name of an object?" >"The same way as you get the name of that cat you found on your porch: >the cat (object) itself cannot tell you its name, and it doesn't >really care -- so the only way to find out what it's called is to ask >all your neighbours (namespaces) if it's their cat (object) ... and >don't be surprised if you'll find that it's known by many names, or no >name at all!" Whom should we bug to add it? -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From nicola-mingotti at libero.it Wed Jun 15 21:28:58 2005 From: nicola-mingotti at libero.it (Nicola Mingotti) Date: Thu, 16 Jun 2005 01:28:58 +0000 Subject: splitting delimited strings References: Message-ID: On Wed, 15 Jun 2005 23:03:55 +0000, Mark Harrison wrote: > What's the most efficient way to process this? Failing all > else I will split the string into characters and use a FSM, > but it seems that's not very pythonesqe. like this ? >>> s = "@hello at world@@foo at bar" >>> s.split("@") ['', 'hello', 'world', '', 'foo', 'bar'] >>> s2 = "hello at world@@foo at bar" >>> s2 'hello at world@@foo at bar' >>> s2.split("@") ['hello', 'world', '', 'foo', 'bar'] >>> bye From projecktzero at yahoo.com Tue Jun 28 09:52:44 2005 From: projecktzero at yahoo.com (projecktzero) Date: 28 Jun 2005 06:52:44 -0700 Subject: Getting binary data out of a postgre database In-Reply-To: <3ib8eeFkler1U1@uni-berlin.de> References: <1119636233.488038.170240@z14g2000cwz.googlegroups.com> <3i320qFjktsjU2@uni-berlin.de> <1119878398.854244.132830@z14g2000cwz.googlegroups.com> <3ib8eeFkler1U1@uni-berlin.de> Message-ID: <1119966764.415895.162330@g43g2000cwa.googlegroups.com> whew! tempFile.write(str(rec[0])) works! printing rec[0].__class__ puts out pyPgSQL.PgSQL.PgBytea Thanks for the help! From fredrik at pythonware.com Wed Jun 15 04:57:30 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Jun 2005 10:57:30 +0200 Subject: "also" to balance "else" ? References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> Message-ID: Ron Adam wrote: > So the (my) confusion comes from the tendency to look at it in terms of > overall program flow rather than in terms of the specific conditional > logic. > > In a for loop the normal, as in terminating normally, behavior of a loop > is one where the loop test evaluates as 'False' ending the loop. And > the abnormal or counter behavior is when a break statement executes. > Thus the 'else' block is the normal result, and the skipping the 'else' > block becomes the abnormal counter behavior. a typical use-case for for-in-else is a search loop: for item in collection: if predicate(item): print "found", item break else: print "not found" return print "use", item where your "abnormal behaviour" is, of course, the expected behaviour. if you insist on looking at things the wrong way, things will look reversed. From kkylheku at gmail.com Tue Jun 21 01:49:43 2005 From: kkylheku at gmail.com (Kaz Kylheku) Date: 20 Jun 2005 22:49:43 -0700 Subject: references/addrresses in imperative languages In-Reply-To: <11bf5ln27f0qf6f@corp.supernews.com> References: <1119323217.670985.68250@o13g2000cwo.googlegroups.com> <11bf5ln27f0qf6f@corp.supernews.com> Message-ID: <1119332983.836246.155450@g14g2000cwa.googlegroups.com> SM Ryan wrote: > "Kaz Kylheku" wrote: > # SM Ryan wrote: > # > # easy way to see this, is to ask yourself: how come in mathematics > # > # there's no such thing as "addresses/pointers/references". > # > > # > The whole point of Goedelisation was to add to name/value references into > # > number theory. > # > # Is that so? That implies that there is some table where you can > # associate names (or whatever type of locators: call them pointers, > # whatever) with arbitrary values. But in fact that's not the case. > > Do you really believe the Goedel number of a statement is the statement > itself? Is everything named Kaz the same as you? The Goedel number is a representation of the statement in a way that the name Kaz isn't a representation of me. You cannot identify parts of the name Kaz with parts of me; there is no isomorphism there at all. I am not the translated image of the name Kaz, nor vice versa. A Goedel number isn't anything like a name or pointer. It's an encoding of the actual typographic ``source code'' of the expression. There is nothing external to refer to other than the encoding scheme, which isn't particular to any given Goedel number. The encoding scheme is shallow, like a record player; it doesn't contribute a significant amount of context. If I decode a Goedel number, I won't have the impression that the formula was hidden in the numbering scheme, and the Goedel number simply triggered it out like a pointer. No, it will be clear that each piece of the resulting formula is the direct image of some feature of the Goedel number. From cravephi at hotmail.com Thu Jun 2 09:35:23 2005 From: cravephi at hotmail.com (cravephi at hotmail.com) Date: 2 Jun 2005 06:35:23 -0700 Subject: wxpython or PyQT to make a simulink clone ? In-Reply-To: <873bs1xgot.fsf@smtp.gsi.de> References: <1117699017.376196.37930@f14g2000cwb.googlegroups.com> <873bs1xgot.fsf@smtp.gsi.de> Message-ID: <1117719323.507641.67870@g14g2000cwa.googlegroups.com> thank you, I checked viper, but the license is not so simple.. I am testing your truffaldino ! seems interesting, but I could not launch it. I am running: Python 2.3 wxpython 2.6 (for python 2.3) I installed mtalib, Truffaldino, Smeraldina and nodenet. Also installed DSV and pygsl-0.3.1_Numeric.win32-py2.3.exe Then, I launch /smeraldina/gui/wxsmeraldina but, nothing .. I do not have error messages. it could import all the modules. Can you please help me ? From trentm at ActiveState.com Tue Jun 28 22:10:08 2005 From: trentm at ActiveState.com (Trent Mick) Date: Tue, 28 Jun 2005 19:10:08 -0700 Subject: How to find Windows "Application data" directory?? In-Reply-To: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> References: <7xslz27yj2.fsf_-_@ruckus.brouhaha.com> Message-ID: <20050629021008.GA16099@ActiveState.com> [Paul Rubin wrote] > I'm writing a Windows program that needs to store some user files. > > The logical place to store them is in "Application Data", right? > > Is there a good way to find the correct location of that directory, > preferably without any C extensions? It's ok if the directory is > found at installation time rather than runtime, and bdist_wininst does > have a way to find it from a post-installation script. The trouble is > that the post-installation script doesn't seem to have an obvious way > to communicate the info to the application for later use! > > Any suggestions? The canonical way is using the Window API SHGetFolderPath function with the CSIDL_APPDATA key: from win32com.shell import shellcon, shell print shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0) This requires the PyWin32 extensions (which you already have if you have ActivePython installed). Alternatively you could write your own little C extension to call this Window API function... but you didn't want to do that. You can also call this WIndows API function (in the shell32.dll) with the Python "ctypes" modules out there. Trent -- Trent Mick TrentM at ActiveState.com From pwatson at redlinepy.com Thu Jun 23 02:19:11 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Thu, 23 Jun 2005 01:19:11 -0500 Subject: os.system(cmd) isn't working References: Message-ID: <3hv2j3Fit96kU1@individual.net> "Gregory Pi?ero" wrote in message news:mailman.787.1119499378.10512.python-list at python.org... Hi guys, I'm trying to run this statement: os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' "www.blendedtechnologies.com"') The goal is to have firefox open to that website. When I type r'"C:\Program Files\Mozilla Firefox\firefox.exe"' + ' "www.blendedtechnologies.com"' in the python interpreter I get: '"C:\\Program Files\\Mozilla Firefox\\firefox.exe" "www.blendedtechnologies.com"' And when I copy this into my command prompt (less outermost ' ) firefox opens up to that page like I would expect. However in python nothing happens and I get exit status 1. I'm using Python 2.3 on Windows XP pro service pack 2. I'd greatly appriciate any help. Thanks, Greg =============== These seemed to work on one machine for Python 2.1 and 2.4. >>> os.system('\"C:/Program Files/Mozilla Firefox/firefox.exe\" >>> http://www.blendedtechnologies.com/') 1 >>> os.system('\"C:\\Program Files\\Mozilla Firefox\\firefox.exe\" >>> http://www.blendedtechnologies.com/') 1 >>> os.system(r'"C:\Program Files\Mozilla Firefox\firefox.exe" >>> http://www.blendedtechnologies.com/') 1 From tiissa at nonfree.fr Sat Jun 4 09:31:56 2005 From: tiissa at nonfree.fr (tiissa) Date: Sat, 04 Jun 2005 15:31:56 +0200 Subject: If - Or statements In-Reply-To: References: <42A16BBE.4080301@mailshack.com> <42A170C2.7000608@ucsd.edu> Message-ID: <42a1ad4b$0$30683$626a14ce@news.free.fr> Ognjen Bezanov wrote: > ext = thefile.split('.') #get the file extension > ext[1] = ext[1].lower() #convert to lowercase As a side note, ext[1] will be the first extension: >>> 'foo.bar.ogg'.split('.')[1] 'bar' I'd advise ext[-1], the last element of the splitted list. >>> 'foo.bar.ogg'.split('.')[-1] 'ogg' From cookedm+news at physics.mcmaster.ca Wed Jun 8 12:52:25 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 08 Jun 2005 12:52:25 -0400 Subject: computer algebra packages References: <1118184041.459969.257190@g49g2000cwa.googlegroups.com> <1118209749.248567.168700@g49g2000cwa.googlegroups.com> <1118233766.928467.261650@z14g2000cwz.googlegroups.com> Message-ID: Fernando Perez writes: > Rahul wrote: > >> Hi. >> The reason is simple enough. I plan to do some academic research >> related to computer algebra for which i need some package which i can >> call as a library. Since i am not going to use the package >> myself..(rather my program will)..it will be helpful to have a python >> package since i wanted to write the thing in python. if none is >> available then probably i will need to work on an interface to some >> package written in some other language or work in that language itself. > > I've heard of people writing a Python MathLink interface to Mathematica, which > essentially turns Mathematica into a Python module. But I don't have any > references handy, sorry, and as far as I remember it was done as a private > contract. But it's doable. It should also be doable with Maple, using the OpenMaple API. I've looked at it, and it should be possible. I haven't had the time to actually do anything, though :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From thomas at thomas-lotze.de Sat Jun 11 12:17:06 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sat, 11 Jun 2005 18:17:06 +0200 Subject: Controlling a generator the pythonic way References: Message-ID: Peter Hansen wrote: > Thomas Lotze wrote: >> I can see two possibilities to do this: either the current file position >> has to be read from somewhere (say, a mutable object passed to the >> generator) after each yield, [...] > > The third approach, which is certain to be cleanest for this situation, is > to have a custom class which stores the state information you need, and > have the generator simply be a method in that class. Which is, as far as the generator code is concerned, basically the same as passing a mutable object to a (possibly standalone) generator. The object will likely be called self, and the value is stored in an attribute of it. Probably this is indeed the best way as it doesn't require the programmer to remember any side-effects. It does, however, require a lot of attribute access, which does cost some cycles. A related problem is skipping whitespace. Sometimes you don't care about whitespace tokens, sometimes you do. Using generators, you can either set a state variable, say on the object the generator is an attribute of, before each call that requires a deviation from the default, or you can have a second generator for filtering the output of the first. Again, both solutions are ugly (the second more so than the first). One uses side-effects instead of passing parameters, which is what one really wants, while the other is dumb and slow (filtering can be done without taking a second look at things). All of this makes me wonder whether more elaborate generator semantics (maybe even allowing for passing arguments in the next() call) would not be useful. And yes, I have read the recent postings on PEP 343 - sigh. -- Thomas From peter at engcorp.com Sat Jun 18 12:59:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 18 Jun 2005 12:59:33 -0400 Subject: Unbound names in __del__ In-Reply-To: <87mzpnmwpg.fsf@wilson.rwth-aachen.de> References: <87mzpnmwpg.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > keithley = GpibInstrument(14) > keithley.write("*IDN?") > print keithley.read() > > A keithley.close() would be a wart in my opinion; instead I want to > hide the whole session thing from the programmer. Besides, I > haven't yet given up the hope that the issues with __del__ can be > tackled. At least one alternative comes to mind. Have the GpibInstrument class (or its module) register an atexit() method, and have the constructor for that class track all instances. On shutdown, the atexit method goes through all instruments that are still open and issues the .close() requests, or whatever you do in the __del__ now. In other words, it would be indistinguishable from __del__ from the users' point of view, at the cost of a little extra code to make things explicit, instead of relying on the implicit and, unfortunately, unreliable nature of __del__. (Which is probably the real wart in Python, unfortunately.) -Peter From bvande at po-box.mcgill.ca Thu Jun 30 11:47:29 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu, 30 Jun 2005 11:47:29 -0400 Subject: I have a question. In-Reply-To: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> References: <42c41274$0$6998$b9fe7a78@news.usenetrevolution.com> Message-ID: <42C41411.6020009@po-box.mcgill.ca> Nathan Pinno said unto the world upon 30/06/2005 11:22: > > Hi all, > > Does Python have a random function? If so, can you show me an example > using it? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ >>> import random >>> print "It took %s seconds to find the module named random by looking at the docs" %random.random() It took 0.31385101929 seconds to find the module named random by looking at the docs >>> From peter at engcorp.com Tue Jun 7 09:41:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Jun 2005 09:41:16 -0400 Subject: How do I know when a thread quits? In-Reply-To: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> References: <1118150908.184549.305320@g43g2000cwa.googlegroups.com> Message-ID: <0umdnaKeMsKDOTjfRVn-gA@powergate.ca> Prashanth Ellina wrote: > I have used the low-level thread module to write a multi-threaded app. > > tid = thread.start_new_thread(process, ()) > tid is an integer thread ident. > > the thread takes around 10 seconds to finish processing. Meanwhile the > main thread finished execution and exits. This causes an error because > the child thread tries to access something in the sys module which has > already been GC'ed. I want a reliable way of knowing when the child > thread finished execution so that I can make the main thread wait till > then. > > Any ideas? Yes, use the higher level "threading" module and either the isAlive() call on the Thread object, or just call join() on it to make the main thread wait till it finishes. (By default the main thread will not exit until all threading Threads that aren't daemons have finished... maybe that's sufficient for your needs?) -Peter From gregpinero at gmail.com Tue Jun 28 14:52:54 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 28 Jun 2005 14:52:54 -0400 Subject: I need help figuring out how to fix this code. In-Reply-To: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: <312cfe2b050628115272cc0d93@mail.gmail.com> Make sure that line with name=="Nathan" is not indented. It's hard to tell from the code there. Also, I'm thinking that this won't work: if name == "Nathan": print "What a great name!" elif name == ["Madonna", "Cher"]: because the variable name is a string and not a list. You could try: elif name in ["Madonna", "Cher"]: Greg On 6/28/05, Nathan Pinno wrote: > Hi all, > > I need help figuring out how to fix my code. I'm using Python 2.2.3, and > it keeps telling me invalid syntax in the if name == "Nathan" line. Here is > the code if you need it. > > #This program asks for a password, then asks for the user's name after the > correct password has been supplied. The computers response will vary, > # depending on the name inputted. > print "Program Author: Nathan Pinno" > print "ID# 2413448" > print > print "Program 3 - Loops and IF Conditions" > print > password = raw_input("Type in the password, please: ") > while password != "hello": > print "Incorrect password!" > print "Welcome to the second half of the program!" > name = raw_input("What is your name, please? ") > if name == "Nathan": > print "What a great name!" > elif name == ["Madonna", "Cher"]: > print "May I have your autograph please!" > else > print name,", that's a nice name!" > > What's wrong with the code? How do I fix it, so that it works? > > Thanks, > Nathan Pinno > http://www.npinnowebsite.ca/ > > > > -- > > > ---------------------------------------------------------------- > Posted via UsenetRevolution.com - Revolutionary Usenet > ** HIGH RETENTION ** Specializing in Large Binaries Downloads ** > http://www.UsenetRevolution.com > -- > http://mail.python.org/mailman/listinfo/python-list > From nephish at xit.net Tue Jun 7 22:15:26 2005 From: nephish at xit.net (nephish at xit.net) Date: 7 Jun 2005 19:15:26 -0700 Subject: need some cgi help please Message-ID: <1118196926.583420.110950@o13g2000cwo.googlegroups.com> Hey there. Here is the deal.... i have a script that is supposed to open a file based on criteria from a web form. i cant seem to get it to work though. here is the code: form = cgi.FieldStorage() DataRecord = form['DataTime'].value Customer = form['CustName'].value # should be automatically filled in print "Content-Type: text/html\n\n" print WorkingFile = open("/var/www/stretch/web_root/SidCrops/"+Customer+"/"+DataRecord, "r") all_lines = WorkingFile.readlines() WorkingFile.close() for line in all_lines: print line here is the error: WorkingFile undefined, builtin open = , Customer = 'tenderloin', DataRecord = 'Tue Jun 7 20:13:35 2005.txt' IOError: [Errno 2] No such file or directory: '/var/www/stretch/web_root/SidCrops/tenderloin/Tue Jun 7 20:13:35 2005.txt' args = (2, 'No such file or directory') errno = 2 filename = '/var/www/stretch/web_root/SidCrops/tenderloin/Tue Jun 7 20:13:35 2005.txt' strerror = 'No such file or directory' here is the deal.... the file is there ! i run similar code in idle and it works. i just dont get it. it isn't a permissions issue, its chmod 777 all the way. i gotta find out why this is goofing on me... please help me! From jackdied at jackdied.com Wed Jun 22 01:40:37 2005 From: jackdied at jackdied.com (Jack Diederich) Date: Wed, 22 Jun 2005 01:40:37 -0400 Subject: A World Beyond Capitalism 2005, An Annual International Multiracial Alliance Building Peace Conference Is Accepting Proposals... In-Reply-To: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> References: <72377f88af7a83ee71b361549fafdcce@localhost.talkaboutprogramming.com> Message-ID: <20050622054037.GE7478@performancedrivers.com> On Tue, Jun 21, 2005 at 11:30:19PM -0400, Jenta wrote: > A World Beyond Capitalism 2005, An Annual International Multiracial > Alliance Building Peace Conference Is Accepting Proposals... > This must be a joke (and please please be a joke like the recent viral website competition[1] that featured "crying while eating" and "blogebrity") In addition to ridiculous language and quotes like: "Nothing could be more important than war if war could kill everything" the website has no contact phone numbers, and requires singup before they will even tell you the exact details of the location. The '.info' domain also defeats the linux 'whois' command to dig for registrar info. The spaminess of the advertising also marks it as a not-real conference. I cry farce! Otherwise as a send up of prattle this is a very nice job. -jackdied [1] "Contagious Media" Competition http://showdown.contagiousmedia.org/ From fredrik at pythonware.com Tue Jun 14 02:18:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Jun 2005 08:18:57 +0200 Subject: regarding cgi References: <3itre.131252$IO.22318@tornado.tampabay.rr.com> <20050614060009.83183.qmail@web8409.mail.in.yahoo.com> Message-ID: "praba kar" wrote: > I have doubt regarding headers in cgi > programming. If I gives "Content-Type:text/plain" > then I try to print html contents. Is right or wrong > after giving content-type: text/plain? if you expect the HTML contents to appear as HTML, it's wrong. (some web browsers may display it as HTML even if it's tagged as something else, but you shouldn't rely on this) From rbt at athop1.ath.vt.edu Fri Jun 17 08:50:14 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Fri, 17 Jun 2005 08:50:14 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <42B23670.70103@lexicon.net> References: <42ae3411@news.eftel.com> <1118928457.18452.13.camel@athop1.ath.vt.edu> <42B23670.70103@lexicon.net> Message-ID: <1119012614.4268.18.camel@athop1.ath.vt.edu> On Fri, 2005-06-17 at 12:33 +1000, John Machin wrote: > OK then, let's ignore the fact that the data is in a collection of Word > & Excel files, and let's ignore the scale for the moment. Let's assume > there are only 100 very plain text files to process, and only 1000 SSNs > in your map, so it doesn't have to be very efficient. > > Can you please write a few lines of Python that would define your task > -- assume you have a line of text from an input file, show how you would > determine that it needed to be changed, and how you would change it. The script is too long to post in its entirety. In short, I open the files, do a binary read (in 1MB chunks for ease of memory usage) on them before placing that read into a variable and that in turn into a list that I then apply the following re to ss = re.compile(r'\b\d{3}-\d{2}-\d{4}\b') like this: for chunk in whole_file: search = ss.findall(chunk) if search: validate(search) The validate function makes sure the string found is indeed in the range of a legitimate SSN. You may read about this range here: http://www.ssa.gov/history/ssn/geocard.html That is as far as I have gotten. And I hope you can tell that I have placed some small amount of thought into the matter. I've tested the find a lot and it is rather accurate in finding SSNs in files. I have not yet started replacing anything. I've only posted here for advice before beginning. > > > > > > >>(4) Under what circumstances will it not be possible to replace *ALL* > >>the SSNs? > > > > > > I do not understand this question. > > Can you determine from the data, without reference to the map, that a > particular string of characters is an SSN? See above. > > If so, and it is not in the map, why can it not be *added* to the map > with a new generated ID? It is not my responsibility to do this. I do not have that authority within the organization. Have you never worked for a real-world business and dealt with office politics and territory ;) > >>And what is the source of the SSNs in this file??? Have they been > >>extracted from the data? How? > > > > > > That is irrelevant. > > Quite the contrary. If they had been extracted from the data, They have not. They are generated by a higher authority and then used by lower authorities such as me. Again though, I think this is irrelevant to the task at hand... I have a map, I have access to the data and that is all I need to have, no? I do appreciate your input though. If you would like to have a further exchange of ideas, perhaps we should do so off list? From peterbe at gmail.com Tue Jun 14 12:08:59 2005 From: peterbe at gmail.com (peterbe at gmail.com) Date: 14 Jun 2005 09:08:59 -0700 Subject: Hopefully simple regular expression question References: <1118746918.581184.5470@g49g2000cwa.googlegroups.com> <42aeca58@news.eftel.com> Message-ID: <1118765339.421775.58880@g49g2000cwa.googlegroups.com> Thank you! I had totally forgot about that. It works. From aahz at pythoncraft.com Sun Jun 12 09:31:10 2005 From: aahz at pythoncraft.com (Aahz) Date: 12 Jun 2005 06:31:10 -0700 Subject: Scaling down (was Re: Dealing with marketing types...) References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> <7x7jh0l5kg.fsf@ruckus.brouhaha.com> <7xwtp09jh3.fsf@ruckus.brouhaha.com> Message-ID: In article <7xwtp09jh3.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >What example? Slashdot? It uses way more hardware than it needs to, >at least ten servers and I think a lot more. If LJ is using 6x as >many servers and taking 20x (?) as much traffic as Slashdot, then LJ >is doing something more efficiently than Slashdot. So what? I think you're missing the real point of the article: using LAMP scales *DOWN* in a way that enterprise systems don't. Getting your first prototype up and running is far more important than sheer scalability, and LAMP does have many mechanisms to obtain scalability when it's needed. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ f u cn rd ths, u cn gt a gd jb n nx prgrmmng. From thomas at thomas-lotze.de Sat Jun 11 10:10:32 2005 From: thomas at thomas-lotze.de (Thomas Lotze) Date: Sat, 11 Jun 2005 16:10:32 +0200 Subject: Controlling a generator the pythonic way Message-ID: Hi, I'm trying to figure out what is the most pythonic way to interact with a generator. The task I'm trying to accomplish is writing a PDF tokenizer, and I want to implement it as a Python generator. Suppose all the ugly details of toknizing PDF can be handled (such as embedded streams of arbitrary binary content). There remains one problem, though: In order to get random file access, the tokenizer should not simply spit out a series of tokens read from the file sequentially; it should rather be possible to point it at places in the file at random. I can see two possibilities to do this: either the current file position has to be read from somewhere (say, a mutable object passed to the generator) after each yield, or a new generator needs to be instantiated every time the tokenizer is pointed to a new file position. The first approach has both the disadvantage that the pointer value is exposed and that due to the complex rules for hacking a PDF to tokens, there will be a lot of yield statements in the generator code, which would make for a lot of pointer assignments. This seems ugly to me. The second approach is cleaner in that respect, but pointing the tokenizer to some place has now the added semantics of creating a whole new generator instance. The programmer using the tokenizer now needs to remember to throw away any references to the generator each time the pointer is reset, which is also ugly. Does anybody here have a third way of dealing with this? Otherwise, which ugliness is the more pythonic one? Thanks a lot for any ideas. -- Thomas From d at e.f Fri Jun 24 10:07:40 2005 From: d at e.f (D H) Date: Fri, 24 Jun 2005 09:07:40 -0500 Subject: webserver application (via Twisted?) In-Reply-To: References: Message-ID: flupke wrote: > I need to program and setup serveral webservices. > If i were still using jsp, i would use Tomcat to make the several > applications available on a given port. > How can i accomplish this in Python? > I was thinking about Twisted but it's not clear to me what parts i need > to make a webserver listen on a certain port and having it serve > different application based on the url that i received. See mod_python: http://www.modpython.org/ but there are literally dozens of other options in Python though: http://wiki.python.org/moin/WebProgramming If you want to it in your own standalone server, then I second the recommendation for Karrigell (which also can be run in mod_python as well). From peter at engcorp.com Tue Jun 14 09:18:15 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 09:18:15 -0400 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <42AE59D9.7010704@REMOVEMEcyber.com.au> Message-ID: Roy Smith wrote: > Steven D'Aprano wrote: > >>High and low tides aren't caused by the moon. > > They're not??? Probably he's referring to something like this, from Wikipedia, which emphasizes that while tides are caused primarily by the moon, the height of the high and low tides involves the sun as well: "The height of the high and low tides (relative to mean sea level) also varies. Around new and full Moon, the tidal forces due to the Sun reinforce those of the Moon, due to the syzygy found at those times - both the Sun and the Moon are 'pulling the water in the same direction.'" (If I'm right about this, then the statement is still wrong, since even without the sun there would be high and low tides, just not of the magnitude we have now.) -Peter From mcherm at mcherm.com Fri Jun 10 15:49:46 2005 From: mcherm at mcherm.com (Michael Chermside) Date: Fri, 10 Jun 2005 12:49:46 -0700 Subject: a question from a newcomer to this language Message-ID: <20050610124946.n04zn6b3py8gkcss@login.werra.lunarpages.com> Shankar writes: > Is there any way to convert a string into an instruction that will be > executed? Short answer: Yes. The exec statement does what you want: >>> x = 3 >>> y = 4 >>> exec "z = x * y" >>> print z 12 HOWEVER... the long answer is that you almost certainly do NOT want to use exec. Nearly everything that can be done with exec can be done without it and the solution that does NOT use exec is faster, more understandable, and has better security features. Often the solution that does not use exec will be simpleer and more elegant as well. If you look at a problem and are nearly certain that it needs to be solved using exec, try posting it here... the people on this newsgroup are very good at solving challenges like that. But try it yourself first... you may learn something. -- Michael Chermside From zanesdad at bellsouth.net Fri Jun 3 12:21:21 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 03 Jun 2005 12:21:21 -0400 Subject: couple of new python articles on onlamp Message-ID: <42A08381.9070404@bellsouth.net> I've got a couple of new articles on ONLamp: Writing Google Desktop Search Plugins http://www.onlamp.com/pub/a/python/2005/06/01/kongulo.html and Python Standard Logging http://www.onlamp.com/pub/a/python/2005/06/02/logging.html Comments, criticisms, flames all welcome. Jeremy Jones From sjmaster at gmail.com Wed Jun 1 14:30:44 2005 From: sjmaster at gmail.com (Steve M) Date: 1 Jun 2005 11:30:44 -0700 Subject: Pressing A Webpage Button References: Message-ID: <1117650644.769406.191680@g47g2000cwa.googlegroups.com> Do you actually need to 'press' the button? Or do you just need the effect that pressing the button would bring about (e.g., submitting a Google search query and receiving the results page)? If the latter, then you might want to search for, e.g., "html form get post" and check out some results. Pushing the button is often just loading a URL with parameters. For example, go to Google and type "html form get post" into the search box and press Submit. Now look at the URL you are visiting in your location bar, the URL of the search results. It will be something like: http://www.google.com/search?hl=en&q=html+form+get+post&btnG=Google+Search If you were to load that URL directly (without having gone to the Google homepage, typed "html form get post" in the text entry box and pressed submit) the exact same effect would happen. Filling in the box and clicking the submit button is just the user-friendly way of constructing that URL. From gaz082 at gmail.com Mon Jun 27 19:09:38 2005 From: gaz082 at gmail.com (Inkiniteo) Date: 27 Jun 2005 16:09:38 -0700 Subject: Plain text email? References: <1119911939.179743.98220@z14g2000cwz.googlegroups.com> Message-ID: <1119913778.308704.238610@g44g2000cwa.googlegroups.com> Humm. I just create the message this way: message = 'Serie:\t\t' + str(type) + str(series) + \ '\t\t\tUbicaci?n:\t\t\t' + place + '\n' + \ 'Date&Time:\t' + date and send it with: message = header + message server = smtplib.SMTP('localhost') server.sendmail('email at email.com', email, message) server.quit() From riccardo_cut1 at cut2_sideralis.net Thu Jun 23 06:45:45 2005 From: riccardo_cut1 at cut2_sideralis.net (Riccardo Galli) Date: Thu, 23 Jun 2005 12:45:45 +0200 Subject: PEP ? os.listdir enhancement References: Message-ID: On Thu, 23 Jun 2005 11:34:02 +0200, Andreas Kostyrka wrote: > What's wrong with > > (os.path.join(d, x) for x in os.listdir(d)) > > It's short, and easier to understand then some obscure option ;) > > Andreas how does it help in using list comprehension, as the ones in the first post? -- Riccardo Galli Sideralis Programs http://www.sideralis.net From steven.bethard at gmail.com Mon Jun 27 23:42:51 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Jun 2005 21:42:51 -0600 Subject: Beginner question: Converting Single-Element tuples to list In-Reply-To: <1119928779.725558.211940@g47g2000cwa.googlegroups.com> References: <1119848291.377966.146060@g47g2000cwa.googlegroups.com> <1119849232.609949.272220@g43g2000cwa.googlegroups.com> <1119850812.545438.187700@g47g2000cwa.googlegroups.com> <1119883969.197756.22140@f14g2000cwb.googlegroups.com> <1119888923.782530.286990@g44g2000cwa.googlegroups.com> <1119928779.725558.211940@g47g2000cwa.googlegroups.com> Message-ID: vdavidster at gmail.com wrote: > if type(input) == str: You might consider writing this as: if isinstance(input, basestring): I don't know if pyparsing ever produces unicode objects, but in case it does (or it starts to in the future), isinstance is a better call here. STeVe From EP at zomething.com Thu Jun 9 22:33:21 2005 From: EP at zomething.com (EP) Date: Thu, 9 Jun 2005 18:33:21 -0800 Subject: Dealing with marketing types... In-Reply-To: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> References: <8B6qe.1742$pa3.909@newsread2.news.atl.earthlink.net> Message-ID: <20050609183321.1428046472.EP@zomething.com> flyingfred0 wrote: > A small software team (developers, leads and even the manager when he's > had time) has been using (wx)Python/PostgreSQL for over 2 years and > developed a successful 1.0 release of a client/server product. > > A marketing/product manager has brought in additional management and > "architecture" experts to propose moving the entire thing to a Java > (application server) platform for the next release. They want a > "scalable, enterprise solution" (though they don't really know what > that means) and are going crazy throwing around the Java buzzwords (not to > mention XML). Marketing needs a compelling story to tell the customer: why _this_ technology? Java and XML are cheap buzz words to throw around (but not too much buzz left anymore!) What they need is a story, not a bunch of buzz words, but that story needs to fit into the customers' world view, it needs to mean something to the customer. It's possible that Python/PostgreSQL is a technology combination that represents a winning story, at least in the right marketplaces. Possibly the development team is more technically savvy than the marketers ;-), so try to gently help them understand why the Python/PostgreSQL story is strong. Faster incremental development of releases ("Customer, no long waits for the new features you want like you have with Java apps. Ou development is fast and agile like your requirements!") might be the kind of perspective that helps your cause. Give the marketing guys "stories" about why the current product implementation is good from a marketing perspective - how (wx)Python/PostgreSQL will make the product unique and noticeable and easier to sell than another Java/XML client server app. I think that's about the best you can do. good luck! Eric (Psuedo-marketing-type) From eloff777 at yahoo.com Wed Jun 22 19:26:31 2005 From: eloff777 at yahoo.com (Eloff) Date: 22 Jun 2005 16:26:31 -0700 Subject: Avoiding deadlocks in concurrent programming In-Reply-To: References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: <1119482791.094538.43920@g14g2000cwa.googlegroups.com> Hi Steve, The backup thread only holds the lock long enough to create an in-memory representation of the data. It writes to disk on it's own time after it has released the lock, so this is not an issue. If you're saying what I think you are, then a single lock is actually better for performance than multiple locks so long as one avoids waiting for other resources like I/O. -Dan From chinook.nr at tds.net Tue Jun 28 07:39:59 2005 From: chinook.nr at tds.net (Chinook) Date: Tue, 28 Jun 2005 07:39:59 -0400 Subject: OO refactoring trial ?? Message-ID: <0001HW.BEE6AF4F0004008BF00FF3B0@smtp.tds.net> Clarifications: 1) Truth test simplified after a %) by Peter Otten - thanks. In reality the "testit" methods will all be quite different as you might imagine (as will the "doit" methods). 2) A final subclass will always return True, so there will always be a valid result. ==================== Following is a simple trial structure of a refactoring (top-down to OO) learning exercise I'm doing. Whether you call it a Factory pattern, COR pattern, or some hinze 57, I don't know what class to use till run time and I'm trying to avoid a lengthy "if" sequence, the test sequence is important, and to avoid code duplication I'll be using code objects in the "doit" methods. You've already given me many good ideas in previous threads and this is where it got you :~) This works, but would you please tell me: 1) What you don't like about the approach and/or how it might be improved 2) The implications of using this in a recursive approach (referenced from but outside the recursive function) 3) Any other comments you might offer Thank you, Lee C =========== ootest.py ============ class MF(object): @staticmethod def findit(t): for it in MF.__subclasses__(): if it.testit(t): return it().doit class A(MF): @staticmethod def testit(tv): return (tv == 'relates to A') def doit(self): print '# did A #' class B(MF): @staticmethod def testit(tv): return (tv == 'relates to B') def doit(self): print '# did B #' mydoit = MF.findit('relates to B') mydoit() mydoit = MF.findit('relates to A') mydoit() ======== Test run ============== Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] Type "help", "copyright", "credits" or "license" for more information. >>> import ootest # did B # # did A # >>> From steve at REMOVETHIScyber.com.au Sat Jun 25 14:33:15 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Sun, 26 Jun 2005 04:33:15 +1000 Subject: a dictionary from a list References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> <1119707062.260303.185590@g47g2000cwa.googlegroups.com> Message-ID: On Sat, 25 Jun 2005 06:44:22 -0700, George Sakkis wrote: > "Roy Smith" wrote: > >> I just re-read the documentation on the dict() constructor. Why does it >> support keyword arguments? >> >> dict(foo="bar", baz="blah") ==> {"foo":"bar", "baz"="blah"} >> >> This smacks of creeping featurism. Is this actually useful in real code? >> It took me several readings of the doc to understand what this was doing. >> Essentially, it's Perl's bareword syntax, and once I realized that, I >> simultaneously understood what was happening and was revolted that Python >> seems to have picked up one of Perl's most bizarre and confusing features. > > The worst thing about this form of the dict constructor it's not the > syntax; I think this becomes obvious after you've seen it once. More > annoying is that it "wastes" keyword arguments that could otherwise be > used to determine the characteristics of the dict. Perhaps the most > common desired feature is setting a default value for the dict, that > would allow for instance: > > wordCount = dict(default=0) > wordPos = dict(default=[]) > for pos,word in enumerate(text): > wordCount[word] += 1 > wordPos[word].append(pos) > > Other candidate optional arguments would allow type checking (e.g. > dict(keys=int, values=list)) or performance fine-tuning (e.g. > dict(minsize = 10, maxsize = 10000, average = 200)). I hope the > decision for this form of the constructor is reconsidered for python > 3K. Since Python dicts don't have default values, or type-checking, or user-editable performance fine-tuning, or for that matter any optional arguments, it is hardly possible to "waste" keyword arguments for a function that doesn't need any keyword arguments. What you actually mean to say is that the use of keyword arguments as "bareword" syntax for initialising dicts conflicts with the use of keyword arguments for non-existent, hypothetical and/or user-defined classes. That's okay. I'm perfectly comfortable with the fact that the syntax for initialising a dict conflicts with the syntax for initialising a list, a Decimal, a MutableString, and a ConfigParser object. So why should I be distressed that it conflicts with the syntax for initialising MyDictWithDefaultValue objects? -- Steven. From mh at pixar.com Wed Jun 15 19:03:55 2005 From: mh at pixar.com (Mark Harrison) Date: Wed, 15 Jun 2005 23:03:55 GMT Subject: splitting delimited strings Message-ID: What is the best way to process a text file of delimited strings? I've got a file where strings are quoted with at-signs, @like this at . At-signs in the string are represented as doubled @@. What's the most efficient way to process this? Failing all else I will split the string into characters and use a FSM, but it seems that's not very pythonesqe. @rv@ 2 @db.locks@ @//depot/hello.txt@ @mh@ @mh@ 1 1 44 @pv@ 0 @db.changex@ 44 44 @mh@ @mh@ 1118875308 0 @ :@@: :@@@@: @ (this is from a perforce journal file, btw) Many TIA! Mark -- Mark Harrison Pixar Animation Studios From oren.tirosh at gmail.com Thu Jun 23 02:19:04 2005 From: oren.tirosh at gmail.com (Oren Tirosh) Date: 22 Jun 2005 23:19:04 -0700 Subject: voicemail program written with python In-Reply-To: References: Message-ID: <1119507544.835150.114250@g47g2000cwa.googlegroups.com> It is relatively easy to write voice applications for the Asterisk software PBX using the CGI-like AGI (Asterisk Gateway Interface). The following document describes the AGI and has some examples in Python: http://home.cogeco.ca/~camstuff/agi.html From peter at engcorp.com Tue Jun 14 07:59:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 14 Jun 2005 07:59:39 -0400 Subject: Reg cgi header In-Reply-To: References: Message-ID: praba kar wrote: > I have doubt regarding headers in cgi > programming. If I gives "Content-Type:text/plain" > then I try to print html contents. Is right or wrong > after giving content-type: text/plain? Since you didn't like the other two replies you've already received in response to your previous two postings of the same question, I'll provide another and you can see if you like it any better: It is wrong. Don't do it. :-) -Peter From jstroud at mbi.ucla.edu Sat Jun 25 23:05:14 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 25 Jun 2005 20:05:14 -0700 Subject: Favorite non-python language trick? In-Reply-To: <200506251844.12393.jstroud@mbi.ucla.edu> References: <200506251844.12393.jstroud@mbi.ucla.edu> Message-ID: <200506252005.14967.jstroud@mbi.ucla.edu> On Saturday 25 June 2005 06:44 pm, James Stroud wrote: > I thought they were > pointless 18 years ago when I learned pascal in highschool and after 20 > years, I still think they are still pointless. I think that fails "==". -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From grig.gheorghiu at gmail.com Tue Jun 21 13:00:08 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 21 Jun 2005 10:00:08 -0700 Subject: utf8 silly question In-Reply-To: References: Message-ID: <1119373208.663784.230850@g14g2000cwa.googlegroups.com> Salut, Catalin You can first convert your c string to unicode, and in the process specify an encoding that understands non-ASCII characters (if you don't specify an encoding, it will try to use your default, which is most likely ASCII, and you'll get the error you mentioned.). In the following example, I specified 'iso-8859-1' as the encoding. Then you can utf8-encode the c string via the codecs module. Here's a snippet of code (note the error when I don't specify a non-default unicode encoding): Python 2.4 (#1, Nov 30 2004, 16:42:53) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> c = unicode(chr(169)+" some text") Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xa9 in position 0: ordinal not in range(128) >>> c = unicode(chr(169)+" some text", 'iso-8859-1') >>> print c ? some text >>> import codecs >>> print codecs.encode(c, 'utf-8') ?? some text From supermhaxx at despammed.com Tue Jun 28 08:39:41 2005 From: supermhaxx at despammed.com (Mhaxx) Date: Tue, 28 Jun 2005 14:39:41 +0200 Subject: p Message-ID: From fredrik at pythonware.com Tue Jun 28 08:04:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 28 Jun 2005 14:04:00 +0200 Subject: How to compress a folder and all of its sub directories and filesinto a zip file? References: <311b5ce105062723167e892833@mail.gmail.com><42C188F3.7010704@rt.sk> <311b5ce1050628002075da2e3@mail.gmail.com><311b5ce10506280029682b9366@mail.gmail.com> <42C0FFCC.8030708@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote: > So, it would appear that compression requires a 3rd party module, not > included in Python (and not present on my Windows box). where did you get your Windows Python? afaik, the zlib module has been included in all major Python binary distributions since 1.5.2 or so... From fredrik at pythonware.com Wed Jun 22 03:59:09 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Jun 2005 09:59:09 +0200 Subject: utf8 and ftplib References: <1119267462.32655.236736750@webmail.messagingengine.com><1119275301.13168.236745297@webmail.messagingengine.com> Message-ID: Fredrik Lundh wrote: > character references refer to code points in the Unicode code > space, so you just convert the bytes you get after converting > to UTF-8. "so you cannot just", of course. From tjreedy at udel.edu Wed Jun 1 20:36:11 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 1 Jun 2005 20:36:11 -0400 Subject: NSLU2 and python - a love story ? References: <1117629593.000908.294450@g43g2000cwa.googlegroups.com> <1117664564.859147.185660@g49g2000cwa.googlegroups.com> Message-ID: "Thomas W" wrote in message news:1117664564.859147.185660 at g49g2000cwa.googlegroups.com... > have replacement-firmware. The point is that alot of people have > modified their NSLU2, which by the way don't remove any of the > functionality of the original product as I understand it, There are two replacement firmware images. One extends the original firmware functionality (moving data back and forth from ethernet/internet to usb strorage). The other, for Linux experts, replaces it. > My interest in it is due to the fact that my current two servers makes > alot of noise, are big and uses alot of eletricity. I had not thought of that aspect. > The first project I have in mind is a web-interface to my digital image > collection, in which I can organise the pictures in categories, add > metadata, generate galleries and slideshows etc. From what I can see > the NSLU2 would have little problems serving this specific purpose, in > addition to serving the images thru samba as well so I can access them > with my laptop, my KISS DP-558 PVR and my XBox. The > "distro"/replacement-firmware for the NSLU2 allready have most of the > modules I need ( CherryPy, pySQLite/SQLite ). The only thing missing > is, as I said earlier, PIL. > > I think anything running linux and especially Python, is awsome, I'll > admit that. Perhaps I'm just blinded by all that and cannot see the > fact that 266Mhz isn't enough "juice". It depends on your image sizes and amount of processing you want to do on the NSLU2. For uncompressed TIFFs from multimegapixel cameras, 32MB will be cramped. One can apparently expand memory, but "A new kernel will be necessary to enable usage of the extra memory. " I don't know if this means the new kernel in either or both the replacements or one that one has to supply. 60K jpeg web images are a different story. For interactive processing of such large images (like color correction, edge finding, etc) my experience (with 300-400MH Win machines) suggests that you might find 256MH somewhat pokey. But I don't know what you are used to with your laptop or current servers. I don't know what 'generate gallery' requires. Terry J. Reedy From rrr at ronadam.com Wed Jun 22 10:02:44 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 22 Jun 2005 14:02:44 GMT Subject: getting an object name In-Reply-To: References: Message-ID: <8ceue.152725$IO.89419@tornado.tampabay.rr.com> David Bear wrote: > Let's say I have a list called, alist. If I pass alist to a function, > how can I get the name of it? > > alist = range(10) > > def afunction(list): > listName = list.__name__ (fails for a list object) > Using an object's name as data isn't a good idea because it will generally cause more problems than it solves. If you have several different types of lists and need to handle them differently, then you might consider using class's that knows how to handle each type of list. Also, if the name is really part of the data, then you should store the name as a string with the list. class data1(object): def __init__(self, alist, name): self.list = alist self.name = name def data_type(self): print "This is a data1 object" class data2(object): def __init__(self, alist, name): self.list = alist self.name = name def data_type(self): print "This is a data2 object" list_a = data1( range(10), "small list") print list_a.list print list_a.name list_b = data2( range(100), "large list") def data_type(data): data.data_type() # don't need the name here data_type(list_a) # prints 'This is a data1 object' data_type(list_b) # prints 'This is a data2 object' You can also store a name with the list in a list if you don't want to use class's. alist = ['mylist',range[10]] print alist[0] # name print alist[1] # list Regards, Ron From donn at u.washington.edu Wed Jun 1 12:35:12 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 01 Jun 2005 09:35:12 -0700 Subject: ignoring SIGPIPE in a python script? References: Message-ID: In article , Dan Stromberg wrote: > I have a python script that sometimes gets a SIGPIPE signal, and errors > out. And I want it to just terminate as though it had hit EOF. > > I'm running: > > signal.signal(signal.SIGPIPE,signal.SIG_IGN) > > ...in the main function, but the script is still erroring out on sigpipe > when the consumer to its producer terminates early. > > Am I going to have to code in a handful of exceptions, and then > conditionalize what happens in those exception handlers, to get the > desired behavior? > > ISTR hearing that although bash notifies one of SIGPIPE errors, tcsh > generally silently ignores them. From this, I conclude that it might be > reasonable for my script to ignore SIGPIPE. This is a little idiosyncracy of Python's. You can restore the default signal handler, signal.signal(signal.SIGPIPE, signal.SIG_DFL) and it will behave like a normal UNIX application. These other applications aren't precisely ignoring SIGPIPE, though. If you think about what that would look like, I guess it would mean they would continue to write output, since it's truly a rare application that checks its output (especially since it's usually buffered.) The SIGPIPE signal just aborts the program. Not really very much like EOF at all. You could install your own handler, but it would probably make about as much sense to just trap the exception. Donn Cave, donn at u.washington.edu From chad.hughes at pnl.gov Fri Jun 10 14:14:16 2005 From: chad.hughes at pnl.gov (Hughes, Chad O) Date: Fri, 10 Jun 2005 11:14:16 -0700 Subject: SMTP Test Rig Message-ID: <42C7E766869C42408F0360B7BF0CBD9B014B6164@pnlmse27.pnl.gov> Thanks very much it works great and does exactly what I need for a test I have to perform. I started teaching myself the SMTP protocol last night and it does not look to hard. But this saves me a great deal of time an effort. I hope you can find a good place to host it, as it is the only example I have seen yet. Chad -----Original Message----- From: Tim Williams [mailto:listserver at tdw.net] Sent: Friday, June 10, 2005 5:35 AM To: Hughes, Chad O; Jesse Noller Subject: SMTP Test Rig Chad, Jesse. The SMTP test rig receives SMTP emails and can be configured to write them to the screen, save them to a file - or both. Have fun # """ SMTPRIG.py (SMTP Test Rig) Version 1.0 Copyright (C) Tim Williams (tdw at tdw.net) 10th June 2005 # # This software is provided "AS IS" without any warranty # explicit or implied. # # Redistribution of this code is allowed provided the # above copyright information remains intact. # # This code was developed out of the need for a very basic # test SMTP server, and later expanded to add logging to # screen and/or the ability to save the email to a text file. # # This server has the bare minimum SMTP functionality required # to impliment the above requirements. It has no error checking # or rfc822 compliance checks, it will receive anything from anyone # no matter how bad their SMTP dialogue is. # # This server has only been tested in a windows environment # # This server can receive multiple concurrent emails (multithreaded inbound) # # This server CAN NOT RELAY email to another server (unless you add that bit yourself) # # Please feel free to send comments or questions to tdw at tdw.net # """ from socket import * from SocketServer import * from Queue import Queue from random import randrange from os import path, makedirs import thread server_port = 2525 # the port the server will run on file_path = 'txtmails' # path for saved files write_to_screen = 1 # 1 to enable, 0 to disable write_to_file = 1 # 1 to enable, 0 to disable try: makedirs(file_path) except OSError, x: #[Errno 17] File exists: pass q_print = Queue() #queue for printing to console. class SMTPServer(ThreadingMixIn, TCPServer): # other functions exist here in a live server def some_function(self): pass #end of class SMTPServer class SMTPRequestHandler(StreamRequestHandler): global write_to_file, file_path def handle(self): qprint ('*-'*30) self.ip, self.port = self.client_address self.port = str(self.port) self.ip = str(self.ip) qprint ( "<=====> Incoming connection from ", self.ip, ' Port:', self.port) self.terminated = 0 self.receiving_data = 0 self.SendResponse('220 ** Welcome **') self.msg = [] self.msg_count = 1 empty_line = 0 self.msg_id() commands={ 'HELO' : self.__OK, # supported commands 'QUIT' : self.__QUIT, 'MAIL' : self.__OK, 'RCPT' : self.__OK, 'NOOP' : self.__OK, 'RSET' : self.__OK, 'HELP' : self.__OK, 'DATA' : self.__DATA, } while not self.terminated: try: self.inputline = self.rfile.readline() self.inputline = self.inputline.rstrip() qprint (self.port + '<== ' + self.inputline ) except: self.inputline = ' ' request = self.inputline.upper().split() if self.receiving_data: self.receive_body() elif request and commands.has_key(request[0]): # eg: if has_key HELO commands[request[0]](request) else: self.SendResponse("500 Unknown Command "+ self.inputline) if self.inputline == '': # empty commandline empty_line += 1 if empty_line > 9: # max empty lines self.SendResponse('550 Too many empty lines') break # end of smtp conversation def receive_body(self): if self.inputline == '.': self.receiving_data = 0 self.msg_count += 1 self.msg_id() if write_to_file: self.write_file() self.SendResponse('250 2.1.0 OK: Data received') else: self.msg.append(self.inputline) def __OK(self,request): self.SendResponse('250 2.1.0 OK') def __DATA(self,request): self.receiving_data = 1 self.SendResponse('354 End data with .') def __QUIT(self,request): self.terminated = 1 self.SendResponse('221 2.1.0 Bye') qprint ('*-'*30) qprint (' ') def SendResponse(self,msg): qprint (self.port + '==> '+ msg) msg = msg + '\r\n' self.wfile.write(msg) self.wfile.flush() def msg_id(self): self.msg_name = str(randrange(1,999))+self.port+str(self.msg_count) def write_file(self): msg = '\r\n'.join(self.msg) self.msg = [] file_loc = path.join(file_path, self.msg_name)+'.txt' file = open(file_loc, "wb") file.write(msg) file.close() # end of class SMTPRequestHandler def qprint(*args): """Put a string on the print queue""" if write_to_screen: q_print.put(''.join(args)) def printThread(): """wait for items to print to console""" while 1: m = q_print.get(1) print m thread.start_new_thread(printThread, ()) # new thread for print queue processing def StartSMTPServer(): print '*'*35 print 'Server Starting, CTRL-C to end' print '*'*35 setdefaulttimeout( 30 ) # timeout incoming connections server = SMTPServer(('', server_port ), SMTPRequestHandler) server.serve_forever() #end of def StartSMTPServer if __name__ == '__main__': StartSMTPServer() From steven.bethard at gmail.com Wed Jun 1 10:52:54 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 01 Jun 2005 08:52:54 -0600 Subject: how to convert string to list or tuple In-Reply-To: References: <1117383768.099922.308760@o13g2000cwo.googlegroups.com> Message-ID: Duncan Booth wrote: > Steven Bethard wrote: > > >>Interestingly, I don't seem to be able to create a file object as a >>class attribute in restricted mode: >> >>py> class C(object): >>... def __init__(self): >>... self.f = file('temp.txt', 'w') >>... >>py> eval('''[ cls for cls in >>{}.__class__.__bases__[0].__subclasses__() if cls.__name__ == >>'C'][0]().f.write("stuff")''', dict(__builtins__=None)) Traceback >>(most recent call last): >> File "", line 1, in ? >> File "", line 0, in ? >>AttributeError: 'C' object has no attribute 'f' >>py> eval('''[ cls for cls in >>{}.__class__.__bases__[0].__subclasses__() if cls.__name__ == >>'C'][0]().__dict__''', dict(__builtins__=None)) {} > > Weird. I copied and paste your class and eval exactly (apart from deleting > the ... prompts) and it worked exactly as expected: writing 'stuff' to > temp.txt. (Python 2.4) So, I played around with this a little bit. If I start up a new interpreter and type it in like above, I get the behavior you do. What I had actually done (abbreviated) was: py> class C(object): ... pass ... py> class C(object): ... def __init__(self): ... self.f = file('temp.txt', 'w') ... py> eval('''[ cls for cls in {}.__class__.__bases__[0].__subclasses__() if cls.__name__ == 'C'][0]().f.write("stuff")''', dict(__builtins__=None)) Traceback (most recent call last): File "", line 1, in ? File "", line 0, in ? AttributeError: 'C' object has no attribute 'f' And the problem with this is that both __main__.C objects are now subclasses of object: py> eval('''[ cls for cls in {}.__class__.__bases__[0].__subclasses__() if cls.__name__ == 'C']''', dict(__builtins__=None)) [, ] So I was getting the wrong __main__.C object. Sorry for the confusion! Now, even using this technique, *your* code can't call the file constructor: py> class C(object): ... def __init__(self): ... self.file = file ... py> eval('''[ cls for cls in {}.__class__.__bases__[0].__subclasses__() if cls.__name__ == 'C'][-1]().file("temp.txt", "w")''', dict(__builtins__=None)) Traceback (most recent call last): File "", line 1, in ? File "", line 0, in ? IOError: file() constructor not accessible in restricted mode But unless the person eval-ing your code *only* writes immaculate code I can see that you can probably screw them. ;) I wonder why __subclasses__ isn't a restricted attribute... Is it ever used for something that isn't evil? ;) STeVe From gregpinero at gmail.com Tue Jun 14 11:48:03 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 14 Jun 2005 11:48:03 -0400 Subject: MySQLDBAPI In-Reply-To: References: <2tqln2-6c3.ln1@news.interplanet.it> Message-ID: <312cfe2b05061408481a3e7de0@mail.gmail.com> see below On 6/10/05, Daniel Dittmar wrote: > Gregory Pi?ero wrote: > > Is that something I can install all to my home directory? > > If you have a similar Linux distribution at home, simply build the mysql > extension on that machine and then copy it to the web server. I have Ubuntu running at home and Redhat is running on the server. Would this still work for me? Do I need to install the same old version of MySql on my home computer? > > Otherwise: > > You don't have to actually install it. Just make sure that Setup.py > finds the headers and libs > > 1a) get the rpm and extract the files Are you referring to the rpm for Mysql? I would just get the same version as the server has? > > or 1b) compile (but don't install) mysql from sources > > 2) specify the locations of the header files and the libs to Setup.py or > patch the module such that the defaults point to your directories. From > your error message, the current default for the includes seems to be > /usr/local/mysql/include/mysql So the new location will be where I extracted the RPM to? > > 3) You can then delete the directories created in 1a or 1b So the new python module, the dpapi will be installed in my home directory? So when I import it from another script I would just append my home directory to the sys.path first to use it? > > Daniel > -- > http://mail.python.org/mailman/listinfo/python-list > From lbates at syscononline.com Tue Jun 7 18:45:00 2005 From: lbates at syscononline.com (Larry Bates) Date: Tue, 07 Jun 2005 17:45:00 -0500 Subject: School Administration Software In-Reply-To: References: Message-ID: <42A6236C.4040400@syscononline.com> You may want to take a look at: Centre http://www.miller-group.net/ Open Admin http://richtech.ca/openadmin/about.html A low cost, but pretty mature package is also available: SchoolMation http://www.schoolmation.net/schoolmationweb/main/index.php I don't have personal experience, but Google turned these up quickly. Larry Bates Greg Lindstrom wrote: > Hello- > > I just picked up my daughters' report cards for the year (they did well, > thank-you) and was approached by the school administrator about writing > an Acess application to help track attendance for next year > (excused/unexcused, after so many unexcused absences a letter will be > generated, etc.). Since I have a feel for how large this request will > become, I googled for school administration software on the Python site > and was pleased to get 312 "hits". There's software out there but -- > alas -- it's difficult to tell what is being used, what people think, > what's being maintained, etc. > So...do any of you have experience with any of this software? This is > for a small (~400 students k-12), private school that is not swimming in > taxpayer dollars and I would rather use Open Source because we will > probably need to customize some reports, etc. Any advice you have would > be welcome. > > Thanks, > --greg > From reinhold-birkenfeld-nospam at wolke7.net Thu Jun 2 10:52:58 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 02 Jun 2005 16:52:58 +0200 Subject: Two questions In-Reply-To: References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <3g8kqaFb5v3dU2@individual.net> Richard Lewis wrote: > On 2 Jun 2005 06:45:18 -0700, qscomputing at gmail.com said: >> Hi, >> >> I've developed in several other languages and have recently found >> Python and I'm trying to use it in the shape of the PythonCard >> application development tool. >> >> My two questions: >> >> 1. What is the easiest way to create a for loop in the style I'm used >> to from Delphi ie: >> for I:=0 to 2 do begin >> //code >> end; >> > for i in range(0, 2): > do stuff Eh, no. range(0, 3) would be correct, since the Python range function generates a list from start to stop-1. > The range([start], stop, [step]) function generates a sequence of > numbers which the the for loop iterates over. > > (You can also use xrange() for a more memory efficient solution for very > large ranges). > >> 2. Philospohy(sp?) aside, I could potentially want to create a >> binary-only distribution of my finished apps. I noticed the >> documentation on .pyc files: how do I create these and, aside from >> being basically read-only, are they used just like ordinary .py source >> files? And can they be easily reverse-engineered? They are a binary representation of bytecode, just like in Java. They can be reverse-engineered more easily than machine code, but it still is no no-brainer. Btw, they are created automatically... Reinhold From listserver at tdw.net Thu Jun 9 10:20:41 2005 From: listserver at tdw.net (Tim Williams) Date: Thu, 9 Jun 2005 15:20:41 +0100 Subject: Simple SMTP server References: <4222a8490506090644442aa67d@mail.gmail.com> Message-ID: <004101c56cfe$6a7cbd60$ccbefea9@twilliams> ----- Original Message ----- From: "Jesse Noller" > I am looking at implementing a simple SMTP server in python - I know > about the smtpd module, but I am looking for code examples/snippets as > the documentation is sparse. > > If anyone has any good examples/recipes I'd greatly appreciate it. This is a test server I put together (part adapted from somewhere else) earlier in the week, it is multithreaded inbound. You could add your required functionality quite easily. It currently starts on port 2525 (watch out for line-wraps) ## #! /usr/bin/python import sys from socket import * from SocketServer import * class SMTPServer(ThreadingMixIn, TCPServer): # # other functions exist here in the live server # def noFunction(): pass #end of class SMTPServer class SMTPRequestHandler(StreamRequestHandler): def handle(self): self.terminated = 0 self.SendResponse('220 ** Welcome **') commands={ 'HELO' : self.__HELO, # supported commands 'QUIT' : self.__QUIT, #'MAIL' : self.__MAIL, #'RCPT' : self.__RCPT, 'NOOP' : self.__NOOP, #'RSET' : self.__RSET, 'EHLO' : self.__HELO, # handled by HELO #'DATA' : self.__DATA, } while not self.terminated: try: self.inputline = self.rfile.readline() self.inputline = self.inputline.rstrip().upper() except: self.inputline = '*?*' request = self.inputline.split() print "request=",request if request and commands.has_key(request[0]): # eg: if has_key FROM commands[request[0]](request) else: self.SendResponse("?? "+ self.inputline) def __HELO(self,request): if request[0]== 'HELO': self.SendResponse('250 2.1.0 Hello') else: self.SendResponse('250-Hello\r\n250-SIZE 9999999\r\n250-ENHANCEDSTATUSCODES\r\n250 HELP') def __NOOP(self,request): self.SendResponse('250 2.1.0 OK') def __QUIT(self,request): self.terminated = 1 self.SendResponse('Goodbye') print "Session Closed" def SendResponse(self,msg): print msg msg = msg + '\r\n' self.wfile.write(msg) self.wfile.flush() # end of class SMTPRequestHandler def StartSMTPServer(): print '*'*35 print 'Server Starting, CTRL-C to end' print '*'*35 setdefaulttimeout( 30 ) # timeout incoming connections server = SMTPServer(('', 2525 ), SMTPRequestHandler) server.serve_forever() #end of def StartSMTPServer if __name__ == '__main__': StartSMTPServer() From kveretennicov at gmail.com Thu Jun 16 14:21:50 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 16 Jun 2005 21:21:50 +0300 Subject: Set of Dictionary In-Reply-To: <20050616160959.34219.qmail@web53910.mail.yahoo.com> References: <4660fe3005061608023c4f96ab@mail.gmail.com> <20050616160959.34219.qmail@web53910.mail.yahoo.com> Message-ID: <4660fe3005061611217a1b612f@mail.gmail.com> On 6/16/05, Vibha Tripathi wrote: > I need sets as sets in mathematics: That's tough. First of all, mathematical sets can be infinite. It's just too much memory :) Software implementations can't fully match mathematical abstractions. > sets of any unique type of objects including those > of dictionaries, I should then be able to do: > a_set.__contains__(a_dictionary) and things like that. Maybe you can use a list for that: >>> d1 = {1: 2} >>> d2 = {3: 4} >>> s = [d1, d2] >>> {1: 2} in s True >>> {5: 6} in s False > Can sets in Python 2.4.1, be reimplemented from > scratch to not have it work on top of dict? Sure, why not? - kv From emami at knmi.nl Mon Jun 20 05:50:24 2005 From: emami at knmi.nl (Nader Emami) Date: Mon, 20 Jun 2005 11:50:24 +0200 Subject: binary file Message-ID: L.S., I have used the profile module to measure some thing as the next command: profile.run('command', 'file') But this make a binary file! How can I write the result of 'profile' in a ascii file? Others how can I read (or convert) the binary file to am ascii file? Regards, Nader From jepler at unpythonic.net Wed Jun 22 12:50:01 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 22 Jun 2005 11:50:01 -0500 Subject: Loop until condition is true In-Reply-To: References: Message-ID: <20050622165000.GB26783@unpythonic.net> def until(pred): yield None while True: if pred(): break yield None def example(): i = 0 for _ in until(lambda: x==0): x = 10 - i i += 1 print x, i example() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From duncan.booth at invalid.invalid Wed Jun 1 04:30:05 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jun 2005 08:30:05 GMT Subject: how to convert string to list or tuple References: <1117383768.099922.308760@o13g2000cwo.googlegroups.com> Message-ID: Steven Bethard wrote: > Interestingly, I don't seem to be able to create a file object as a > class attribute in restricted mode: > > py> class C(object): > ... def __init__(self): > ... self.f = file('temp.txt', 'w') > ... > py> eval('''[ cls for cls in > {}.__class__.__bases__[0].__subclasses__() if cls.__name__ == > 'C'][0]().f.write("stuff")''', dict(__builtins__=None)) Traceback > (most recent call last): > File "", line 1, in ? > File "", line 0, in ? > AttributeError: 'C' object has no attribute 'f' > py> eval('''[ cls for cls in > {}.__class__.__bases__[0].__subclasses__() if cls.__name__ == > 'C'][0]().__dict__''', dict(__builtins__=None)) {} > Weird. I copied and paste your class and eval exactly (apart from deleting the ... prompts) and it worked exactly as expected: writing 'stuff' to temp.txt. (Python 2.4) From R.Brodie at rl.ac.uk Tue Jun 28 09:56:47 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 28 Jun 2005 14:56:47 +0100 Subject: Python 2.1 / 2.3: xreadlines not working with codecs.open References: Message-ID: "Eric Brunel" wrote in message news:opss2ywss0rqur0o at eb.pragmadev... > > Replying to myself. One more funny thing: > > >>> import codecs, xreadlines > >>> f = codecs.open('foo.txt', 'r', 'utf-8', 'replace') > >>> [l for l in xreadlines.xreadlines(f)] > [u'\ufffd\ufffd'] You've specified utf-8 as the encoding instead of iso8859-1, by the way. From gsakkis at rutgers.edu Sun Jun 19 16:17:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 19 Jun 2005 13:17:50 -0700 Subject: Why is there no instancemethod builtin? References: <1119132363.372425.136410@g14g2000cwa.googlegroups.com> <1119197146.922190.38000@g44g2000cwa.googlegroups.com> <1119201221.143713.8890@z14g2000cwz.googlegroups.com> <1119202546.388847.114650@g14g2000cwa.googlegroups.com> <1119203542.789312.5620@g44g2000cwa.googlegroups.com> <11bbi5o11pjcj1f@news.supernews.com> Message-ID: <1119212270.552078.87290@g14g2000cwa.googlegroups.com> "John Roth" wrote: > Unfortunately it doesn't work: getitem can be defined for > a class that acts like a dictionary: that is, the items are > not integers, let alone integers that extend in a strict > sequence from 0. This is true, but that's the current behaviour of iterators for classes that define __getitem__ without __iter__: class AnIterable(object): def __init__(self, it): self._it = it def __getitem__(self,i): return self._it[i] >>> x = AnIterable(dict(a=1,b=2)) >>> list(x) KeyError: 0 George From roy at panix.com Sun Jun 5 12:46:24 2005 From: roy at panix.com (Roy Smith) Date: Sun, 05 Jun 2005 12:46:24 -0400 Subject: For review: PEP 343: Anonymous Block Redux and Generator Enhancements References: <2a2oe.40882$_r1.1220427@news20.bellglobal.com> Message-ID: Nicolas Fleury wrote: > It's important to note that nobody is against the PEP syntax. We are > only talking about adding things to it In think the above is a contradiction in terms. From oliver.andrich at gmail.com Mon Jun 20 17:29:18 2005 From: oliver.andrich at gmail.com (Oliver Andrich) Date: Mon, 20 Jun 2005 23:29:18 +0200 Subject: Python and encodings drives me crazy In-Reply-To: <6f7b52d05062013545cbc435d@mail.gmail.com> References: <6f7b52d05062013545cbc435d@mail.gmail.com> Message-ID: <6f7b52d05062014292f25e8a9@mail.gmail.com> Well, I narrowed my problem down to writing a macroman or cp850 file using the codecs module. The rest was basically a misunderstanding about codecs module and the wrong assumption, that my input data is iso-latin-1 encode. It is UTF-8 encoded. So, curently I am at the point where I have my data ready for writing.... Does the following code write headline and caption in MacRoman encoding to the disk? Or better that, is this the way to do it? headline and caption are both unicode strings. f = codecs.open(outfilename, "w", "macroman") f.write(headline) f.write("\n\n") f.write(caption) f.close() Best regards, Oliver -- Oliver Andrich --- http://fitheach.de/ From onurb at xiludom.gro Wed Jun 29 04:29:56 2005 From: onurb at xiludom.gro (bruno modulix) Date: Wed, 29 Jun 2005 10:29:56 +0200 Subject: Dictionary to tuple In-Reply-To: References: <42c169d0$0$23811$626a14ce@news.free.fr> Message-ID: <42c25c0d$0$23840$626a14ce@news.free.fr> Erik Max Francis wrote: > bruno modulix wrote: > >> Err... don't you spot any useless code here ?-) >> >> (tip: dict.items() already returns a list of (k,v) tuples...) > > But it doesn't return a tuple of them. Which is what the tuple call > there does. Of course, but the list-to-tuple conversion is not the point here. The useless part might be more obvious in this snippet: my_list = [(1, 'one'), (2, 'two'), (3, 'three')] my_tup = tuple([(k, v) for k, v in my_list]) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From codedivine at gmail.com Fri Jun 17 17:13:19 2005 From: codedivine at gmail.com (Rahul) Date: 17 Jun 2005 14:13:19 -0700 Subject: Multiple instances of a python program In-Reply-To: References: <1118947630.385547.231370@g43g2000cwa.googlegroups.com> Message-ID: <1119042799.954464.39790@g44g2000cwa.googlegroups.com> Hi. I will look into it..thanks rahul Jeremy Sanders wrote: > On Thu, 16 Jun 2005 11:47:10 -0700, Rahul wrote: > > > If you have a python script and you want that 75 copies of the script be > > run simultaneously how will you do it? Is there anyway to do so without > > running 75 copies of the python interpreter simultaneously? > > If you're running on Linux (and other Unixes perhaps), you could use the > os.fork() function to create independent child processes from a single > python process. I believe Linux forked processes share memory until a > section of memory is written to (copy on write functionality). > > If most of python is in a shared library, then this probably won't make > much difference. > > Jeremy From gerrit.muller at embeddedsystems.nl Tue Jun 28 10:43:38 2005 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Tue, 28 Jun 2005 16:43:38 +0200 Subject: whois like functionality on Windows? Message-ID: I am migrating a website from a UNIX based machine to an Windows machine. In the logfiles I got from the old machine I mostly got domain names and sometimes only IP addresses. The Windows machine seems to produce only IP addresses. Somehow I cannot find a windows solution to translate an IP address back into a domain-name. Searching with Google shows that more people have been wrestling with this problem. I did find working whois scripts, but unfortunately: - the verbose whois registrar information often forbids automated access - the information is rather distributed, so you have to somehow access sufficient servers - you still have to find the domain name in the sea of details returned I also found socket based solutions, but these solutions crash with the message "host not found" :-( Anyone suggestions? kind regards, Gerrit -- Gaudi systems architecting: From philippe at philippecmartin.com Mon Jun 27 23:43:12 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 03:43:12 GMT Subject: Better console for Windows? References: <1119926660.200528.303150@g47g2000cwa.googlegroups.com> Message-ID: Hi, You might want to check out ipyhton. http://ipython.scipy.org Regards, Philippe Brett Hoerner wrote: > This is a pretty basic, mostly un-python-related question, although I'm > asking because of Python. > > Is there a different shell I can use (other than cmd.com) to run Python > in, where I can full-screen the window (if I pleased), etc? As it is, > things that would run far off the right have to be word wrapped after > very few characters. > > Another problem with cmd.com is when I run IPython, if I have an error, > or tab or anything, I get the speaker beep (ala linux) but I can't find > a way to turn it off. This is a huge problem because I cannot disable > my system speaker on my laptop (not even in BIOS like my old one, and > it's an "error", it bypasses the fact that all my sound is muted in > Windows) and I get incredibly loud beeps all the time (because I suck) > which would not be acceptable while I'm coding on the sly in boring > class. > > Ideas? The only thing I can think of now is using Putty to SSH into a > machine, no beeps there, and I can resize... but I don't have a machine > to SSH into, much less one with all the stuff I want on it. > > Thanks in advance. > Brett From peter at engcorp.com Fri Jun 24 21:21:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 21:21:34 -0400 Subject: Newbie question: how to keep a socket listening? In-Reply-To: <1119660879.852664.167100@f14g2000cwb.googlegroups.com> References: <1119637288.536579.249340@z14g2000cwz.googlegroups.com> <11bok3btkedg151@corp.supernews.com> <1119660879.852664.167100@f14g2000cwb.googlegroups.com> Message-ID: ncf wrote: > Heh, like I said. I was not at all sure. :P > > Nevertheless, could this be the problem? =\ You *may* correct, mainly because the OP's code doesn't appear to spawn off new threads to handle the client connections, which means he can handle only one connection at a time. Specifically, while he is talking to one client he is not also in an accept() call on the server socket, which means there will be (because of the listen(1) call) only a single pending connection allowed in the backlog. I haven't attempted a thorough analysis... just this much, trying to see whether it is obvious that the listen(1) is at fault -- and it's not obvious. I thought this response might clarify the meaning of listen(1) a little bit for some folks nevertheless. -Peter From bokr at oz.net Sun Jun 26 16:49:45 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 26 Jun 2005 20:49:45 GMT Subject: slicing a bsddb table, eg. for rec in bsddb["AArdvark":"zebra"]: print rec References: <1118600533.4398.21.camel@localhost> Message-ID: <42bf1128.276877849@news.oz.net> On Sun, 12 Jun 2005 16:49:57 -0500, Skip Montanaro wrote: > > Neville> # I was expecting a slice of an index file to yield a > Neville> # generator so not all the records need to be read from disk.... > >Slicing is a feature of sequence types, not mapping types. > > >>> import string > >>> d = dict(zip(string.lowercase, string.uppercase)) > >>> d > {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', ...} > >>> d["a":"z"] > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unhashable type > >>> import UserDict > >>> d2 = UserDict.UserDict(d) > >>> d2 > {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', ...} > >>> d2["a":"z"] > Traceback (most recent call last): > File "", line 1, in ? > File "/Users/skip/local/lib/python2.5/UserDict.py", line 17, in __getitem__ > def __getitem__(self, key): return self.data[key] > TypeError: unhashable type > >The unhashable type it's referring to is the slice object generated by the >"a":"z" notation: > > >>> hash(slice("a", "z")) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: unhashable type > >If you look at help on the slice type, you'll see that it takes three args: > > class slice(object) > | slice([start,] stop[, step]) > | > | Create a slice object. This is used for extended slicing > | (e.g. a[0:10:2]). > | > >Step sizes really only make sense for sequence indices. > Yes, but if you have an implicit sort assumption for your keys, you can treat them as a sequence, and slice out the keys of interest and get their values, e.g., (no guarantees, not tested beyond what you see, that I just hacked here ;-) >>> class SliceDict(dict): ... def __getitem__(self, i): ... if type(i) is slice: ... keys = sorted(self.keys()) ... start = i.start; stop = i.stop ... try: start = keys.index(start) ... except ValueError: ... if start is not None: raise KeyError, start ... try: stop = keys.index(stop ) ... except ValueError: ... if stop is not None: raise KeyError, stop ... return [dict.__getitem__(self, k) for k in keys[start:stop]] ... else: ... return dict.__getitem__(self, i) ... >>> sd = SliceDict(a=1,b=2,z=26,k=11) >>> sd['b':'z'] [2, 11] >>> sd['b':] [2, 11, 26] >>> sd[:'z'] [1, 2, 11] >>> sd['b':'z'] [2, 11] >>> sd['b'] 2 >>> sorted(sd.items()) [('a', 1), ('b', 2), ('k', 11), ('z', 26)] >>> sd['x':'k'] Traceback (most recent call last): File "", line 1, in ? File "", line 8, in __getitem__ KeyError: 'x' >>> sd['x'] Traceback (most recent call last): File "", line 1, in ? File "", line 14, in __getitem__ KeyError: 'x' Hm, None as an actual key might be a little problematical though ;-) I would think this could be a handy way to get data base records that were selected from a range of sorted keys using sql and loading a dict like the above. Regards, Bengt Richter From ognjen at mailshack.com Thu Jun 2 16:29:24 2005 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Thu, 02 Jun 2005 21:29:24 +0100 Subject: Formatting Time Message-ID: <429F6C24.8000404@mailshack.com> I never thought id need help with such a thing as time formatting (admittadly i never did it before) but ok, i guess there is a first for everything. I have a float variable representing seconds, and i want to format it like this: 0:00:00 (h:mm:ss) Now search as I might i am finding this quite elusive, i had a look at the time module but that seems overly complicated for this. Anyone got any simple solutions to doing this? cheers! From devlai at gmail.com Tue Jun 28 15:03:09 2005 From: devlai at gmail.com (Devan L) Date: 28 Jun 2005 12:03:09 -0700 Subject: I need help figuring out how to fix this code. In-Reply-To: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> References: <42c1997b$0$6975$b9fe7a78@news.usenetrevolution.com> Message-ID: <1119985388.875820.143080@z14g2000cwz.googlegroups.com> password = raw_input("Type in the password, please: ") while password != "hello": print "Incorrect password!" Wouldn't this print "Incorrect password" untill the end of time if you didn't supply the correct password? From trentm at ActiveState.com Mon Jun 13 12:19:58 2005 From: trentm at ActiveState.com (Trent Mick) Date: Mon, 13 Jun 2005 09:19:58 -0700 Subject: searching for IDE In-Reply-To: References: <1118602945.370653.226760@f14g2000cwb.googlegroups.com> Message-ID: <20050613161958.GE30983@ActiveState.com> [Grumman wrote] > alexrait1 wrote: > > I need an IDE for python that has the ability to show the filds of a > > class when I write "." > > Just the way it works in eclipse/JBuilder with java or visual studio > > with c++ > > For now I treid eric3 and IDLE they don't do this... > > > > The ActiveState python editor (pythonwin?) does this. To be clear: ActivePython (ActiveState's distro of Python) includes the PyWin32 extensions by default on Windows. PyWin32 is an open source set of extensions for Python on Windows. The PyWin32 extensions include a Python editor called Pythonwin. http://www.activestate.com/Products/ActivePython/ http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/about.html ActiveState also has a product called Komodo that is an IDE for a number of dynamic languages: Python, Perl, PHP, Tcl, etc. http://www.activestate.com/Products/Komodo/ For Visual Studio users, ActiveState also has a VS.NET plugin for Python (Visual Python), and plugins for Perl and XSLT as well. http://www.activestate.com/Products/Visual_Python/ Cheers, Trent -- Trent Mick TrentM at ActiveState.com From fredrik at pythonware.com Wed Jun 15 12:54:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Jun 2005 18:54:07 +0200 Subject: Tkinter Question References: <23B7F3E89F1D424C96B13402B5F514D3048A55F9@ntm007.apsc.com> Message-ID: Nicholas.Vaidyanathan at aps.com wrote: > Thanks for all the help guys... I'm a bit confused as to the inner > workings of the Tkinter system (I'm both a Python and a GUI n00b). I was > hoping that by slapping the x on button python was doing some cool > dynamic variable creation (i.e. creating 9 variables with 1 loop using > the x as a variable to modify the identifier), but I suppose you can't > do that in Python (or can you?) that's what lists are for (see the python tutorial for details). > I'm a little confused as to why self.button.text doesn't work but > self.button["text"] does, can someone explain this? x.text and x["text"] are two different operations in Python, and Tkinter uses the former for widget methods, and latter for widget options. (w[x] is a shortcut for x.cget(x), btw) From hipandey at yahoo.co.in Sun Jun 5 13:47:06 2005 From: hipandey at yahoo.co.in (abhishek pandey) Date: Sun, 5 Jun 2005 10:47:06 -0700 (PDT) Subject: how can delay be caused in tcp connection Message-ID: <20050605174706.29785.qmail@web8509.mail.in.yahoo.com> sir, i am new to python. plz tell me how to cause delay in sending data through tcp connection. If can be implemented in python then plz let me know. waiting for reply from anyone thanx a lot.. its abhishek --------------------------------- Discover Yahoo! Get on-the-go sports scores, stock quotes, news & more. Check it out! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Mon Jun 13 15:24:38 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 13 Jun 2005 12:24:38 -0700 Subject: Adding to Exception.args In-Reply-To: References: Message-ID: <42add650$1@nntp0.pdx.net> Andreas Beyer wrote: > I came up with the following code: > inp = file(file_name) > for n, line in enumerate(inp): > try: > # parse line ... > except Exception, e: > inp.close() # Is this necessary for 'r' files? > args = list(e.args) > args.insert(0, 'line: %d'%(n+1)) > e.args = tuple(args) > raise inp = open(file_name) # GvR prefers this style, not file try: for n, line in enumerate(inp): try: # parse line ... except Exception, e: e.args = e.args + ('line: %d' % (n + 1),) # tuple add raise finally: inp.close() # it is certainly more portable, and more readable > Is there any specific order to the arguments in e.args? > Should my 'user argument' be at the beginning or at the end of e.args? If you are going to play with it, it is more likely that indices are used (so making e.args[0] refer to the same thing may help). The __str__ method of the Exception is responsible for formatting. If you "wrap" an exception that has its own __str__ method, it may well expect the args tuple to hold a precise number of elements (and therefore fail to convert to a string). --Scott David Daniels Scott.Daniels at Acm.Org From tim.golden at viacom-outdoor.co.uk Thu Jun 23 08:51:19 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 23 Jun 2005 13:51:19 +0100 Subject: python create WMI instances Message-ID: <9A28C052FF32734DACB0A288A3533991EBB92C@vogbs009.gb.vo.local> [future_retro at yahoo.co.uk] | I've got as far as this. I don't get any errors but still no | printer???? | | >>> import win32com.client | >>> WBEM = | win32com.client.GetObject(r"winmgmts:{impersonationLevel=imper | sonate}!\\" + "." + r"\root\cimv2") | >>> printer = WBEM.Get("Win32_Printer").SpawnInstance_() | >>> printer.Properties_('DeviceID').Value = 'myprinter' | >>> printer.Properties_('DriverName').Value = 'HP 2000C' | >>> printer.Properties_('Location').Value = 'myoffice' | >>> printer.Properties_('Network').Value = 'True' | >>> printer.Properties_('Shared').Value = 'True' | >>> printer.Properties_('ShareName').Value = 'myprintershare' | >>> printer.Put_ | | Do I need to specify any flags with Put_ ? Well you certainly need to call it -- printer.Put_ () -- and not just refer to it. But maybe that's just a cut-and-paste problem. In theory (according to the docs) you could pass a CREATE_ONLY flag (or something like that) but I don't think it's strictly necessary. I'd imagine that it would create if it didn't exist. Check out msdn for more details than you want to know. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From peter at engcorp.com Fri Jun 24 09:01:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 24 Jun 2005 09:01:52 -0400 Subject: howto load and unload a module In-Reply-To: References: Message-ID: Guy Robinson wrote: > Some of these scripts could potentially be quite large. Also the list of > scripts could be quite large. So the main reason for unloading modules > is to save memory. Unless you're talking megabytes of bytecode (do a "wc *.pyc" on the compiled files and see) it's probably not worth the bother. Still, assuming the modules are pure Python, and don't do strange things like inject references to themselves or their data into other places (i.e. other modules, including sys or builtins), it should be possible to unload them simply by deleting all references to them, *including* manually removing them from sys.modules. How do you plan to import them? Using the import statement, or __import__, or some other means? How you do it will determine exactly what steps are required to free them up. Note also that this won't necessarily release any memory back to the operating system, and it won't necessarily unload any extension modules or other shared libraries that are loaded. The whole concept of "unloading" a module is pretty much undefined in Python, so whatever you can get is the best you can expect... -Peter From enleverlesO.OmcO at OmclaveauO.com Fri Jun 24 16:34:06 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 24 Jun 2005 22:34:06 +0200 Subject: Office COM automatisation - calling python from VBA References: <1119642545.750550.304450@g44g2000cwa.googlegroups.com> Message-ID: <42bc6e52$1$913$8fcfb975@news.wanadoo.fr> Hi ! Perso, j'utilise ?a (VBA) : Sub TestPonx() Dim oa As Object Set oa = CreateObject("Ponx.Mci") Cells(2, 4) = oa.PRet("123+45+6") Set oa = Nothing End Sub "Ponx.Mci" est le nom du serveur COM Python PRet() est ?quivalent ? eval() Michel Claveau From claird at lairds.us Wed Jun 22 14:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Wed, 22 Jun 2005 18:08:03 GMT Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> Message-ID: <8oioo2-0kn.ln1@lairds.us> In article , Dan wrote: . . . >> You wouldn't have to distribute the (rather expensive) Access application >> since this is little more than a front for the underlying DAO/ADO database >> libraries that are built into the warp and woof of MS Windows. Your Python >> application can address the DAO or ADO directly as these will libraries will >> be pre-installed and/or freely available for MS Windows. Fast, freely >> available, no license restrictions, and no need for extra downloads for a >> reasonably recent (Win2000, XP) operating system. >> > >And then XP Autoupdate executes, some of those Access/MSDE libraries are >updated, and you app is broken. Are you saying that Python-based applications are particularly vulnerable in this all-too-common scenario? If so, I'm not getting it; why is the architecture described more fragile than more traditional Windows-oriented development patterns? If not, then, ... well then I truly don't get your point. From tprimke at interia.pl Fri Jun 24 05:33:05 2005 From: tprimke at interia.pl (TPJ) Date: 24 Jun 2005 02:33:05 -0700 Subject: A tool for Python - request for some advice References: <1119333625.643631.286450@o13g2000cwo.googlegroups.com> Message-ID: <1119605585.777704.165910@o13g2000cwo.googlegroups.com> > So, to make sure I've understood (...) : you want to provide > a specialized install script for Python (3rd party modules, > non-standard locations, etc.) yes > You started in bash to deal with minority cases without an extant > Python install. My motivation was rather to avoid a bootstrap-like problems. I thought that writing a script in _Python_ for compiling _Python_ is just silly idea. I thought that bash (available even in rescue distros!) would be a better tool. > But clearly, there will be a Python install by the > time your bash script is done, or something will have gone very wrong. yes > That suggests implementing the custom installation work in Python, and > having a bash script that will Well... not exactly. My primary goal is to save time spent on downloading, uncompressing, reading documentation, configuring, compiling and installing software. So I want to write a tool that would allow me to spent a few minutes to tell it what to do - and then it would do it all. I would pay attention to this tool for a few minutes, instead of wasting much more time doing it all myself. I could check for a Python installation and install Python in standard way in case Python wouldn't be available but this would have following disadvantages: 1) It would be a large waste of time spent on installing Python in standard way. (Especially if user wouldn't like _standard_ Python installation. I'm working on this script because in most situations I'm not happy with such standard installation!) 2) It would lead to download a particular Python's version for a temporary purpose - and this means additional waste of time and bandwith. For now my script works as follows: 1) It allows user to configure all options and actions. 2) When user is ready it just does what it is supposed to do. The first stage is very important - it takes a few minutes and then all is done automatically. Thanks for your advice - it was really helpful. From jepler at unpythonic.net Sat Jun 11 22:17:22 2005 From: jepler at unpythonic.net (jepler at unpythonic.net) Date: Sat, 11 Jun 2005 21:17:22 -0500 Subject: TKinter -- '' event executing more than once? In-Reply-To: <6EKqe.115932$J25.63349@bignews6.bellsouth.net> References: <6EKqe.115932$J25.63349@bignews6.bellsouth.net> Message-ID: <20050612021718.GA19027@unpythonic.net> Bindings created on a Toplevel or Tk widget apply to *all* widgets in the same toplevel. So you're seeing a event for each widget you create... Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mwm at mired.org Sat Jun 4 20:49:24 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 04 Jun 2005 19:49:24 -0500 Subject: Alternative history References: <1117421732.677244.237730@g49g2000cwa.googlegroups.com> <86wtphtm3f.fsf@guru.mired.org> Message-ID: <86wtp9aaqz.fsf@guru.mired.org> claird at lairds.us (Cameron Laird) writes: > In article <86wtphtm3f.fsf at guru.mired.org>, Mike Meyer wrote: > . >>If it isn't a homework assignment, and you're honestly in such, then >>you should know there's been a lot of research in this area, because >>primes are important in cryptographic applications. Once again, google > . > There's been a lot of research in this area because some minds > burn to grasp the beauty of number theory, and can't stop think- > ing of Number despite blindness, hunger, family, political > oppression, and the other frailties to which humans are prone. Good point. Similar reasons seem to cause a lot of software to get written. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bpeng at rice.edu Sun Jun 19 12:20:30 2005 From: bpeng at rice.edu (Bo Peng) Date: Sun, 19 Jun 2005 11:20:30 -0500 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: Message-ID: Roy Smith wrote: > Can you give us some idea of what it is that you're trying to do? It pretty unusual to see > a requirement like that. def func(type_of_obj1, type_of_obj2, .....): callfunc( [ type_of_obj1 and obj1a() or obj1b(), type_of_obj2 and obj2a() or obj2b(), .... ]) callfunc can take arbitrary number of objects whose types are determined by type_of_obj1 etc. I was using a bunch of if/else to create objects and pass them to callfunc. Since type_of_obj1 etc are usually binary and obj1a() etc will never be false, the and/or solution does not look so bad in this case. Thanks. Bo From jepler at unpythonic.net Sun Jun 12 09:23:04 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 12 Jun 2005 08:23:04 -0500 Subject: TKinter -- '' event executing more than once? In-Reply-To: <0SPqe.90792$8S5.63138@bignews3.bellsouth.net> References: <6EKqe.115932$J25.63349@bignews6.bellsouth.net> <0SPqe.90792$8S5.63138@bignews3.bellsouth.net> Message-ID: <20050612132300.GA8036@unpythonic.net> For me, an 'is' test works to find out what widget the event is taking place on. #------------------------------------------------------------------------ import Tkinter def display_event(e): print "event received", e.widget, e.widget is t t = Tkinter.Tk() t.bind("", display_event) w = Tkinter.Entry(t) t.destroy() #------------------------------------------------------------------------ This program prints: event received .-1209415348 False event received . True if that fails, you could compare str(e.widget) and t._w, though this can give a false positive if you have multiple Tk() instances---each Tk() instance is called ".". Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From negroup at gmail.com Thu Jun 23 08:45:07 2005 From: negroup at gmail.com (Negroup) Date: 23 Jun 2005 05:45:07 -0700 Subject: User interfaces in console (dialog like) Message-ID: <2fdabf19.0506230445.249d063f@posting.google.com> Hi all. I need to provide to my users a graphical interface to be used from os' command line. Initially I thought something equivalent to Unix dialog, and googling around I have found Python Dialog (http://pythondialog.sourceforge.net/). This would be the perfect solution for me if it could be cross platform. However, it doesn't work on Windows, just on Linux/Unix. Do you guys know an alternative that fits my needings without moving from Python? Thanks, -ng From anna-s at internet.is Wed Jun 8 19:36:36 2005 From: anna-s at internet.is (Anna M.) Date: Wed, 8 Jun 2005 23:36:36 -0000 Subject: Tabnanny? Message-ID: <20050608233640.1CBDE7AB7E@mail.internet.is> Hello, i am very new to this. Only heard of python a week ago and have never posted before anywhere. But I am trying to rewrite a program that I made in C++ in Python, a radixSort I did as a school project. I get a Tabnanny Tokenizing Error that says Token Error: EOF in multi-line statement. I gather from the internet that it means I have a tab-error. I just can't seem to find it. Is this something you can help me with? Could I post my code here and you could look at it or is that a bit to much ;) Many thanks, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Thu Jun 23 19:07:26 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 23 Jun 2005 18:07:26 -0500 Subject: string capitalize sentence In-Reply-To: References: Message-ID: <17083.16558.675538.436340@montanaro.dyndns.org> dimitri> I came up with the following solution: dimitri> a = 'harry is a strange guy. so is his sister, but at least she is not a dimitri> guy. i am.' dimitri> b = a.replace('. ', '.') dimitri> splitlist = b.split('.') dimitri> newlist = [] dimitri> for i in range(len(splitlist)): dimitri> i = ''.join(splitlist[i].capitalize() + '.' dimitri> newlist.append(i) dimitri> cap = ' '.join(newlist).replace(' .', '') dimitri> print cap No need for the replace(). Just split on ". ". No need for a for loop either, or the temp variable cap. Use a list comprehension. The result is: print ". ".join([s.capitalize() for s in a.split(". ")]) Skip From kraus at hagen-partner.de Mon Jun 20 02:52:22 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Mon, 20 Jun 2005 08:52:22 +0200 Subject: catch argc-argv In-Reply-To: References: Message-ID: mg wrote: > Hello, > > I am writting bindings for a FEM application. In one of my function > 'initModulename', called when the module is imported, I would like to > get the argc and argv arguments used in the main function of Python. > So, my question is: does the Python API containe fonctions like > 'get_argc()' and 'get_argv()' ? > > Thanks, > > > Use sys.argv: http://python.org/doc/2.4.1/lib/module-sys.html HTH, Wolfram From twic at urchin.earth.li Mon Jun 13 19:04:10 2005 From: twic at urchin.earth.li (Tom Anderson) Date: Tue, 14 Jun 2005 00:04:10 +0100 Subject: implicit variable declaration and access In-Reply-To: <87fyvm6n01.fsf@hector.domek> References: <87fyvm6n01.fsf@hector.domek> Message-ID: On Mon, 13 Jun 2005, Peter Dembinski wrote: > Tom Anderson writes: > > [snap] > >> The MAtrix had evarything in it: guns, a juimping off teh walls, flying >> guns, a bullet tiem, evil computar machenes, numbers that flew, flying >> gun bullets in slowar motian, juimping into a gun, dead police men, >> computar hackeing, Kevin Mitnick, oven trailers, a old womans kitchen, >> stairs, mature women in clotheing, head spark plugs, mechaanical >> squids, Japaneseses assasins, tiem traval, volcanos, a monstar, slow >> time at fastar speed, magic, wizzards, some dirty place, Kung Few, >> fighting, a lot of mess explodsians EVARYWHERE, and just about anything >> else yuo can names! > > ...with greetings to Carnivore ;) Ah, poor old Carnivore. I sort of feel sorry for it, trying to find terrsts in the midst of an internet populated by a hojillion people jabbering about, well, everything, really. Maybe the FBI should hook up with the SETI at home guys. After all, if they can find intelligence in outer space, surely they can find it on the internet? Actually, on second thoughts ... tom -- When I see a man on a bicycle I have hope for the human race. -- H. G. Wells From pwatson at redlinepy.com Mon Jun 20 11:36:09 2005 From: pwatson at redlinepy.com (Paul Watson) Date: Mon, 20 Jun 2005 10:36:09 -0500 Subject: Using print with format to stdout generates unwanted space References: <3hmt4rFhnn89U1@individual.net> <42b6bc99@news.highway1.com.au> Message-ID: <3ho63fFi1o93U1@individual.net> Thanks for all replies. Ok. I agree. While printf() does tightly control formatting in C, it does not in Python. Using write() can be used to output with no changes to the data. "Tim Hoffman" wrote in message news:42b6bc99 at news.highway1.com.au... > Hi Paul > > Based on your description of what you want to do, print is probably not > the correct method of controlling output format. You should use write() > method of the file handle to get unadulterated output. > > print is working as documented . From the Python 2.3 documentation, > Section 6.6 The Print statement. > > "print evaluates each expression in turn and writes the resulting object > to standard output (see below). If an object is not a string, it is first > converted to a string using the rules for string conversions. The > (resulting or original) string is then written. A space is written before > each object is (converted and) written, unless the output system believes > it is positioned at the beginning of a line. This is the case (1) when no > characters have yet been written to standard output, (2) when the last > character written to standard output is "\n", or (3) when the last write > operation on standard output was not a print statement." > > As you can see a space char is written and is correct as per the docs. > > Rgds > > Tim > > Paul Watson wrote: >> #!/usr/bin/env python >> >> # Using a print statement to stdout results in an >> # unwanted space character being generated at the >> # end of each print output. Same results on >> # DOS/Windows and AIX. >> # >> # I need precise control over the bytes that are >> # produced. Why is print doing this? >> # >> import sys >> >> # If this is a DOS/Windows platform, then put stdout >> # into binary mode so that only the UNIX compatible newline >> # will be generated. >> # >> try: >> import msvcrt, os >> msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) >> except: >> print 'This is not an msvcrt platform.' >> pass >> >> # Using print with newline suppressed generates a space at the >> # end of each print statement. >> # >> for i in range(3): >> print '%d,60,' % (i), >> for j in range(10): >> print '%d,' % (j), >> print '' >> >> # Using a list and doing a join does not result in the space >> # character being generated. >> # >> for i in range(3): >> alist = [] >> alist.append('%d,60,' % (i)) >> for j in range(10): >> alist.append('%d,' % (j)) >> print ''.join(alist) >> >> sys.exit(0) From lycka at carmen.se Wed Jun 8 07:50:21 2005 From: lycka at carmen.se (Magnus Lycka) Date: Wed, 08 Jun 2005 13:50:21 +0200 Subject: Destructive Windows Script In-Reply-To: References: Message-ID: rbt wrote: > data = ['0', 'a', '1', 'b', '2', 'c',\ > '3', 'd', '4', 'e', '5', 'f',\ > '6', 'g', '7', 'h', '8', 'i',\ > '9', 'j', '~', '!', '@', '#',\ > '$', '%', '^', '&', '*', ';'] > Note that the backslashes are redundant between pairs of [ ], ( ) or { }. Just write: data = ['0', 'a', '1', 'b', '2', 'c', '3', 'd', '4', 'e', '5', 'f', '6', 'g', '7', 'h', '8', 'i', '9', 'j', '~', '!', '@', '#', '$', '%', '^', '&', '*', ';'] (Not that it solves your disk wiping issue.) From peter at engcorp.com Thu Jun 9 14:20:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Jun 2005 14:20:04 -0400 Subject: Exe file In-Reply-To: References: Message-ID: Philip Seeger wrote: > I'm sorry for that newbie question but how can I compile a program (a .py > file) to an executable file? To save you what might be much wasted time on a wild goose chase, could you please tell us why you want to do this? (performance, protection from prying eyes, easier distribution, or some other reason?) -Peter From andreas at kostyrka.org Thu Jun 2 16:50:31 2005 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Thu, 02 Jun 2005 22:50:31 +0200 Subject: Software licenses and releasing Python programs for review In-Reply-To: References: <1117245014.218831.317750@g14g2000cwa.googlegroups.com> <1117392779.263376.236200@o13g2000cwo.googlegroups.com> <1117694543.931985.290720@g44g2000cwa.googlegroups.com> <7xd5r55j85.fsf@ruckus.brouhaha.com> Message-ID: <1117745432.13995.39.camel@andi-lap> Am Donnerstag, den 02.06.2005, 17:52 +0000 schrieb Karl A. Krueger: > Andreas Kostyrka wrote: > > *) GPL is not acceptable for "library" stuff, because as a software > > developer I'm sometimes forced to do "closed" stuff. > > (Yep, even nowadays there are place where it's basically a legal > > requirement.) > > I'm curious about this last one. > > The GPL does not require that derivative works be published, or that > they be donated back to the original author. All it requires is that > you pass on the rights that you received to the recipient of your > derivative work -- in this case, your customer alone. > > Of course, if your customer is a proprietary software firm looking to > own and sell the software restrictively, then they don't want those > terms. But if they're just looking to use it privately and internally, > I'm curious how the GPL would get in the way of that. Well, basically there are some obstacles: a) legal departments b) the feeling of the customer that he gets something "less" (because the customer doesn't have full control) c) problem cases like external contractors Basically my points are: a) there are certain "feelings" that seem to be common to most open source people. They might vary quite a bit in details but somehow we all swim more or less in the same river. b) as an example I've explained what my personal position in this is. Another take on the GPL (again my philosophy) is, that a license is good if it doesn't restrict. GPL'ed projects are successful mostly when the GPL adds benefits. GPL licensed projects have benefits: * strong anti-fork pressure. (Because you cannot just fork the code and go closed. Any fork must have a real good reason d'etre or it will die.) * community orientation -> GPL gives a strong "it's our code we are working on" feeling. * a growing number of software that is only available under the GPL. But it also has a number of drawbacks, like: * It forces the GPL (more or less) on all users [applies only to library building blocks] * Without copyright assignments it leads to patchy ownership structure. E.g. changing the license for the Linux kernel would be a really major undertaking. The point is that the license should be tailored to the intended use of your software. And think about it like that: "What can I give my users so that they become interested in my software?" Just being able to do something like burning a DVD might be enough for many "typical" Windows users, but the opensource crowd usually demands more. Like in more blueprints, more rights, etc. And fact is that the basic environment without artifical constructs like intellectual property legaslation favors the users: Without patents, in most cases somebody will reimplement your software, if there is need. Without copyrights, the users will just copy your binary ;) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From spam.csubich+block at block.subich.spam.com Thu Jun 30 04:06:35 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Thu, 30 Jun 2005 04:06:35 -0400 Subject: twisted: not doing DNS resolutions? In-Reply-To: References: Message-ID: Christopher Subich wrote: > From what I can tell, the problem lies in that Twisted simply isn't > performing the DNS resolutions. From the connection factory's > startedConnecting method, print connector.getDestination() results in: > > IPv4Address(TCP, 'hostname', port) Update: after doing some diving in the twisted source, it is supposed to do that. My guess is that either it thinks the hostname is a valid ip address (unlikely), or a callback isn't actually getting called. This confuses me. From sjsorell at vti.ca Wed Jun 22 18:32:54 2005 From: sjsorell at vti.ca (Scott Sorell) Date: Wed, 22 Jun 2005 22:32:54 GMT Subject: voicemail program written with python Message-ID: Hello! I was wondering if anyone knows of any voicemail programs written in python or any tools I could use to make one? My non-profit needs voicemail and I wondered if there was anything that via a modem you could record messages etc. Any help'll be appreciated! SS From edvard+news at majakari.net Wed Jun 29 06:08:30 2005 From: edvard+news at majakari.net (Edvard Majakari) Date: Wed, 29 Jun 2005 13:08:30 +0300 Subject: ANN: PyDev 0.9.5 released References: <42A720BD.5050701@esss.com.br> Message-ID: <87mzp9a31d.fsf@titan.staselog.com> Dave Cook writes: >> PyDev - Python IDE (Python Development Enviroment for Eclipse) version >> 0.9.5 has just been released. > > Does it work with the newly released Eclipse 3.1? Seems to work for me (but I've only coded one smallish Python program with it) -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; From skromta at gmail.com Sat Jun 18 03:41:06 2005 From: skromta at gmail.com (Kalle Anke) Date: Sat, 18 Jun 2005 09:41:06 +0200 Subject: Migrating from Windows to OS X References: <1119079582.973569.191490@f14g2000cwb.googlegroups.com> Message-ID: <0001HW.BED99CB20042B4FEF0407550@news.individual.de> On Sat, 18 Jun 2005 09:26:23 +0200, ladasky at my-deja.com wrote (in article <1119079582.973569.191490 at f14g2000cwb.googlegroups.com>): > I am sitting in front of a nice new PowerBook portable which has OS > 10.4 installed. The Python.org web site says that Apple has shipped OS > 10.4 with Python 2.3.5 installed. How exactly do I access this? I > have searched through the Applications and Libraries folders. I found > the site-packages directory, but nothing other than that. Launch Terminal (can be found in /Application/Utilities/) type python that's it jem From ola.natvig at infosense.no Tue Jun 14 04:00:01 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: 14 Jun 2005 10:00:01 +0200 Subject: Regarding Content-type headers In-Reply-To: References: Message-ID: praba kar wrote: > Dear All, > > I have doubt regarding headers in cgi > programming. If I gives "Content-Type:text/plain" then > I try to print html contents. Is right or wrong after > giving content-type: text/plain? > > regards > Prabahar It's not wrong, but you won't get the results you want. If you want to display HTML your should send the content-type: text/html. regards Ola Natvig From cam.ac.uk at mh391.invalid Thu Jun 9 04:20:40 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 09 Jun 2005 09:20:40 +0100 Subject: Python Challenge web site In-Reply-To: <98OdnUvjYdn8LjrfRVn-qg@comcast.com> References: <98OdnUvjYdn8LjrfRVn-qg@comcast.com> Message-ID: Andy Leszczynski wrote: > http://www.pythonchallenge.com/ > > anybody get to the level 30? :-) No, I've run out of time. It is fun so far though. -- Michael Hoffman From derek.perriero at gmail.com Thu Jun 9 15:53:24 2005 From: derek.perriero at gmail.com (Derek Perriero) Date: Thu, 9 Jun 2005 15:53:24 -0400 Subject: Remove duplicates from list In-Reply-To: References: <17fc2016050609114439ad3fb0@mail.gmail.com> Message-ID: <17fc2016050609125328857d82@mail.gmail.com> Sorry for not being more clear. I'm using Zope to store the hours of each library on the campus. The hours of each library will be set on a basis of Monday - Friday. i.e. Monday for a specific library, let's say Downtown Campus Library will stored as an attribute of 8am - 9pm, in Zope, and each day till Friday will be stored as the hours dictate. I'm generating a print-out based on these hours and info for the general public. The goal of mine is to group all the libraries under one heading if they have the exact same hours, to cut back on redundancy when a user looks at it. So when I say: collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday + item.Friday + item.Saturday + item.Sunday, the order is already this preset configuration. I want 'collect' to be static so it can compare it against another libraries hours and group it if necessary. The libraries that fail to be duplicates of other libraries will be generated as usual under the grouped libraries. They will have a single heading. An example can be seen here of what I am trying to achieve: http://www.libraries.wvu.edu/hours/summer.pdf These are the outputs I failed to mention last time. What I want: ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - 5pm9am - 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - 5pmClosed'] What I am getting now: ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - 5pm9am - 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am - 5pmClosed'] Thanks, -Derek On 6/9/05, Chris Lambacher wrote: > > It is very unclear what you are trying to do. Why not explain what > you want the output to be. You will get better answers. > > As a first stab at what you are doing wrong: > collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday > + item.Friday + item.Saturday + item.Sunday > > The above is string addition and the result is a string. The ouput > you provide is in fact a list with no duplicates, i.e. there are no > two strings the same. > > If order is not important to you a structure that will give you an > 'unordered list with no duplicates' is a set (available in the std > library in Python 2.3 and 2.4, see the cookbook for recipies for > earlier versions of Python). Note that sets are unordered, i.e. no > guarentee is made about what order the elements are accessed in when > you iterate over them. > > -Chris > > On 6/9/05, Derek Perriero wrote: > > I've been un-triumphantly trying to get a list of mine to have no > repeats in > > it. First, I'm pulling attributes from Zope and forming a list. Next, > I'm > > pulling those same values and comparing them against the same list and > if > > the values equal each other and are not already in the list, they append > to > > my 'nodupes' list. My current result is showing what I put in I am > getting > > out. Below the code is my output of 'nodupes' list. Here's the snippet. > > > > regHours = context.getMainPrint(); <---attributes from Zope > > > > libslist = [] > > nodupes = [] > > > > #collect libraries > > for libs in regHours: > > cache = libs.Monday + libs.Tuesday + libs.Wednesday + libs.Thursday + > > libs.Friday + libs.Saturday + libs.Sunday > > libslist.append(cache) > > > > #pull repeated values > > for item in regHours: > > collect = item.Monday + item.Tuesday + item.Wednesday + item.Thursday + > > item.Friday + item.Saturday + item.Sunday > > libName = item.libraryName > > > > for libs in libslist: > > if collect == libs and libs not in nodupes: > > nodupes.append(libs) > > > > My Current Output: > > ['8am - 9pm8am - 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pm6pm - 10pm', > '8am - > > 9pm8am - 9pm8am - 9pmClosed8am - 5pm9am - 5pm6pm - 10pm', '8am - 9pm8am > - > > 9pm8am - 9pm8am - 9pm8am - 5pm9am - 5pmClosed', '9am - 8pm9am - 8pm9am - > > 8pm9am - 8pm9am - 8pm9am - 6pm12pm - 6pm', '9am - 5pm9am - 5pm9am - > 5pm9am - > > 5pm9am - 5pmClosedClosed', '10am - 5pm10am - 5pm10am - 5pm10am - 5pm10am > - > > 5pm10am - 5pmClosed'] > > > > Thanks > > > > > > > > > > > > -- > > Perriero, Derek > > derek.perriero at gmail.com > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > Christopher Lambacher > lambacck at computer.org > -- Perriero, Derek derek.perriero at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cpunerd4 at gmail.com Sat Jun 18 14:27:17 2005 From: cpunerd4 at gmail.com (cpunerd4) Date: 18 Jun 2005 11:27:17 -0700 Subject: extreme newbie In-Reply-To: References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> <1119105092.240065.224910@g44g2000cwa.googlegroups.com> <3hiq3lFh0dsfU1@uni-berlin.de> <1119106093.097295.320940@g44g2000cwa.googlegroups.com> <1119111817.610572.73580@g14g2000cwa.googlegroups.com> Message-ID: <1119119237.846538.259790@g43g2000cwa.googlegroups.com> the problem is that i don't even know the language yet. . . From kbilsted at hotmail.com Thu Jun 9 06:28:13 2005 From: kbilsted at hotmail.com (newseater) Date: 9 Jun 2005 03:28:13 -0700 Subject: multiple inheritance In-Reply-To: References: <1118303813.869435.141580@g49g2000cwa.googlegroups.com> <1118305667.847406.58280@g44g2000cwa.googlegroups.com> Message-ID: <1118312893.482453.112320@g44g2000cwa.googlegroups.com> how nice! is this due to a linearization taking place of A and B when compiling C ? is this a 'feature' of the language or its actual semantics to behave like this? > class IFoo(object): > def foo(self): > pass > > class A(IFoo): > def foo(self): > print "a" > super(A,self).foo() > > class B(IFoo): > def foo(self): > print "b" > super(B,self).foo() > > class C(A,B): > def foo(self): > print "c" > super(C,self).foo() > > >>> C().foo() > c > a > b From pyguy2 at gmail.com Tue Jun 28 09:37:41 2005 From: pyguy2 at gmail.com (pyguy2 at gmail.com) Date: 28 Jun 2005 06:37:41 -0700 Subject: windows/distutils question In-Reply-To: <7xd5q7xctb.fsf@ruckus.brouhaha.com> References: <7xd5q7xctb.fsf@ruckus.brouhaha.com> Message-ID: <1119965861.456293.153210@f14g2000cwb.googlegroups.com> If the environment variable: os.environ['APPDATA'] is present on non-English Windows, you may be able to use that to get what you need. john From kevin at rustybear.com Thu Jun 2 22:26:44 2005 From: kevin at rustybear.com (kosuke) Date: 2 Jun 2005 19:26:44 -0700 Subject: optparse.py: FutureWarning error References: <1117722584.910599.242900@g47g2000cwa.googlegroups.com> <429FBE20.8020608@lexicon.net> Message-ID: <1117765604.103092.154190@g47g2000cwa.googlegroups.com> man python --- COMMAND LINE OPTIONS -c command Specify the command to execute (see next section). This terminates the option list (following options are passed as arguments to the command). -d Turn on parser debugging output (for wizards only, depending on compilation options). -E Ignore environment variables like PYTHONPATH and PYTHONHOME that modify the behavior of the interpreter. -h Prints the usage for the interpreter executable and exits. -i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the com- mand. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception. -O Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo. Given twice, causes docstrings to be discarded. -Q argument Division control; see PEP 238. The argument must be one of "old" (the default, int/int and long/long return an int or long), "new" (new division semantics, i.e. int/int and long/long returns a float), "warn" (old division semantics with a warning for int/int and long/long), or "warnall" (old division semantics with a warning for all use of the division operator). For a use of "warnall", see the Tools/scripts/fixdiv.py script. -S Disable the import of the module site and the site-dependent manipulations of sys.path that it entails. -t Issue a warning when a source file mixes tabs and spaces for indentation in a way that makes it depend on the worth of a tab expressed in spaces. Issue an error when the option is given twice. -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xreadlines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop. -v Print a message each time a module is initialized, showing the place (filename or built-in module) from which it is loaded. When given twice, print a message for each file that is checked for when searching for a module. Also provides information on module cleanup at exit. -V Prints the Python version number of the executable and exits. -W argument Warning control. Python sometimes prints warning message to sys.stderr. A typical warning message has the following form: file:line: category: message. By default, each warning is printed once for each source line where it occurs. This option controls how often warnings are printed. Multiple -W options may be given; when a warning matches more than one option, the action for the last matching option is performed. Invalid -W options are ignored (a warning message is printed about invalid options when the first warning is issued). Warnings can also be controlled from within a Python program using the warnings module. The simplest form of argument is one of the following action strings (or a unique abbreviation): ignore to ignore all warnings; default to explicitly request the default behavior (printing each warning once per source line); all to print a warning each time it occurs (this may generate many messages if a warning is triggered repeatedly for the same source line, such as inside a loop); module to print each warning only only the first time it occurs in each module; once to print each warning only the first time it occurs in the program; or error to raise an exception instead of printing a warning message. The full form of argument is action:message:category:module:line. Here, action is as explained above but only applies to messages that match the remaining fields. Empty fields match all values; trailing empty fields may be omitted. The message field matches the start of the warning message printed; this match is case-insensitive. The category field matches the warning category. This must be a class name; the match test whether the actual warning category of the message is a subclass of the specified warning cat- egory. The full class name must be given. The module field matches the (fully-qualified) module name; this match is case-sensi- tive. The line field matches the line number, where zero matches all line numbers and is thus equivalent to an omitted line num- ber. -x Skip the first line of the source. This is intended for a DOS specific hack only. Warning: the line numbers in error messages will be off by one! From andre.egners at rwth-aachen.de Thu Jun 30 16:17:52 2005 From: andre.egners at rwth-aachen.de (=?ISO-8859-1?Q?Andr=E9_Egners?=) Date: Thu, 30 Jun 2005 22:17:52 +0200 Subject: Scket connection to server In-Reply-To: References: Message-ID: <3ij2bgFlr9h0U1@news.dfncis.de> Steve Horsley wrote: > JudgeDread wrote: > >> hello python gurus >> >> I would like to establish a socket connection to a server running a >> service >> on port 29999. the host address is 10.214.109.50. how do i do this using >> python? >> >> many thanks >> >> > > Off the top of my head (so there could be errors): > > import socket > s = socket.Socket() > s.connect((10.214.109.50, 29999)) > s.send("Hello, Mum\r\n") > > That should point you in the right direction, anyway. > > There is a higher level socket framework called twisted that everyone > seems to like. It may be worth looking at that too - haven't got round > to it myself yet. > > Steve Just curious...where do these messages show up @10.214.109.50? andre -- Nothing is easier than being busy - and nothing more difficult than being effective. From hancock at anansispaceworks.com Tue Jun 28 23:37:58 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Tue, 28 Jun 2005 22:37:58 -0500 Subject: Set/Get attribute syntatic sugar In-Reply-To: References: <342dnXzzuo4WBlzfRVn-pg@powergate.ca> Message-ID: <200506282237.58883.hancock@anansispaceworks.com> On Tuesday 28 June 2005 07:07 pm, Elmo M?ntynen wrote: > Peter Hansen wrote: > > ???? ???????? wrote: > >> There is a syntactic sugar for item access in > >> dictionaries and sequences: > >> o[e] = v <-> o.__setitem__(e, v) > >> o[e] <-> o.__getitem__(e) > >> > >> where e is an expression. > >> > >> There is no similar way for set/get attribute for objects. > >> If e is a given name, then o.e = v <-> o.__setattr__(e, v) > >> o.e <-> o.__getattr__(e) > >> > >> Anybody thought about this issue? I'm pretty sure it's been discussed. Javascript unifies the concepts of dictionary access and object attribute access into the single concept of "associational array" (there are some limitations to the Javascript version, so they aren't really equivalent, but for simple cases they often are). In Javascript, the expression a['b'] means the same thing as a.b > > Perhaps not, but now that you've pointed it out they've taken the time > > machine back and fixed the problem before it arose: > > Maybe funny, but a bit too cocky for my taste. Robert kern is propably > right about what he really meant so don't be too hasty in the future, > right?). Looking at his code example I got the picture that he's of the > kind that could come up with something useful. So either he's > right(which I think is the case), or it's just the kind of silly mistake > all of us sometimes make. I sure think some one should look in to this > suggestion. Could be, but I think the absence of "sugar" in this situation is at least semi-intentional. We already have dictionary access for when this type of situation is needed. And if you really want an object that permits either type of access --- that is, for which dictionary access and attribute access are the same --- it is not difficult to create one. OTOH, if it were automatic, it would tend to erase any distinction between the two concepts. Stylistically, dictionaries are the "right" thing to use when the elements are going to be very fluid, whereas objects are expected to have more or less fixed attribute and method interfaces. Making "access to attribute by string name" more difficult than "access to dictionary value by string key" is one way to encourage the distinction. And, really, when you do need it, __getattr__ / __setattr__ aren't really *that* difficult to use. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From philippe at philippecmartin.com Tue Jun 28 13:31:43 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 28 Jun 2005 17:31:43 GMT Subject: Embedding python in C Message-ID: <3Qfwe.519$Ox3.92@newssvr12.news.prodigy.com> Hi, Is there a program out there that would generate the C code to instantiate objects and call them: ex: miracle.exe -i mymodule.py -o module_internface.c ? I seem to recall a _yes_ to that but I got a memory overflow :-) Thanks, Philippe From exarkun at divmod.com Wed Jun 8 20:36:13 2005 From: exarkun at divmod.com (Jp Calderone) Date: Wed, 8 Jun 2005 20:36:13 -0400 Subject: Fast text display? In-Reply-To: <7xekbcl6ix.fsf@ruckus.brouhaha.com> Message-ID: <20050609003613.15830.1645536561.divmod.quotient.3161@ohm> On 08 Jun 2005 17:26:30 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >Riccardo Galli writes: >> Using tkinter doesn't need downloading and installing only in Windows. >> In *nix is not so common to have tcl/tk installed (and probably in Mac too) > >Hmm, in the Linux distros that I'm used to, tcl/tk is preinstalled. I >had the impression that it was included with Python but obviously I >haven't looked that closely. What does "included with Python" mean anyway? Different packagers make different decisions. Some may include Tcl/Tk, others may exclude it. Some may provide a separate but trivially-installable package for it. On systems with reasonable package managers, it barely makes a difference, as any packaged software is at most one or two simple commands away. This applies to other libraries as well, of course. Installing wxPython on Debian is a 5 second ordeal. This is not to say debian is awesome and you should go install it right now or *else*, just to say that the installation of a single piece of software can vary greatly in difficulty between different platforms. Jp From guy.lateur at b-b.be Thu Jun 16 10:38:58 2005 From: guy.lateur at b-b.be (Guy Lateur) Date: Thu, 16 Jun 2005 14:38:58 GMT Subject: Where is Word? References: Message-ID: <6agse.122273$pX2.6921312@phobos.telenet-ops.be> Ok, I've tried various proposed solutions, and this is what I've come up with: # get Word path wordKey = win32api.RegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths', 0, win32con.KEY_READ) wPath = win32api.RegQueryValue(wordKey, 'winword.exe') win32api.RegCloseKey(wordKey) # open/write tempfile & delete afterwards fD, fN = tempfile.mkstemp('.txt') fH = os.fdopen(fD, 'w') fH.write('blabla') fH.close() os.spawnl(os.P_WAIT, wPath, 'winword.exe', fN) os.remove(fN) The above seems to work ok, but if you run the script a second time without first closing Word(1), the os.spawnl() doesn't seem to block. As a consequence, the tempfile is not removed (because Word still has it open when os.remove(fN) is called). Is this behaviour normal? Anything I can do about this? Thanks, g From hancock at anansispaceworks.com Sat Jun 25 04:02:03 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 25 Jun 2005 03:02:03 -0500 Subject: a dictionary from a list In-Reply-To: <1119652006.368615.153320@z14g2000cwz.googlegroups.com> References: <2133494.bAtaJnSUkF@teancum> <1119652006.368615.153320@z14g2000cwz.googlegroups.com> Message-ID: <200506250302.03657.hancock@anansispaceworks.com> On Friday 24 June 2005 05:26 pm, infidel wrote: > dict((x, None) for x in alist) or if you want it to run in 2.3 (before "generator expressions"): dict( [(x,None) for x in alist] ) Before the dict constructor, you needed to do this: d={} for key in alist: d[key]=None which is still only 3 lines and will run in Python 1.5, IIRC. -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From http Thu Jun 9 21:39:26 2005 From: http (Paul Rubin) Date: 09 Jun 2005 18:39:26 -0700 Subject: Fast text display? References: <7xu0k8s6to.fsf@ruckus.brouhaha.com> <863brr6xiw.fsf@guru.mired.org> <7xzmtzm9vi.fsf@ruckus.brouhaha.com> <86is0n57u4.fsf@guru.mired.org> Message-ID: <7xis0n9ei9.fsf@ruckus.brouhaha.com> Mike Meyer writes: > > OK. But I found on RH9 and FC3, as well as on Windows, that tcl/tk > > was preinstalled (or included with Python). I didn't find wxwidgets > > preinstalled on any of those systems. > > I think posts are getting crossed here. The python sources you get > from www.python.org don't include tcl or tk, which is how the poster I > was replying to specified things. Here's what I believe the situation is: RH9: tcl/tk preinstalled, tkinter included with python. Once I install RH9, I can use Python, tkinter, and tcl/tk without downloading anything additional. FC3: same as RH9 Windows: tcl and tk and tkinter all included in python.msi. Once I install Python, I can use tkinter/tcl/tk without installing anything additional. > > What about wxwidgets, which wxpython requires? > > If the package needs something and it's not installed, the package > system will get it and install it. That's the *point* of a package > system. Not really. A package system turns a software distro into a single file you can install. In some instances a package depends other packages and some package managers can then go chase down the dependencies, but that's not characteristic of packages per se, and while it's better than nothing, it's best to avoid it since the mechanism breaks a lot. Tcl/tk is a boneheaded system in many ways, but it's been very successful partly through the strategy of avoiding installation hassle by minimizing dependencies. > The package system can be configured in a number of different ways. My > configuration - with a broadband network connection - is to check the > local disk cache, then download anything that's missing. You can > preload the disk cache by doing "make fetch-recursive" if you > want. You can preload the cache by hand if you want, but the package > system is very picky about the version numbers of things it's trying > to build, so that'd be a pain. Best is to have just one package that doesn't depend on any other packages and doesn't need any further downloads, so once you've installed it, you're done. From eurleif at ecritters.biz Sat Jun 25 09:18:27 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 25 Jun 2005 13:18:27 GMT Subject: execute python code and save the stdout as a string In-Reply-To: <1119701023.896260.4770@g47g2000cwa.googlegroups.com> References: <1119701023.896260.4770@g47g2000cwa.googlegroups.com> Message-ID: jwaixs wrote: > I've a question. Can I execute a part of a python code and put it's > output in a string? >>> import sys >>> from cStringIO import StringIO >>> >>> def exec_and_get_output(code): ... old_stdout = sys.stdout ... sys.stdout = StringIO() ... try: ... exec code in {}, {} ... return sys.stdout.getvalue() ... finally: ... sys.stdout = old_stdout ... >>> exec_and_get_output("print 'foo'") 'foo\n' From grante at visi.com Fri Jun 24 21:38:37 2005 From: grante at visi.com (Grant Edwards) Date: Sat, 25 Jun 2005 01:38:37 -0000 Subject: Newbie question: how to keep a socket listening? References: Message-ID: <11bpdct9ccbld4b@corp.supernews.com> On 2005-06-25, Jp Calderone wrote: > The argument to listen() is only a _hint_ to the TCP/IP stack. > Linux, at least, will not create a buffer large enough for > only a single connection. You can test this easily: create a > socket, bind it to an address, call listen(1) on it, and > *don't* call accept(). Telnet (or connect somehow) > repeatedly, until your connection is not accepted. On my > system (Linux 2.6.10), I can connect successfully 8 times > before the behavior changes. I had noticed that once upon a time. I had forgotten that 8 was the minimum, but I do remember that 1 didn't result in a second connect failing. -- Grant Edwards grante Yow! Ha ha Ha ha Ha ha at Ha Ha Ha Ha -- When will I visi.com EVER stop HAVING FUN?!! From desertgarden at netscape.com Sat Jun 11 10:46:04 2005 From: desertgarden at netscape.com (Brian) Date: Sat, 11 Jun 2005 14:46:04 GMT Subject: cgi script runs under Opera, but not firefox In-Reply-To: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> References: <1118498439.747797.282150@g44g2000cwa.googlegroups.com> Message-ID: Yes, I agree that it is best to check the HTML source code of the page that is being generated. The server is obviously generating the code, but the difference here is how the two browsers are interpreting the HTML data. Check the source code for the HTML document. I bet the problem resides in the page itself. Brian --- nephish at xit.net wrote: > Hey there, > i have a python cgi script that prints out html just fine in the Opera > browser > but doesnt print at all under FireFox. > weird, eh? > i am getting nothing in the apache logs about any error. > perhaps its a firefox issue, but i doubt it. > > any suggestions. simple script here.. > From aetodd at gmail.com Fri Jun 17 14:24:11 2005 From: aetodd at gmail.com (Andrew) Date: 17 Jun 2005 11:24:11 -0700 Subject: Shortcut to initialize variables Message-ID: <1119032651.912256.319140@o13g2000cwo.googlegroups.com> Newb here... For one of my programs I want to initialize a variable for each letter of the alphabet. For example, a,b,c = 0,0,0. I don't think this works, but I'm wondering if I can do something similar to this: from string import ascii_lowercase class Blah: def __init__(self): for letter in ascii_lowercase: setattr(self,letter,0) Is there a way I can do something like this without using classes? Thanks From kent37 at tds.net Thu Jun 9 19:24:10 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Jun 2005 19:24:10 -0400 Subject: Generating HTML from python In-Reply-To: References: Message-ID: <42a8cf40$1_3@newspeer2.tds.net> Philippe C. Martin wrote: > Hi, > > I wish to use an easy way to generate reports from wxPython and feel > wxHtmlEasyPrinting could be a good solution. > > I now need to generate the HTML wxHtmlEasyPrinting can print: I need to have > a title followed by lines of text that do not look too ugly. If possible I > would like to use an existing module. > > Q1) Is there such a module ? > Q2) Is my approach fairly good ? There are many ways to do this. The simplest is just to mix HTML and Python code in your own module, as Thomas has shown. This is quick and easy to do but IMO it doesn't scale well to large pages or large number of pages; the mix of raw HTML and Python code is hard to work with. This page lists many alternatives: http://wiki.python.org/moin/WebProgramming The interesting categories from that page: "Templating Engines" provide a way to describe the HTML that is more-or-less independent of the code. They vary widely in style. If you want a lot of control over the generated HTML you probably want to use one of these. "HTML Shorthand Processors" provide an alternate way to specify markup and a program to convert the markup to HTML. reStructuredText is in this category. To use one of these you would still have to generate the alternate markup in your program similar to the simple HTML method. "HTML Generation class libraries" are libraries that make it easier to create HTML programmatically. This can be a good approach if the HTML is simple. I guess you can add many Python XML libraries to this category as well; for example you could use ElementTree to generate a model of an XHTML page and output it. Choosing within the categories depends a lot on personal preference, you just have to find a package whose style you like and whose features fit your needs. HTH, Kent From skip at pobox.com Sun Jun 12 17:49:57 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 12 Jun 2005 16:49:57 -0500 Subject: slicing a bsddb table, eg. for rec in bsddb["AArdvark":"zebra"]: print rec In-Reply-To: <1118600533.4398.21.camel@localhost> References: <1118600533.4398.21.camel@localhost> Message-ID: <17068.44549.53234.201300@montanaro.dyndns.org> Neville> # I was expecting a slice of an index file to yield a Neville> # generator so not all the records need to be read from disk.... Slicing is a feature of sequence types, not mapping types. >>> import string >>> d = dict(zip(string.lowercase, string.uppercase)) >>> d {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', ...} >>> d["a":"z"] Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type >>> import UserDict >>> d2 = UserDict.UserDict(d) >>> d2 {'a': 'A', 'c': 'C', 'b': 'B', 'e': 'E', 'd': 'D', ...} >>> d2["a":"z"] Traceback (most recent call last): File "", line 1, in ? File "/Users/skip/local/lib/python2.5/UserDict.py", line 17, in __getitem__ def __getitem__(self, key): return self.data[key] TypeError: unhashable type The unhashable type it's referring to is the slice object generated by the "a":"z" notation: >>> hash(slice("a", "z")) Traceback (most recent call last): File "", line 1, in ? TypeError: unhashable type If you look at help on the slice type, you'll see that it takes three args: class slice(object) | slice([start,] stop[, step]) | | Create a slice object. This is used for extended slicing | (e.g. a[0:10:2]). | Step sizes really only make sense for sequence indices. Skip From mike at jackalope.demon.co.uk Tue Jun 28 16:52:09 2005 From: mike at jackalope.demon.co.uk (Mike Holmans) Date: Tue, 28 Jun 2005 21:52:09 +0100 Subject: When someone from Britain speaks, Americans hear a "British accent"... References: <1119983260.720573.255200@z14g2000cwz.googlegroups.com> <11c38sv6ul8ck99@corp.supernews.com> Message-ID: On Tue, 28 Jun 2005 19:23:11 -0000, Grant Edwards tapped the keyboard and brought forth: >On 2005-06-28, muldoon wrote: > >> Americans consider having a "British accent" a sign of sophistication >> and high intelligence. > >That depends on the accent. I believe that's probably true for >the educated south of England, BBC, received pronunciation. I >don't think that's true for some of the other dialects from >northern areas (e.g. Liverpool) or the "cockney" accent. > >> Many companies hire salespersons from Britain to represent >> their products,etc. Question: When the British hear an >> "American accent," does it sound unsophisticated and dumb? > >I too have always wondered about this. Since you've acknowledged that it's only the RP accent which gets that respect in the US (and since I speak it, I rather enjoy my visits across the pond) and others are either cute or obvious hicks, it shouldn't be a surprise that the same applies to the wide range of accents used by Americans. The strong Appalachian accent of the guide who took us round some caves in WV last year was the epitome of unsophistication - although what he said was extremely informative and delved into some advanced science. My wife's an Okie, but she speaks the US equivalent of RP - the one used by newsreaders on the main terrestrial TV networks and which is commonly thought to be used mostly in Ohio and other places just south of the Great Lakes. If there's such a thing as a standard "American accent", that's it. It neither sounds dumb nor clever - just American. Some of those sonorous slow talkers from the South, and majestic bass African-Americans like James Earl Jones or Morgan Freeman, have far more gravitas than any English accent can: to us, such people sound monumental. But most of the obviously regional accents in the US sound cute or picturesque, while the ones Americans tend to regard as hick accents just sound comical. The problem which a lot of fairly-midstream American accent users face is that it's the same sort of thing which Brits try and imitate when they want to suggest a snake-oil salesman. At bottom, an American accent doesn't mark someone out to a Brit as dumb or unsophisticated, but the immediate suspicion generated is that they're a phony and likely to be saying stuff without much regard for its accuracy. Cheers, Mike From gregpinero at gmail.com Tue Jun 14 22:30:15 2005 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Tue, 14 Jun 2005 22:30:15 -0400 Subject: MySQLDBAPI In-Reply-To: <3h939qFfvmjfU1@uni-berlin.de> References: <2tqln2-6c3.ln1@news.interplanet.it> <312cfe2b05061408481a3e7de0@mail.gmail.com> <3h939qFfvmjfU1@uni-berlin.de> Message-ID: <312cfe2b05061419302497dd6@mail.gmail.com> The closest thing I found was libmysqlclient.a in /home/gpinero/rpmmysql/usr/lib/mysql/ I added that path to my library_dir in setup.py but I still get the same error message when I do python2.4 setup.py build I really appriciate your help. I really want to start web development in python. Thanks, Greg From jfine at pytex.org Wed Jun 29 02:43:19 2005 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 29 Jun 2005 07:43:19 +0100 Subject: Converting TeX tokens into characters Message-ID: <42C24307.8060709@pytex.org> I'm sort of wishing to convert TeX tokens into characters. We can assume the standard (i.e. plain) category codes. And that the characters are to be written to a file. This proceess to take place outside of TeX. Say in a Python program. Think of a pretty-printer. * Read the TeX in as tokens. * Write the TeX out as characters. My present interest is in the writer part. And I'd very much prefer to have human-editable output. So the writer should have methods for * Writing a string (not containing control sequences). * Writing a control sequence (or control symbol). And, like humans, it should also have a line length limit. Does anyone know of such a writer? Or something close? Or any projects that could use such a writer? -- Jonathan From kveretennicov at gmail.com Thu Jun 23 19:35:13 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Fri, 24 Jun 2005 01:35:13 +0200 Subject: suggestions invited In-Reply-To: <1119555027.087947.100970@g43g2000cwa.googlegroups.com> References: <1119433626.312619.8970@g43g2000cwa.googlegroups.com> <1119552092.000448.10230@g47g2000cwa.googlegroups.com> <1119555027.087947.100970@g43g2000cwa.googlegroups.com> Message-ID: <4660fe3005062316351e8dad5@mail.gmail.com> On 23 Jun 2005 12:30:27 -0700, Aditi wrote: > Thanks for ur effort... And I apologise for being sloppy in writing. > Well I agree the whole project sounds fictitious because it has been > assigned to me in that spirit. The project was explained to me in > just 5 minutes and so these are the only details I have and the only > documentation I have is a list of the 31 applications used in the > company and that the platform used in the company is OS 400. Pardon me, is it a real company or a fictious one? > > The reason why I posted this mail was to invite ideas as to how could I > make the best use of these details and suggestions because I myself > found these details way too less. I think I should have written about > this in the first mail to avoid frustration to the people who are > trying to help > me. > Anyways now that it is known that the project has been assigned to me > just for the heck of it would like to make my project such that they > want to use it...I would definately not let my work go wasted...So do > let me know what you think could be done in this direction. If you have real users, your first step is to talk to them to define project goals. Everything else (xml, python, etc.) is irrelevant until you know *what* you want to build. Go talk to your potential users, know why (if at all) they need this monitoring system, learn their current tools and processes, see how your system could help them do their job more efficiently. Don't start coding until you have clear understanding of requirements. There are lots of nice intelligent people on this list, but they can't substitute people you are building this system for :) - kv From tcris2005 at hotmail.com Sat Jun 18 20:33:03 2005 From: tcris2005 at hotmail.com (=?iso-8859-1?B?TElERVJBTsdBISE=?=) Date: 18 Jun 2005 17:33:03 -0700 Subject: MONEY, MONEYYYY Message-ID: <1119141183.493120.79880@g49g2000cwa.googlegroups.com> Querido Amigo, Voc? pode ganhar 50.000 REAIS ou mais nos pr?ximos 90 dias, parece imposs?vel? Prossiga lendo todos os detalhes (n?o h? nada escondido)... Aten??o: esta ? a tradu??o feita e adaptada para portugu?s. No final desta tradu??o encontrar? o original em ingl?s para eventual uso. DISCUTIDO NA T.V DOS EUA. Obrigado pelo seu tempo e interesse. Esta ? a carta acerca da qual muito se tem falado ultimamente nos notici?rios dos EUA. Devido ? popularidade desta carta na Internet, os principais notici?rios da noite dedicaram-lhe imenso espa?o; recentemente foi-lhe mesmo dedicado um espect?culo inteiro para a investiga??o do programa abaixo descrito, tentando concluir se realmente se pode ganhar legalmente dinheiro com este sistema. O espect?culo investigou se o programa era ou n?o legal. Provou-se de uma vez por todas que n?o h? absolutamente nenhum impedimento legal ? participa??o no programa. Isto ajudou a mostrar ?s pessoas que este ? um modo simples, inocente e divertido para obter dinheiro extra. Os resultados deste espect?culo foram verdadeiramente not?veis. O n?mero de pessoas participantes no sistema aumentou drasticamente. Considerando que todos ganham com o aumento do n?mero de participantes, tornou-se verdadeiramente excitante a participa??o no sistema. Voc? entender? o que queremos dizer quando o experimentar. EIS A DESCRI??O DO SISTEMA IMPRIMA ESTE TEXTO PARA REFER?NCIA FUTURA A seguinte oportunidade de rendimentos poder? ser muito interessante para si. Se voc? deseja ganhar mais de 50.000 contos em menos de 90 dias! Por favor leia o programa inclu?do... E NO FINAL... LEIA-O NOVAMENTE!!!!! ESTA ? UMA LEG?TIMA E LEGAL OPORTUNIDADE DE GANHAR MUITO DINHEIRO. N?o lhe exige que entre em contacto com pessoas, fazer qualquer trabalho dif?cil e, melhor que tudo, voc? nunca tem que deixar a sua casa, excepto para se deslocar ao correio. Se acredita que algum dia ganhar? a sorte grande que h? muito vem esperando, ent?o ELA CHEGOU! Simplesmente siga as instru??es, e os seus sonhos tornar-se-?o realidade. Esta ordem multi-n?vel de E-mail que comercializa programas, funciona perfeitamente... 100% todas as vezes. O E-mail ? a ferramenta de vendas do futuro. Beneficie das vantagens deste m?todo de publicidade AGORA!!! Quanto mais esperar, mais outras pessoas estar?o negociando. Ganhe o seu peda?o desta ac??o!!! O MARKETING de MULTI-N?VEL (MLM) ganhou, finalmente, respeitabilidade. Est? sendo ensinado na Universidade de Harvard, e em Stanford. O Wall Street Journal declarou mesmo que entre 50% e 65% de todos os bem ser?o vendidos por m?todos de servi?os multi-n?vel j? no final deste ano. Esta ? uma ind?stria de bili?es de d?lares e dos 500.000 milion?rios nos E.U.A., 20% (100.000) fez a sua fortuna nos ?ltimos anos usando sistemas MLM. Al?m disso, estat?sticas mostram que 45 pessoas se tornam milion?rios todos os dias usando Marketing de multi-n?vel. Durante o ?ltimo ver?o Donald Trump participou no espect?culo de David Letterman. Dave perguntou-lhe o que faria se perdesse a sua imensa fortuna e tivesse de recome?ar de novo do nada. Sem vacilar, Trump disse que criaria uma empresa que comercializasse em MLM. A audi?ncia come?ou a vai?-lo. Ele olhou a audi?ncia e respondeu - "? por isso que eu estou aqui sentando e voc?s est?o a? do lado de l?"! Com uma cadeia de marketing voc? tem duas fontes de renda. Comiss?es directas e comiss?es de vendas atrav?s das pessoas que voc? inicia no neg?cio. A renda residual ? o segredo do sistema. Significa que investindo apenas algum tempo e pouqu?ssimo dinheiro uma ?nica vez ir? cobrando novamente e novamente e novamente. A comercializa??o em rede, tamb?m significa ser pago pelo trabalho de outros. UMA NOTA PESSOAL DO CRIADOR DESTE PROGRAMA: Quando ler o relat?rio e os programa inclusos, voc? concluir? que tais programas, legais, n?o poderiam ter sido criados por um amador. Deixe-me falar-lhe um pouco de mim. Eu tive um neg?cio lucrativo durante 10 anos. Ent?o em 1979 o neg?cio entrou em queda. Contudo continuava fazendo o mesmo que anteriormente resultara perfeitamente, agora, por?m, simplesmente j? n?o funcionava. Finalmente compreendi. N?o era eu, era a economia que n?o evoluia desde 1945. N?o ser? necess?rio contar-lhe o que aconteceu, por exemplo, ? taxa de desemprego... provavelmente voc? saber? dessa terrivel experi?ncia em primeira m?o. O maior per?odo de sempre de fracassos e bancarrotas. A classe m?dia arriscava-se a desaparecer. Os que souberam como sobreviver investiram sabiamente e moveram-se para cima. Os que o n?o fizeram incluindo os que nunca tiveram qualquer coisa para economizar ou investir, passaram para baixo ao grau de pobres. Dando sentido ? frase "O RICO TORNA-SE MAIS RICO E O POBRE AINDA MAIS POBRE". Os m?todos tradicionais de ganhar dinheiro j? n?o permitiam mover para cima e ficar rico, a inflac??o al?m isso, tratou de que tal n?o acontecesse. Voc? acaba de receber a informa??o que lhe pode dar liberdade financeira para o resto da sua vida, sem "NENHUM RISCO" e "S? COM UM POUCO DE ESFOR?O". Voc? pode ganhar mais dinheiro nos pr?ximos meses do que jamais imaginou. Devo ainda dizer-lhe que n?o verei um ?nico centavo desse dinheiro, nem qualquer outro pessoa que tenha prestado o seu testemunho acerca deste programa. Eu j? fiz mais de 4 MILH?ES de D?LARES! Aposentei-me do sistema depois de enviar mais de 16.000 programas. Agora tenho v?rios escrit?rios que fazem estes e v?rios outros programas em todo o mundo. Siga o programa EXACTAMENTE DE ACORDO COM AS INSTRU??ES. N?o o mude de qualquer maneira. Ele funciona perfeitamente do modo como est?. Envie uma c?pia deste E-mail para todos aqueles que achar interessantes e com ambi??es. Uma das pessoas para quem voc? o enviou talvez o reenvie a outras e o seu nome estar? em todas elas! Lembre-se que quantos mais E-Mails enviar a potenciais interessados, mais potenciais clientes voc? poder? obter. Assim meu amigo, dei-lhe as ideias, a informa??o, o material e a oportunidade para se tornar financeiramente independente. A DECIS?O AGORA ? SUA! PENSE NISTO Antes de apagar este programa da sua caixa postal, como eu quase fiz, perca algum tempo a ler este texto e A PENSAR REALMENTE NELE. Pegue numa calculadora e fa?a contas a quanto vai ganhar. Seja o mais pessimista poss?vel acerca do n?mero de respostas que ir? receber e n?o importa o c?lculos que fa?a, voc? ainda continuar? ganhando muito dinheiro! Qualquer duvida que tenha desaparecer? quando chegarem as suas primeiras ordens. FUNCIONA! Jody Jacobs, Richmond, VA. EIS COMO ESTE PROGRAMA SURPREENDENTE LHE FAR? GANHAR MILHARES DE D?LARES INSTRU??ES: Este m?todo de AUMENTAR o seu capital funciona efectivamente. Eu estou seguro que voc? ganhar? 50.000 contos ou mais nos pr?ximos 90 dias. Antes que consiga dizer "Fui enganado...", por favor leia este programa cuidadosamente. N?o ? uma carta em cadeia, mas uma oportunidade perfeitamente legal de ganhar dinheiro. Basicamente, eis o que tem de fazer: como em todos os neg?cios de multi-n?vel, constru?mos n?s pr?prios o nosso neg?cio recrutando novos s?cios e vendendo os nossos produtos. Todos os Estados nos E.U.A. nos permitem recrutar s?cios empresariais para vendas multi-n?vel e n?s efectivamente oferecemos um produto para TODOS os d?lares que nos s?o enviados. AS SUAS ORDENS V?M PELO CORREIO E S?O SATISFEITAS ATRAV?S DE E-MAIL, assim voc? n?o est? pessoalmente envolvido em vendas. Tudo ? feito reservadamente em sua pr?pria casa, loja ou escrit?rio. Este ? o MELHOR sistema de Multi-n?vel de ordens por correio. Eis o que ter? de fazer: 1. Encomende todos os 4 relat?rios da lista abaixo. Se o dinheiro n?o abunda e os 4 contos n?o est?o todos dispon?veis pode comprar os relat?rios aos poucos: encomende-os ? medida que vai necessitando. Come?e por encomendar o N? 1 que ser? aquele que ter? de fornecer em primeiro lugar. Assim, o seu investimento inicial (relat?rio+carta a fazer a encomenda) n?o ultrapassa os 5,60 reais facilmente recuper?veis ao fim de poucos dias! * Para cada relat?rio envie 5 reais em dinheiro (para todos os endere?os fora de Portugal). (Se o endere?o for portugu?s envie ent?o5,00$ euros em notas). MENCIONE O N?MERO DO RELAT?RIO QUE EST? ENCOMENDANDO, O SEU ENDERE?O DE E-MAIL, O SEU NOME & ENDERE?O de RETORNO (no caso de haver algum problema) para a pessoa cujo nome aparece na lista como vendedor do respectivo relat?rio. * Quando fizer a sua encomenda, tenha a certeza que ordena cada um dos quatro relat?rios. Voc? precisar? de todos os quatro relat?rios de forma a poder guard?-los no seu computador e poder, por sua vez, revend?-los. * Dentro de alguns dias receber?, por E-mail cada um dos quatro relat?rios. Salve-os no seu computador assim eles estar?o acess?veis para que os envie aos milhares de pessoas que os ir?o encomendar. QUALQUER PESSOA EM TODO O MUNDO PODE FAZER ISTO. 2.a) N?o altere os nomes das pessoas que est?o listadas em cada relat?rio, ou a sua respectiva sucess?o na lista; se o fizer perder? a maioria dos seus lucros. Uma vez que entenda o modo como tudo funciona, voc? compreender? que ? do seu interesse em n?o fazer qualquer altera??o. Lembre-se que este m?todo tem sido testado, e nada h? a modificar na sua g?nese. b. Depois de encomendar os quatro relat?rios, use este mesmo an?ncio para reiniciar o seu ciclo. Remova o nome que se encontra debaixo do RELAT?RIO N? 4. (Esta pessoa j? antes tinha feito o mesmo e j? ganhou INDUBITAVELMENTE os seus 50.000 reais!) c. Mova o nome e endere?o debaixo de RELAT?RIO N? 3 para debaixo do RELAT?RIO N? 4. d. Mova o nome e endere?o debaixo de RELAT?RIO N? 2 para debaixo do RELAT?RIO N? 3. e. Mova o nome e endere?o debaixo de RELAT?RIO N? 1 para debaixo do RELAT?RIO N? 2. f. Insira o seu nome e endere?o no RELAT?RIO N? 1. Por favor tenha certeza que copia cada nome COM A M?XIMA PRECIS?O! 3. use esta carta tal como lhe foi enviada, inclusive a lista modificada de nomes, salvando-a no seu computador. N?o fa?a NENHUMA mudan?a ?s instru??es nela contidas. 4. agora voc? est? pronto para come?ar uma campanha de publicidade na NET! Anunciar na NET pode ser muito barato, e h? CENTENAS de lugares GR?TIS onde anunciar. (E-mail, newsgroups, etc). Outra via que poder? usar para anunciar ? atrav?s de listas de E-mail. Poder? comprar estas listas ou pagar a algu?m que as colija para si. COMECE IMEDIATAMENTE A SUA CAMPANHA! 5. Por cada 5 d?lares ou 5 reais que receber, tudo o que tem que fazer ? enviar por E-mail os relat?rio encomendados. ISSO ? TUDO! TENTE SER R?PIDO NAS SUAS RESPOSTAS. ENVIE OS RELAT?RIOS NO MESMO DIA EM QUE RECEBEU A ORDEM! Isso vai garantir que o E-mail que enviou, permite ao comprador iniciar as vendas com o seu nome nas listas! Para crescer rapidamente ? necess?rio ser-se pontual e cort?s. Lembre-se que a pessoa que lhe est? a enviar dinheiro est? a preparar-se para vender PARA SI, em cadeia, milhares de relat?rios! RELAT?RIOS DISPON?VEIS Encomende cada RELAT?RIO por N?MERO e NOME Notas: - ENVIE SEMPRE 5 reais ou euros (para Portugal) EM DINHEIRO POR CADA RELAT?RIO. - ENVIE SEMPRE A SUA ORDEM EM CORREIO AZUL PARA ENTREGA MAIS R?PIDA. -embrulhe as notas em pelo menos duas folhas de papel. -numa dessas folhas de papel, inclua o n?mero e o nome do relat?rio que est? ordenando, bem como o seu E-mail, nome e endere?o postal. REPORT 1 "The Insider's Guide to Advertising for Free on the Internet" ENCOMENDE O RELAT?RIO N? 1 A: TEREZA CRISTINA RUA PIRAJUSSARA, 36A PQ JUREMA GUARULHOS - S?O PAULO CEP 07244-13 - BRASIL ********** REPORT 2 "The Insider's Guide to Sending Bulk E-mail on the Internet" ENCOMENDE O RELAT?RIO N? 2 A: Pedro Filipe Farracho Silva E.N. n?9 - Pr?x. Boavista Carapinheira 2640 Igreja Nova - Mafra *********** REPORT 3 "The Secrets to Multilevel Marketing on the Internet" ENCOMENDE O RELAT?RIO N? 3 A: Renato Figueiredo Vivenda Faustino Apartado 75 8400 Ferragudo ************* REPORT 4 "How to Become a Millionaire Utilizing the Power of Multilevel Marketing and the Internet" ENCOMENDE O RELAT?RIO N? 4 A: Paulo Jorge dos Santos Apartado 517 8500 Portim?o *************** AQUI EST? COMO ESTE PLANO SURPREENDENTE O FAR? GANHAR DINHEIRO Digamos que voc? decide come?ar s? com um pequeno n?mero de endere?os (E-mail) para ver como tudo funciona. Assumamos que a sua meta ? conseguir que 10 pessoas participem no seu primeiro n?vel. (Colocando um lote de an?ncios GR?TIS na Internet adquirir? FACILMENTE um n?mero maior de respostas). Assumamos tamb?m que, de todos eles, apenas 10 aderem ao sistema. Sigamos este exemplo (pessimista) para alcan?ar os resultados ESTONTEANTES abaixo descritos. 1? n?vel: os seus 10 compradores com 5,00 = 50,00 (j? recuperou o que investiu!) 2? n?vel: 10 aderentes conseguidos pelos primeiros 10 (5,00 x 100) = 500,00 3? n?vel: 10 aderentes desses 100 (5,00 x 1.000) = 5.000 4? n?vel: 10 aderentes desses 1.000 (5.000 x 10.000) = 50.000.000 TUDO SOMADO:------- 55.550,00 Lembre-se que tudo isto se passa assumindo que apenas 10 pessoas aderem ao sistema e cada uma, por sua vez, s? recruta outras 10 pessoas. Pense por um momento o que acontecer? se eles recrutarem 20 participantes! Muitos conseguir?o decerto angariar centenas! PENSE NISTO! Os custos para que possa participar s?o rid?culos (seguramente voc? pode dispor de 20 d?lares ou 20,00reais). Obviamente j? tem uma conex?o ? Internet e o respectivo E-mail ? GRATUITO!!! O RELAT?RIO N? 3 ensina-lhe os m?todos mais produtivos para o uso do seu E-mail, bem como m?todos para adquirir listas de E-mail. Alguns vendedores de listagens tamb?m participam em vendas MLM! Aproximadamente 50.000 novas pessoas aderem em cada m?s ? Internet! SEGREDOS PARA O SUCESSO TRATE TUDO ISTO COMO O SEU NEG?CIO! Seja r?pido, profissional, e siga as instru??es com precis?o. *Envie IMEDIATAMENTE os quatro relat?rios porque: Quando voc? recebe uma ordem, tem que enviar o produto pedido obedecendo ?s Leis Postais e de Lotaria dos E.U.A, T?tulo 18, sec??es 1302 e 1341 ou T?tulo 18, Sec??o 3005 do C?digo Norte-Americano, bem como o C?digo de Registos Federais Vol. 16, sec??es 255 e 436, que determinam que "um produto ou servi?o deve ser fornecido em troca de dinheiro recebido". SATISFA?A AS SUAS ENCOMENDAS NO MESMO-DIA EM QUE AS RECEBE. Seja paciente e persistente com este programa. Se seguir as instru??es exactamente, ent?o os resultados ser?o indubitavelmente um ?xito! ACIMA DE TUDO, TENHA F? EM SI E ACREDITE QUE TER? SUCESSO! DIRECTRIZES PARA O SUCESSO Siga estas directrizes que lhe assegurar?o o seu sucesso: Se n?o receber 10 ou 20 ordens para o RELAT?RIO N? 1 dentro de duas semanas, continue anunciando at? que tal aconte?a. Ent?o, dentro de algumas semanas, receber? pelo menos 100 ordens para o RELAT?RIO N? 2. Uma vez recebidas 100 ou mais ordens para o RELAT?RIO N? 2, VOC? PODE RELAXAR, porque o sistema j? est? trabalhando para si, e o dinheiro continuar? chegando em quantidade! ? IMPORTANTE LEMBRAR-SE QUE: Cada vez que o seu nome ? rebaixado na lista, voc? ? colocado na frente de um Relat?rio DIFERENTE. Voc? pode SEGUIR O RASTO DO SEU PROGRESSO ao saber que relat?rio as pessoas lhe est?o encomendando. Se quiser gerar mais rendimentos, envie outro grupo de E-mails e comece todo o processo novamente! N?o h? limite ao rendimento neste neg?cio! TESTEMUNHOS "Este programa FUNCIONA, mas voc? tem que seguir todas as indica??es! Especialmente a regra de n?o tentar colocar o seu nome numa posi??o diferente; n?o funciona e voc? perder? muito do potencial rendimento. Eu sou a prova viva de que funciona. ? realmente uma grande oportunidade para ganhar dinheiro relativamente f?cil. Se escolher participar, siga exactamente, o programa e voc? estar? a caminho da total seguran?a financeira". Sean McLaughlin, Jackson, MS. "Meu nome ? Frank. Minha esposa, Doris e eu vivemos em Bel-Air, MD. Sou contabilista numa corpora??o norte-americana e ganho razoavelmente bem. Quando recebi o programa, gozei com a coisa, valendo-me dos meus conhecimentos sobre popula??o e percentagens envolvidas. Eu "sabia" que n?o funcionava. Doris ignorou totalmente a minha suposta sabedoria e atirou-se ? ideia de cabe?a. N?o s? a gozei como estava pronto para lhe deitar o velho "eu bem te avisei " quando a coisa desse em nada... muito bem, enganei-me! Dentro de duas semanas ela recebera mais de 50 respostas. Passados 45 dias recebera mais de $147.200 em notas de 5 d?lares! Fiquei chocado! Eu estava seguro que a coisa n?o funcionava. Agora uni-me ? Doris no seu passatempo. N?s devemos tudo ao sistema MLM". T. Franco. Bel Air, MD. "Apenas quero passar-lhe os meus melhores desejos e encorajamentos. Quaiquer d?vidas que tenha desaparecer?o quando as suas primeiras ordens chegarem. Verifiquei junto da ag?ncia postal norte-americana que o plano era legal. Definitivamente isto FUNCIONA!!!" PS: ISSO ? UM SERVI?O DE REVENDA DE SERVI?OS, NADA ? GR?TIS. PE?A O RELAT?TORIO VEJA , SEU CONT?UDO DE EDUCA??O E INSTRU??O PARA O MUNDO DOS N?GOCIOS!! INFORMA??ES: . SUCESSO!!!!! From rkern at ucsd.edu Wed Jun 1 16:06:13 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 01 Jun 2005 13:06:13 -0700 Subject: Generalized Linear Least Squares Problems In-Reply-To: References: <1117534369.263476.120510@o13g2000cwo.googlegroups.com> Message-ID: Colin J. Williams wrote: > Tim Leslie wrote: > >>On 31 May 2005 03:12:49 -0700, venkat wrote: >> >>>Hi, >>> >>>I want to solve linear least sqaure problem( min||c-Ax||2 subject to >>>Bx=d ). How do I do it in python. lapack has a routine for doing this >>>(DGGLSE). Can I access this from python? >> >>Check out scipy, in particular the linear algebra package. >> >>http://www.scipy.org/documentation/apidocs/scipy/scipy.linalg.html >> >>Cheers, >> >>Tim > > Or you could try numarray, available for use with Python 2.4 Neither of these solve the generalized least squares problem. However, it is easier to add to scipy.linalg. Look at the file scipy/Lib/linalg/generic_flapack.py and copy and modify the block for DGELSS to work for DGGLSE. Then modify the Python function scipy.linalg.lstsq to take the optional extra arguments and do the generalized problem. Finally, contribute your changes back to scipy and win the accolades you deserve. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From thomasbartkus at comcast.net Thu Jun 23 11:44:04 2005 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Thu, 23 Jun 2005 10:44:04 -0500 Subject: Database recommendations for Windows app References: <42b97240$0$24467$da0feed9@news.zen.co.uk> <8oioo2-0kn.ln1@lairds.us> <3tiue.27$jv6.1568@news.uswest.net> <4aGdnfbfEs1YIiffRVn-3Q@telcove.net> Message-ID: "Magnus Lycka" wrote in message news:d9eg04$tr8$1 at wake.carmen.se... > Thomas Bartkus wrote: > > "Magnus Lycka" wrote in message > > > The O.P. wanted a database for his > > > Python app, and Thomas Bartkus suggested Access. > > > > Not exactly! > > Sorty, I meant Jet or whatever the backend is called these days. Hey! Even MS is confused these days. > > If we start with vanilla Python, we need just the tiny PySqlite module > and DB-API compliant Python code to get a SQLite solution to work. One > small 3rd party module which is trivial to bundle. There is no way you > can access ADO with less 3rd party stuff bundled than that. The minimum > is to bundle win32all or ctypes, but then you need to work much harder. > You probably want a 3rd party python ADO library as well. Then it's > much more stuff to bundle. I was thinking of Win32com which I expect lets you put a wrapper around ADO and work the ADO (or any other ActiveX) object model from within Python. However I must confess that while I am quite familiar with ADO, I haven't used it with Python. I do know that the ADO (or DAO) libraries are complete, SQL oriented, database systems that are available on every WinXP desktop. I *think* "Jet" refers to the underlying, .mdb file based storage engine that ADO rides on top of by default. All WinXP platforms have this and do not need another db platform - IOW we don't need to distribute a db platform here! Unless one simply prefers something else ;-) Thomas Bartkus From osvaldo.santana at indt.org.br Thu Jun 9 19:30:54 2005 From: osvaldo.santana at indt.org.br (osvaldo.santana at indt.org.br) Date: Thu, 9 Jun 2005 18:30:54 -0500 Subject: ANN: Python for Maemo released! Message-ID: We are proudly to announce the first release of Python for Maemo platform. This is in *alpha* stage yet. Bug fixes, wishes, suggestions, etc, are encouraged and welcomed. Please, contact us by mail (ok, bugzilla coming soon). * Ruda Moura * Osvaldo Santana PyGTK, PyGame, PyNumeric and some packages missing for SDL are also included. Please, visit: http://www.indt.org.br/maemo/index.html#python for more information. No reptiles were harmed in the making of these crafts. From tjreedy at udel.edu Thu Jun 2 13:29:51 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Jun 2005 13:29:51 -0400 Subject: Beginner question: Logs? References: <1117682961.672287.7260@g44g2000cwa.googlegroups.com> <1117685058.142351.123660@g47g2000cwa.googlegroups.com> Message-ID: "Peter Hansen" wrote in message news:Q7mdnfJgTO82lgLfRVn-qA at powergate.ca... > Elliot Temple wrote: >> from math import * >> log10(15625) > > It's always a good idea, especially when answering a beginner's > question, to add the caution that this form ("from xxx import *") has > certain dangers** associated with it, and is widely considered poor > style, and should really only rarely be used. Which is why I often do things like >>> import math as m >>> m.log... From spam.csubich+block at block.subich.spam.com Wed Jun 8 17:53:05 2005 From: spam.csubich+block at block.subich.spam.com (Christopher Subich) Date: Wed, 08 Jun 2005 17:53:05 -0400 Subject: pack heterogeneous data types In-Reply-To: <1118267340.026766.188450@g14g2000cwa.googlegroups.com> References: <1118267340.026766.188450@g14g2000cwa.googlegroups.com> Message-ID: ashokbellur at gmail.com wrote: > Hello, > > How do i pack different data types into a struct or an array. Examples > would be helpful. > > Say i need to pack an unsigned char( 0xFF) and an long( 0xAAAAAAAA) > into a single array? The reason i need to do this is send a packet over > a network. Look at the struct module, struct.pack sounds like what you need. From rbt at athop1.ath.vt.edu Thu Jun 16 09:34:45 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 16 Jun 2005 09:34:45 -0400 Subject: Is Python Suitable for Large Find & Replace Operations? In-Reply-To: <42af1b28$0$10131$626a14ce@news.free.fr> References: <42af1b28$0$10131$626a14ce@news.free.fr> Message-ID: <1118928885.18452.17.camel@athop1.ath.vt.edu> On Tue, 2005-06-14 at 19:51 +0200, Gilles Lenfant wrote: > rbt a ?crit : > > Here's the scenario: > > > > You have many hundred gigabytes of data... possible even a terabyte or > > two. Within this data, you have private, sensitive information (US > > social security numbers) about your company's clients. Your company has > > generated its own unique ID numbers to replace the social security numbers. > > > > Now, management would like the IT guys to go thru the old data and > > replace as many SSNs with the new ID numbers as possible. You have a tab > > delimited txt file that maps the SSNs to the new ID numbers. There are > > 500,000 of these number pairs. What is the most efficient way to > > approach this? I have done small-scale find and replace programs before, > > but the scale of this is larger than what I'm accustomed to. > > > > Any suggestions on how to approach this are much appreciated. > > Are this huge amount of data to rearch/replace stored in an RDBMS or in > flat file(s) with markup (XML, CSV, ...) ? > > -- > Gilles The data is in files. Mostly Word documents and excel spreadsheets. The SSN map I have is a plain text file that has a format like this: ssn-xx-xxxx new-id-xxxx ssn-xx-xxxx new-id-xxxx etc. There are a bit more than 500K of these pairs. Thank you, rbt From dalke at dalkescientific.com Mon Jun 13 03:49:44 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 13 Jun 2005 07:49:44 GMT Subject: new string function suggestion References: <7fare.27429$J12.6708@newssvr14.news.prodigy.com> Message-ID: Andy wrote: > What do people think of this? > > 'prefixed string'.lchop('prefix') == 'ed string' > 'string with suffix'.rchop('suffix') == 'string with ' > 'prefix and suffix.chop('prefix', 'suffix') == ' and ' Your use case is > I get tired of writing stuff like: > > if path.startswith('html/'): > path = path[len('html/'):] > elif s.startswith('text/'): > path = path[len('text/'):] > > It just gets tedious, and there is duplication. Instead I could just write: > > try: > path = path.lchop('html/') > path = path.lchop('text/') > except SomeException: > pass But your posted code doesn't implement your use case. Consider if path == "html/text/something". Then the if/elif code sets path to "text/something" while the lchop code sets it to "something". One thing to consider is a function (or string method) which is designed around the 'or' function, like this. (Named 'lchop2' but it doesn't give the same interface as your code.) def lchop2(s, prefix): if s.startswith(prefix): return s[len(prefix):] return None path = lchop2(path, "html/") or lchop2(path, "text/") or path If I saw a function named "lchop" (or perhaps named "lchomp") I would expect it to be (named 'lchomp3' so I can distinguish between it and the other two) def lchop3(s, prefix): if s.startswith(prefix): return s[len(prefix):] return s and not raise an exception if the prefix/suffix doesn't match. Though in this case your use case is not made any simpler. Indeed it's uglier with either newpath = path.lchop3("html/") if newpath == path newpath = path.lchop3("text/") if newpath == path: ... or if path.startswith("html/"): path = path.lstrip("html/") elif path.startswith("text/"): path = path.lstrip("text/") ... I tried finding an example in the stdlib of code that would be improved with your proposal. Here's something that would not be improved, from mimify.py (it was the first grep hit I looked at) if prefix and line[:len(prefix)] == prefix: line = line[len(prefix):] pref = prefix else: pref = '' In your version it would be: if prefix: try: line = line.rstrip(prefix) except TheException: pref = '' else: pref = prefix else: pref = '' which is longer than the original. From pickle.py (grepping for 'endswith(' and a context of 2) pickle.py- if ashex.endswith('L'): pickle.py: ashex = ashex[2:-1] pickle.py- else: pickle.py: ashex = ashex[2:] this would be better with my '3' variant, as ashex = ashex.rchop3('L')[2:] while your version would have to be try: ashex = ashex.rchomp('L')[2:] except SomeException: ashex = ashex[2:] Even with my '2' version it's the simpler ashex = (ashex.rchop2('L') or ashex)[2:] The most common case will be for something like this tarfile.py- if self.name.endswith(".gz"): tarfile.py- self.name = self.name[:-3] My "3" code handles it best self.name = self.name.rstrip3(".gz") Because your code throws an exception for what isn't really an exceptional case it in essence needlessly requires try/except/else logic instead of the simpler if/elif logic. > Does anyone else find this to be a common need? Has this been suggested > before? To summarize: - I don't think it's needed that often - I don't think your implementation's behavior (using an exception) is what people would expect - I don't think it does what you expect Andrew dalke at dalkescientific.com From please_post at nomail.edu Fri Jun 17 17:52:53 2005 From: please_post at nomail.edu (bill) Date: Fri, 17 Jun 2005 21:52:53 +0000 (UTC) Subject: ISO authoritative Python ref References: Message-ID: In bill writes: >I have to learn Python in a hurry. My apologies. I found what I needed. I don't understand it how I missed it in my first round of searching. Thanks, bill From me at privacy.net Sun Jun 12 10:13:46 2005 From: me at privacy.net (Dan Sommers) Date: 12 Jun 2005 10:13:46 -0400 Subject: How to get/set class attributes in Python References: Message-ID: On Sun, 12 Jun 2005 15:35:46 +0200, Kalle Anke wrote: > In learning Python I've understood that I should write code in such a > way that it can handle different data and this is fine with me. But > what if I have a class where different attributes should only have > values of a certain type and everything else is an error. > For example, if I have an class that defines three attributes: first > and last name plus email address. The only valid data types for the > first two are strings and for the last an EmailAddress class. > How should I handle this in Python? > Should I use just don't care (but I'm going to send the data to a > database so I need to ensure that the data is OK)? Should I use > 'isinstance' and check manually? Or should I do something else? One key phrase here is "duck typing": if it walks like a duck, and swims like a duck, and quacks like a duck, then it's a duck, or at least you can assume it's a duck. For example: def put_something( file_open_for_writing, something ): file_open_for_writing.write( str( something ) ) I don't care if file_open_for_writing is "really a file," as long it has a "write" method that writes a string somewhere. The other key phrase is "we're all adults here": if I import sin from the math module and pass it a unicode string, I get what I deserve. In lower-level methods/functions, I usually just assume that parameters are correct, and let the higher-level code catch any exceptions that occur becuase it (the higher-level code) messed up and passed the wrong kind of parameter. For example, UI code *has* to check things that users type, but once that happens, there's no need for my program to recheck every parameter on every function call all the way down. Either everything works, or that same UI code catches and logs a TypeError or ValueError or KeyError exception and asks the user what to do next. Regards, Dan -- Dan Sommers From phil at riverbankcomputing.co.uk Thu Jun 9 15:19:49 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 9 Jun 2005 20:19:49 +0100 Subject: Questions on using Qt or wxWindows with Python and OS X In-Reply-To: References: Message-ID: <200506092019.49558.phil@riverbankcomputing.co.uk> On Thursday 09 June 2005 8:07 pm, Tim Jarman wrote: > Hi Kenneth! > > In article , > > Kenneth McDonald wrote: > > If this is not an appropriate newsgroup for this type of posting, > > please let me know and (if possible) suggest an alternative. I've > > done a fair bit of research on the net, but information is scattered > > all over the place and I haven't been able to find mailing lists > > relating specifically to python and UIs. > > AFAIK there isn't a specific newsgroup/mailing list for Python GUIs in > general, although perhaps there should be. This is as good a place to > ask as any, I'd guess. There is a mailing list for PyQt on OS X at... https://lists.sourceforge.net/lists/listinfo/pyqt-mac-list Phil From sjmachin at lexicon.net Mon Jun 13 20:26:18 2005 From: sjmachin at lexicon.net (John Machin) Date: Tue, 14 Jun 2005 10:26:18 +1000 Subject: \r\n or \n notepad editor end line ??? In-Reply-To: References: <1118237045.305238.276700@g49g2000cwa.googlegroups.com> <1118238280.678863.211490@g44g2000cwa.googlegroups.com> Message-ID: <42ae242a@news.eftel.com> Steven D'Aprano wrote: > On Mon, 13 Jun 2005 11:53:25 +0200, Fredrik Lundh wrote: > > >> wrote: >> >> >>>It means in windows we should use 'wb' to write and 'rb' to read ? >>>Am I right? >> >>no. >> >>you should use "wb" to write *binary* files, and "rb" to read *binary* >>files. >> >>if you're working with *text* files (that is, files that contain lines of text >>separated by line separators), you should use "w" and "r" instead, and >>treat a single "\n" as the line separator. > > > I get nervous when I read instructions like this. It sounds too much like > voodoo: "Do this, because it works, never mind how or under what > circumstances, just obey or the Things From The Dungeon Dimensions will > suck out your brain!!!" > > Sorry Fredrik :-) > Many people don't appear to want to know why; they only want a solution to what they perceive to be their current problem. > When you read a Windows text file using "r" mode, what happens to the \r > immediately before the newline? The thing to which you refer is not a "newline". It is an ASCII LF character. The CR and the LF together are the physical representation (in a Windows text file) of the logical "newline" concept. Internally, LF is used (irrespective of platform) to represent that concept. > Do you have to handle it yourself? No. > Or will > Python cleverly suppress it so you don't have to worry about it? Suppressed: no, it's a transformation from a physical line termination representation to a logical one. Cleverly: matter of opinion. By Python: In general, no -- the transformation is handled by the underlying C run-time library. > > And when you write a text file under Python using "w" mode, will the > people who come along afterwards to edit the file in Notepad curse your > name? If they do, it will not be because other than CRLF has been written as a line terminator. > Notepad expects \r\n EOL characters, and gets cranky if the \r is > missing. AFAIR, it performs well enough for a text editor presented with a file consisting of one long unterminated line with occasional embedded meaningless-to-the-editor control characters. You can scroll it, edit it, write it out again ... any crankiness is likely to be between the keyboard and the chair :-) > > How does this behaviour differ from "universal newlines"? > Ordinary behaviour in text mode: Win: \r\n -> newline -> \r\n Mac OS X < 10: \r -> newline -> \r other box: \n -> newline -> \n Note : TFM does appear a little light on in this area. I suppose not all users of Python have aquired this knowledge by osmosis through decades of usage of C on multiple platforms :-) "Universal newlines": On *any* box: \r\n or \n or \r (even a mixture) -> \n on reading On writing, behaviour is "ordinary" i.e. the line terminator is what is expected by the current platform "Universal newlines" (if used) solves problems like where an other-boxer FTPs a Windows text file in binary mode and then posts laments about all those ^M things on the vi screen and :1,$s/^M//g doesn't work :-) HTH, John From lkirsh at cs.ubc.ca Mon Jun 6 23:45:28 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Mon, 06 Jun 2005 20:45:28 -0700 Subject: reloading my own modules Message-ID: I have a driver module as well as several other modules. I am running the driver interactively from emacs - that is, I don't restart python on each run. I want to work it such that every time a modify the source for one of the non-driver modules and re-run the driver, the other modules will be reloaded. I have the following at the top of my driver module: import dbtest, util for module in ['dbtest', 'util']: if module in sys.modules.keys(): reload(sys.modules[module]) Is this the best way to do it? It seems a bit verbose, but not really all that bad. I was just wondering if there is a more standard way to do it? Lowell From mirnazim at gmail.com Mon Jun 27 03:19:01 2005 From: mirnazim at gmail.com (Mir Nazim) Date: 27 Jun 2005 00:19:01 -0700 Subject: what is your opinion of zope? In-Reply-To: References: Message-ID: <1119856741.354862.282180@g44g2000cwa.googlegroups.com> http://www.zope.org/Wikis/ZODB/FrontPage/guide/index.html This should solve this problem. --- Mir Nazim www.planetnazim.com From jhe13586 at bigpond.net.au Thu Jun 2 10:06:58 2005 From: jhe13586 at bigpond.net.au (Joal Heagney) Date: Thu, 02 Jun 2005 14:06:58 GMT Subject: Two questions In-Reply-To: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> References: <1117719918.564327.160210@g49g2000cwa.googlegroups.com> Message-ID: <6oEne.847$F7.474@news-server.bigpond.net.au> qscomputing at gmail.com wrote: > Hi, > > I've developed in several other languages and have recently found > Python and I'm trying to use it in the shape of the PythonCard > application development tool. > > My two questions: > > 1. What is the easiest way to create a for loop in the style I'm used > to from Delphi ie: > for I:=0 to 2 do begin > //code > end; Um, assuming that this loops through the numbers 0 to 2 and assigns them to the variable I, and then does something in code with I after it's been assigned, the python equivalent is: for I in range(0,3): //code (Note the whitespace after opening the for loop?) And then break the indenting to finish the for loop. So you're next piece of code (Whatever you had after end;) would go here: //morecode. > 2. Philospohy(sp?) aside, I could potentially want to create a > binary-only distribution of my finished apps. I noticed the > documentation on .pyc files: how do I create these and, aside from > being basically read-only, are they used just like ordinary .py source > files? And can they be easily reverse-engineered? As long as you have write access to the directory that you're .py files are in, when you run python, it will generate the .pyc files for you as they are loaded. There is also a utility script in the main distribution called py_compile.py. E.g. compiling a whole directory of .py files: python /path/to/main/install/py_compile.py *.py And to compile them as optimised binary files (.pyo): python -O /path/to/main/install/py_compile.py *.py They are used like ordinary .py source files. (Python actually executes from the .pyc files it builds from your .py files.) They can be reverse-engineered, but then so can Java/C++/Assembler. Have a look through the group for something about being able to distribute your modules.pyc as a zipfile - I remember something about being able to do a -tiny- bit of extra protection by having them as a passworded zip file. > Thanks, > - QS Computing. > Welcome. Joal From noreply at gcgroup.net Sun Jun 12 11:52:48 2005 From: noreply at gcgroup.net (William Gill) Date: Sun, 12 Jun 2005 15:52:48 GMT Subject: Capture close window button in Tkinter Message-ID: I am trying to make a simple data editor in Tkinter where each data element has a corresponding Entry widget. I have tried to use the FocusIn/FocusOut events to set a 'hasChanged' flag (if a record has not changed, the db doesn?t need updating). This seems to work fine except that when the user finishes and clicks a ?done? button or the close window button (in the root widget) no FocusOut event is triggered. I can trigger a FocusOut event if the ?done? button opens another window (i.e. a messagebox) that takes focus. Enter and Leave follow the mouse, but don?t trigger when the user tabs between fields. Is there a better way to monitor 'hasChanged'? Also, how do I capture the root window close button? Thanks, Bill From bpeng at rice.edu Sat Jun 18 22:15:48 2005 From: bpeng at rice.edu (Bo Peng) Date: Sat, 18 Jun 2005 21:15:48 -0500 Subject: Is there something similar to ?: operator (C/C++) in Python? In-Reply-To: References: Message-ID: >>In Python, I am using temporary variables like >> >>if cond1: >> para1 = a >>else: >> para1 = b >> >># .... >># a bunch of such if/else >> >>func(para1, para2,...) > > > Yeah, that's how I would do it. How many of these things do you have? I have around 10 of them. Using these if/else, it will take 50 lines for a function call. It also bothers me to have 10 variables left in the namespace, in addition to finding 10 meaningful names. The FAQ provides two solutions, neither of them are elegant. I guess I will use if/else for reasability purpose. Thanks. Bo From mwm at mired.org Thu Jun 23 15:21:11 2005 From: mwm at mired.org (Mike Meyer) Date: Thu, 23 Jun 2005 15:21:11 -0400 Subject: Loop until condition is true References: <86u0jpytg7.fsf@guru.mired.org> Message-ID: <86ll50zxp4.fsf@guru.mired.org> Michael Hoffman writes: > Mike Meyer wrote: > >> Making None a constant broke existing code (and I just saw old code >> that assigned to None). Are True and False that much more common as >> variable names than None? > > Yes. In fact, I count at least 4 different modules in the Python 2.4 > standard library that assign to True or False, mainly as a > compatibility measure for the days before they were built-ins. If you > try assigning None, CPython will refuse to compile the module, even if > the code where None is assigned is unreachable. > > If there was ever a good reason to assign to None, I don't know it. For the record, the code I just saw did something like this: (var1, var2, None, None) = make_tuple(args) Pretty clearly, they were just throwing away some unused values. Who knows what it did to None... http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From philippe at philippecmartin.com Thu Jun 9 12:02:05 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Thu, 09 Jun 2005 16:02:05 GMT Subject: Generating HTML from python References: <1118327601.205586.289990@f14g2000cwb.googlegroups.com> Message-ID: <1KZpe.2163$751.1088@newssvr30.news.prodigy.com> I'll take a pick thanks - I like the fact it's buit-in (no extra installation) Michele Simionato wrote: > You could generate your report in reStructuredText > format (Google is your friend) and then convert > them in HTML, PS, PDF, etc. > > Michele Simionato From me at privacy.net Wed Jun 22 20:38:53 2005 From: me at privacy.net (Dan Sommers) Date: Wed, 22 Jun 2005 20:38:53 -0400 Subject: Avoiding deadlocks in concurrent programming References: <1119471329.315732.310810@g49g2000cwa.googlegroups.com> <7xhdfqgmsz.fsf@ruckus.brouhaha.com> <1119474582.891149.32740@g14g2000cwa.googlegroups.com> Message-ID: On 22 Jun 2005 14:09:42 -0700, "Eloff" wrote: [Paul Rubin] >> You're doing what every serious database implementation needs to do ... >> Are you sure you don't want to just use an RDBMS? > It was considered, but we decided that abstracting the data into > tables to be manipulated with SQL queries is substantially more > complex for the programmer and way too expensive to the system since > the average action would require 20-100 queries. Obviously, I only know what you've told us about your data, but 20-100 queries? That doesn't sound right. I know that I have often thought that my data and its structure were complex, but then ended up with a fairly straightforward table structure and pretty small queries. With the right set of tables and a strategically placed view or two, IMO you shouldn't need that many queries. As Paul noted, RDBMSes are well- studied and well-understood; they are also extremely powerful when used to their potential. Regards, Dan -- Dan Sommers From cyril.bazin at gmail.com Tue Jun 21 07:39:44 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Tue, 21 Jun 2005 13:39:44 +0200 Subject: Loop until condition is true In-Reply-To: References: Message-ID: Another question could be: why is there not a statement "whileTrue" or "loop"? For exemple: whileTrue: statement 1 if condition: break statement 2 It could be an economy of one unuseful test by loop. On 6/21/05, Magnus Lycka wrote: > > Remi Villatel wrote: > > while True: > > some(code) > > if final_condition is True: > > break > > # > > # > > > > What I don't find so "nice" is to have to build an infinite loop only to > > break it. > > This is a common Python idiom. I think you will get used to it. > > > > Is there a better recipe? > > final_condition = False > while not final_condition: > some(code) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From emami at knmi.nl Mon Jun 20 08:38:26 2005 From: emami at knmi.nl (Nader Emami) Date: Mon, 20 Jun 2005 14:38:26 +0200 Subject: binary file In-Reply-To: <42b6af4f$1_3@newspeer2.tds.net> References: <42b6af4f$1_3@newspeer2.tds.net> Message-ID: <556d8$42b6b8c2$9117fe9b$19867@news2.tudelft.nl> Kent Johnson wrote: > Nader Emami wrote: > >> L.S., >> >> I have used the profile module to measure some thing as the next command: >> >> profile.run('command', 'file') >> >> But this make a binary file! How can I write the result of 'profile' >> in a ascii file? Others how can I read (or convert) the binary file to >> am ascii file? > > > Use an instance of pstats.Stats to interpret the results: > > from pstats import Stats > s = Stats('file') > s.print_stats() > > etc. > http://docs.python.org/lib/profile-stats.html > > Kent I got the same result as the execution of command. But I would like to write to the an external 'ascii' file! Thanks! From Scott.Daniels at Acm.Org Tue Jun 14 15:01:31 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 14 Jun 2005 12:01:31 -0700 Subject: extending Python base class in C In-Reply-To: References: Message-ID: <42af225e$1@nntp0.pdx.net> harold fellermann wrote: > ... > This gives me a pointer to the class I want to use as base class. > Does anyone know how to assign this to the extension class? I tried > to build a tuple (BaseClass,) and assign it (after the respective > PyType_Ready call) ... I think this is your problem -- call PyType_Ready _after_ setting up the base class, not before. --Scott David Daniels Scott.Daniels at Acm.Org From agriff at tin.it Thu Jun 16 05:36:30 2005 From: agriff at tin.it (agriff at tin.it) Date: 16 Jun 2005 02:36:30 -0700 Subject: What is different with Python ? In-Reply-To: References: <3h14quFeqbr8U1@individual.net> <3UJqe.3696$%j7.3186@newssvr11.news.prodigy.com> <1o7sa1lhktsm65ok599ivevak3tua0op2g@4ax.com> Message-ID: <1118914590.744021.53950@z14g2000cwz.googlegroups.com> Andrea Griffini wrote: > That strings in python are immutable it's surely > just a detail, and it's implementation specific, > but this doesn't means it's not something you can > ignore for a while. If you use python this is a > *fundamental* property. My communication ability is dropping every day at an incredible rate (it's getting so bad I've been seriously in doubt about physiological problems). In the above phrase there is a "not" in excess; I meant to write ... but this doesn't means it's something you can ignore for a while. If you use python this ... May indeed be I'm just *realizing* how low are my communication skills... Andrea From tundra at tundraware.com Thu Jun 23 17:57:51 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jun 2005 17:57:51 EDT Subject: OT: Re: Looking For Geodetic Python Software In-Reply-To: References: <447po2-iqt.ln1@eskimo.tundraware.com> <3hvrhjFj3qfmU1@uni-berlin.de> Message-ID: Rocco Moretti wrote: > Tim Daneliuk wrote: > >> Diez B. Roggisch wrote: >> >>> Tim Daneliuk wrote: >>> >>>> Casey Hawthorne wrote: >>>> >>>>> >>>>> Do your planes fly over the earth's surface or through the ground? >>>> >>>> >>>> >>>> >>>> >>>> Why do you presume this has anything to do with airplanes? >>>> >>> >>> That was supposed to be a funny remark regarding that your >>> "straight-line-distance" makes no sense at all - because that would >>> mean that you'd have to go underground. So it has no >>> real-world-application - unless you actually have underground-planes ;) >>> >>> Diez >> >> >> >> Huh? When traversing along the surface of the earth, it's curvature >> is relevant in computing total distance. An airplane flies more-or-less >> in a straight line above that curvature. For sufficiently long airplane >> routes (where the ascent/descent distance is trivial compared to the >> overall horizontal distance traversed), a straight line path shorter >> than the over-earth path is possible. That's why I specified the >> desire to compute both path lengths. Where's the humor? > > > If you re-read what you wrote you'll see the phrase "straight line > flying distance.": > > > 1) Given the latitude/longitude of two locations, compute the distance > > between them. "Distance" in this case would be either the > > straight-line > > flying distance, or the actual over-ground distance that accounts > > for the earth's curvature. > > Casey was pointing out that, due to the convex curvature of the Earth, a > "straight line" between, say, Hong Kong and New York would happen to > pass several miles below the surface of California. For an extreme > example, a Euclidean straight line from the North pole to the south pole > would pass through the center of the earth. Note that you've attached > "Flying distance" to the phrase "Straight line" - Hollywood not > withstanding, there isn't a machine able to "fly" through the center of > the earth. The fact that it might be an unintentional error only adds to > the humor. (c.f Freudian Slips) Yikes! And I thought I was being clear. Sigh ... back to English 101 for moi. > > Given the relative thinness of the atmosphere (~10-20 km) in comparison > with the radius of the earth (~6,400 km), any plane flight of a > considerable distance will be curved in the Euclidean sense, no matter > how they changed their altitude inbetween. OK, now *I* get the joke too ;) Sorry for being obtuse ... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From tziade at nuxeo.com Fri Jun 10 11:46:35 2005 From: tziade at nuxeo.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Fri, 10 Jun 2005 17:46:35 +0200 Subject: IMAP Proxy In-Reply-To: <17065.43504.775271.117915@montanaro.dyndns.org> References: <42A99B1C.7020507@nuxeo.com> <17065.43504.775271.117915@montanaro.dyndns.org> Message-ID: <42A9B5DB.1090409@nuxeo.com> Skip Montanaro wrote: > Tarek> I want to write a small TCP Server in Python to make an IMAP > Tarek> Proxy for post-processing client requests. > > Tarek> It is not long either complicated but needs to be very robust > Tarek> so... maybe someone here has already done such a thing I can use > Tarek> or know where i can get it ? > >There is an IMAP filter as part of the SpamBayes project that you might find >is a useful starting point: > > http://www.spambayes.org/ > > Thanks for pointing it out but what I am looking for is more likely to be a TCP server that is placed on server side as a frontal for the IMAP server to deal with all incoming queries before it is passed to the real IMAP server. The use case is to redirect some search queries to a home made program. Tarek >Skip > > From harold.fellermann at upf.edu Tue Jun 14 12:58:54 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 14 Jun 2005 18:58:54 +0200 Subject: Problem with simple C extension Message-ID: <3dc77a7e7317fe820d6452813bc3809f@upf.edu> Am I stupid or what? I want to implement a very simple extension class in C (as I did it many times before...) The python equivalent of my class whould look like: class physics_DPD : def __init__(self,cutoff,friction,noise,dt) : self.cutoff = cutoff self.friction = friction self.noise = noise self.dt = dt That's all fir the start. Simple, heh? My C implementation is the following: #include #include "structmember.h" // PhysicsDPD instance structure typedef struct { PyObject_HEAD double cutoff; double friction; double noise; double dt; } hyper_PhysicsDPD; //---------------------------------------------------------------------- // tp_init //---------------------------------------------------------------------- static int hyper_PhysicsDPD_init(hyper_PhysicsDPD *self, PyObject *args, PyObject *kwds) { if (!PyArg_ParseTuple(args,"ffff", &self->cutoff, &self->friction, &self->noise, &self->dt )) return -1; printf("%f %f %f %f\n",self->cutoff,self->friction,self->noise,self->dt); return 1; } //---------------------------------------------------------------------- // method table //---------------------------------------------------------------------- static PyMethodDef hyper_PhysicsDPD_methods[] = { {NULL} /* Sentinel */ }; //---------------------------------------------------------------------- // instance members //---------------------------------------------------------------------- static PyMemberDef hyper_PhysicsDPD_members[] = { {"cutoff", T_DOUBLE, offsetof(hyper_PhysicsDPD,cutoff), 0, "cutoff radius"}, {"friction", T_DOUBLE, offsetof(hyper_PhysicsDPD,friction), 0, "friction"}, {"noise", T_DOUBLE, offsetof(hyper_PhysicsDPD,noise), 0, "noise"}, {"dt", T_DOUBLE, offsetof(hyper_PhysicsDPD,dt), 0, "time step"}, {NULL} /* Sentinel */ }; //---------------------------------------------------------------------- // type structure //---------------------------------------------------------------------- static PyTypeObject hyper_PhysicsDPDType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ "simulation.hyper.physics_DPD", /* tp_name */ sizeof(hyper_PhysicsDPD), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE , /* tp_flags */ "DPD physics", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ hyper_PhysicsDPD_methods, /* tp_methods */ hyper_PhysicsDPD_members, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)hyper_PhysicsDPD_init, /* tp_init */ 0, /* tp_alloc */ 0, /* tp_new */ 0, /* freefunc tp_free */ 0, /* inquiry tp_is_gc */ 0, /* PyObject *tp_bases */ 0, /* PyObject *tp_mro */ 0, /* PyObject *tp_cache */ 0, /* PyObject *tp_subclasses */ 0, /* PyObject *tp_weaklist */ 0, /* destructor tp_del */ }; //---------------------------------------------------------------------- // module hyper //---------------------------------------------------------------------- static PyMethodDef hyper_methods[] = { {NULL} /* Sentinel */ }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC inithyper(void) { PyObject* m; m = Py_InitModule3("hyper", hyper_methods, "Faster C implementation of the underlying physics."); hyper_PhysicsDPDType.tp_new = PyType_GenericNew; if (PyType_Ready(&hyper_PhysicsDPDType) < 0) return; Py_INCREF(&hyper_PhysicsDPDType); PyModule_AddObject(m, "physics_DPD", (PyObject *)&hyper_PhysicsDPDType); } Now, compilation and import works without problem. But I cannot assign members in the init-call. >>> import simulation.hyper.physics_DPD as Physics >>> p = Physics(1,2,3,4) 0.000000 0.000000 0.000000 0.000000 >>> p.friction 5.3049894774131808e-315 I must be blind today. Can anyone see what I am doing wrong in init??? Thanks a lot! - harold - -- A country without army is like a fish without bicycle. -- From benji at benjiyork.com Wed Jun 29 17:44:14 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 29 Jun 2005 17:44:14 -0400 Subject: Inheriting from object In-Reply-To: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> References: <1120071332.937868.86400@g43g2000cwa.googlegroups.com> Message-ID: <42C3162E.1060803@benjiyork.com> Fuzzyman wrote: > Also, can anyone explain any tangible benefit of inheriting from > object, when not explicitly using any features of new style classes ? One reason is that properties won't work correctly. -- Benji York From philippe at philippecmartin.com Fri Jun 24 17:20:25 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Fri, 24 Jun 2005 21:20:25 GMT Subject: Running Python interpreter in Emacs References: <1119566062.814042.177620@g44g2000cwa.googlegroups.com> <1119576654.090762.106010@z14g2000cwz.googlegroups.com> <1119645739.213660.103840@o13g2000cwo.googlegroups.com> Message-ID: I do not think there is any need to tell emacs where Python is; besides having python.exe in your Windows $PATH. Regards, Philippe Rex Eastbourne wrote: > I have the following in my .emacs: > > (add-to-list 'load-path "C:\Program Files\Python24") > > Is that enough? I didn't see anything similar to that in your .emacs > file, so I'm wondering if I'm supposed to add the path to my PATH > elsewhere. > > Thanks, > > Rex From rrr at ronadam.com Tue Jun 28 20:28:27 2005 From: rrr at ronadam.com (Ron Adam) Date: Wed, 29 Jun 2005 00:28:27 GMT Subject: Boss wants me to program In-Reply-To: <1119988656.668457.202660@g43g2000cwa.googlegroups.com> References: <1119898281.201400.85040@o13g2000cwo.googlegroups.com> <1119988656.668457.202660@g43g2000cwa.googlegroups.com> Message-ID: xeys_00 at yahoo.com wrote: > Ok, sorry to throw perhaps unrelated stuff in here, but I want everyone > to know what we have right now in the office. We started with an > electric typewriter and file cabinets. We were given an old 386 with a > 20 mb hard drive about 5 years ago, and we moved everything over to a > very very old version of msworks on msdos 6. Depending on what we are > given(for reasons best left alone, I won't explain why we can't > actually COUNT on the actual buying of a new system), we will be left > with this relic, or be given a 486. Maybe a old pentium 90 or so. I may > try to convince the boss that I can write dos programs for the existing > machine. If we get any kind of upgrade, I'm sure it will be able to run > linux with X and a low overhead window manager. If that happened, I'd > be able to use python and this "tk" thing you have talked about and > make something that will work for him, am I correct? The other > alternative is to install console mode linux on it and hope that the > ncurses library can be used by python. The system could be as low as a > 486 dx2 66 with maybe 16 megs of ram. Well, I just thought I'd give you > people more info on the situation. > > Xeys Check the yellow pages in your area (or closest large city if you're not in one), for used computer stores. Or just start calling all the computer stores in your area and ask them if they have any used computers for sale. I was able to get a Dell Pentium 3 for $45 dollars last year for a second computer to put Linux on. I just asked him if he had any old computers for really cheep that booted, and that's what he found in the back. I just needed to add ram and a hard drive. You might be surprised what you can get used if you ask around. Cheers, Ron From fredrik at pythonware.com Tue Jun 21 10:00:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Jun 2005 16:00:36 +0200 Subject: Loop until condition is true References: Message-ID: Remi Villatel wrote: > There is always a "nice" way to do things in Python but this time I can't > find one. > > What I'm trying to achieve is a conditionnal loop of which the condition > test would be done at the end so the loop is executed at least once. It's > some way the opposite of "while". > > So far, all I got is: > > while True: > some(code) > if final_condition is True: > break > # > # > > What I don't find so "nice" is to have to build an infinite loop only to > break it. checking if a logical expression is true by comparing it to True is bad style, and comparing values using "is" is also bad style. the correct way to write that if-statement is: if final_condition: break and yes, the "infinite" while loop is a standard Python pattern. get used to it. From deets at web.de Thu Jun 9 08:23:37 2005 From: deets at web.de (Diez B. Roggisch) Date: Thu, 09 Jun 2005 14:23:37 +0200 Subject: pack heterogeneous data types In-Reply-To: <1118267340.026766.188450@g14g2000cwa.googlegroups.com> References: <1118267340.026766.188450@g14g2000cwa.googlegroups.com> Message-ID: ashokbellur at gmail.com wrote: > Hello, > > How do i pack different data types into a struct or an array. Examples > would be helpful. > > Say i need to pack an unsigned char( 0xFF) and an long( 0xAAAAAAAA) > into a single array? The reason i need to do this is send a packet over > a network. You've been reposting this on a frequent base all the time for 2 weeks now - and everytime you've been told (by me and others) to use the module struct. So - how about actually trying so and come back if you hit the wall with that for whatever reason instead of unsuccsessfully shoehorning arrays int something you think they're supposed to be? Which, BTW, they aren't in _any_ language, as the are homogenous by nature and only pointer-tricks in C can get you around that. Diez From steve at REMOVETHIScyber.com.au Thu Jun 23 06:32:46 2005 From: steve at REMOVETHIScyber.com.au (Steven D'Aprano) Date: Thu, 23 Jun 2005 20:32:46 +1000 Subject: Does a function like isset() exist in Python? References: Message-ID: On Wed, 22 Jun 2005 23:09:57 -0400, Patrick Fitzsimmons wrote: > Hi, > > I'm sure I should know this, but I can't find it in the manual. > > Is there a function in Python like the function in PHP isset()? It > should take a variable name and return True or False depending on > whether the variable is initialized. What would you use such a function for? The closest thing I can think of is testing whether a particular object exists. Eg to test whether your program is running under a version of Python that defines bools, and if not, define your own objects which act in a similar way, you would say try: False except NameError: False = 0 True = not False Note that there is no need to do something with the name "False" in the try clause -- just use it. -- Steven. From robin at alldunn.com Sat Jun 4 19:46:33 2005 From: robin at alldunn.com (Robin Dunn) Date: Sat, 04 Jun 2005 16:46:33 -0700 Subject: ANN: wxPython 2.6.1.0 Message-ID: <42A23D59.9010007@alldunn.com> Announcing ---------- The 2.6.1.0 release of wxPython is now available for download at http://wxpython.org/download.php. Anybody keeping track will probably notice that the prior release (2.6.0.1) was released just about a week ago. This short turn-around time is because I was slow getting the last release done, and the wxWidgets team was uncharacteristically early with the 2.6.1 release! This release consists of a few bug fixes made since 2.6.0.1. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK or GTK2, and Mac OS X. Changes in 2.6.1.0 ------------------ wx.ListCtrl: patch #1210352, fixes editing in generic wx.ListCtrl with wx.LC_EDIT_LABELS. Applied patch #208286, MediaCtrl DirectShow rewrite. DocView patches from Morgan Hua: bug fixes, and additional SVN commands, also added a default template that uses the text editor for any unknown file type. wxMSW: Use the system IDC_HAND cursor for wx.CURSOR_HAND and only fallback to the strange wxWidgets version if the system one is not available. wx.grid.Grid: Merge the cell size attribute the same way that other attributes are merged, e.g., if it is already set to a non-default value in the current GridCellAttr object then don't merge from the other. wx.lib.evtmgr: Fixed to use wx._core._wxPyDeadObject wx.lib.gridmovers: Don't scroll when the mouse is dragged outside of the grid, unless the mouse is kept in motion. wxMSW: Applied patch #1213290 incorrect logic in wx.TopLevelWindow.ShowFullScreen. Applied patch #1213066 correct device names for Joystick in Linux. wxGTK: Applied patch #1207162 wx.TextCtrl.SetStyle fix for overlapping calls. wx.FileConfig: fixed DeleteEntry to set the dirty flag properly so the change will get written at the next flush. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From SILENS at polaroid.com Wed Jun 8 11:39:50 2005 From: SILENS at polaroid.com (Silen, Stephen A) Date: Wed, 8 Jun 2005 11:39:50 -0400 Subject: py2exe -> error in PYTHON23.DLL Message-ID: Stephen A. Silen Polaroid Corporation 1265 Main Street - Bldg. W3-3 Waltham, Massachusetts 02451 U.S.A. tel: 781-386-8410 fax: 781-833-8410 -- This transmission is intended only for use by the addressee(s) named herein and may contain information that is proprietary, confidential and/or legally privileged. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.golden at viacom-outdoor.co.uk Wed Jun 29 05:43:02 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 29 Jun 2005 10:43:02 +0100 Subject: COM problem .py versus .exe Message-ID: <9A28C052FF32734DACB0A288A3533991EBB945@vogbs009.gb.vo.local> [Thomas Heller] | | "Tim Golden" writes: | | > [Greg Miller] | > | Hello again, I put the executable on the "virgin" PC today. | > | I am using | > | the wmi(b) that you gave me. The error that I am | receiving now is: | > | | > | File "autoStart.pyc", line 241, in test | > | File "wmib.pyc", line 157, in ? | > | File "win32com\client\__init__.pyc", line 73, in GetObject | > | File "win32com\client\__init__.pyc", line 88, in Moniker | > | com_error: (-2147221020, 'Invalid syntax', None, None) | > | | > | any thoughts on this error? Thanks again for the help. | > | > Well that's a real pain! | | Doesn't this look like the WMI service (or how it's called) is not | installed? | | Thomas I don't think that's it; (a) because I've seen this issue before on my own machine, although I don't remember what the cause was! and (b) because unless the OP's on Win9x/NT I think it very unlikely that WMI isn't up-and-running. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From kveretennicov at gmail.com Thu Jun 23 05:56:08 2005 From: kveretennicov at gmail.com (Konstantin Veretennicov) Date: Thu, 23 Jun 2005 12:56:08 +0300 Subject: PEP ? os.listdir enhancement In-Reply-To: References: Message-ID: <4660fe30050623025644b024b1@mail.gmail.com> On 6/22/05, Riccardo Galli wrote: > I propose to add an 'abs' keyword which would make os.listdir return the > absolute path of files instead of a relative path. What about os.listdir(dir='relative/path', abs=True)? Should listdir call abspath on results? Should we add another keyword rel? Would it complicate listdir unnecessarily? - kv From cam.ac.uk at mh391.invalid Sun Jun 19 04:42:45 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 19 Jun 2005 09:42:45 +0100 Subject: Why is there no instancemethod builtin? In-Reply-To: <11b89s8rr096kaf@news.supernews.com> References: <11b89s8rr096kaf@news.supernews.com> Message-ID: John Roth wrote: > you need _both_ isinstance and the types module to do a correct > check for any string type: isinstance(fubar, types.StringTypes). > That's because both string and unicode are subtypes of one base. But basestring, their base class is a built-in. -- Michael Hoffman From srinivasanr at gmail.com Tue Jun 7 13:12:14 2005 From: srinivasanr at gmail.com (srinivasanr at gmail.com) Date: 7 Jun 2005 10:12:14 -0700 Subject: xmlrpclib - methodHelp doesn't work Message-ID: <1118164334.528966.125920@g47g2000cwa.googlegroups.com> I tried out the examples in this website for XML-RPC using python - http://www.onlamp.com/pub/a/python/2000/11/22/xmlrpcclient.html?page=2 But I get the following errors when I try to execute the code. Here is the snippet of the code with the error messages. >>> meerkatsvr.system.methodSignature(meerkat.getChannels) Traceback (most recent call last): File "", line 1, in ? NameError: name 'meerkat' is not defined >>> meerkatsvr.system.methodHelp(meerkat.getItems) Traceback (most recent call last): File "", line 1, in ? NameError: name 'meerkat' is not defined can someone tell me what is wrong. Also is there any good online resource for XML-RPC with Python. From reder at jpl.nasa.gov Wed Jun 15 21:00:43 2005 From: reder at jpl.nasa.gov (Leonard J. Reder) Date: Wed, 15 Jun 2005 18:00:43 -0700 Subject: Multithreaded Python FSM (Harel State Machines) In-Reply-To: References: Message-ID: Hello, I am sending this out again in hopes that someone will have some meaningful comments on FSM (finite state machine) modules avaliable for Python. Hope to get a reply or two this time. Thanks. Leonard J. Reder wrote: I have been searching on the web for a specific Python implementation of a FSM. More specifically looking for a Harel State Machine implementation. The Harel State Machine allows multi-threaded capable state machines with hierarchical representation capability (nested instances of state machines). They also have a unique conditional trigger symbol scheme for event representation and state machine transitions. Usually the multiple threads communicate over some sort of queue. I have seen some implementations of simple FSMs and some interesting descriptions of how the generator/yeild Python keywords can be used. I think Python has all the pieces to make a Heral implementation. Does anyone know of a Python implementation of FSM that comes close to this functionality? Any comments or recommendation for FSM packages that I could add this functionality to would be welcome. I certainly think someone has done this approach already. All replies are very much appreciated. Thanks for reading this and please reply. Regards, Len -- ____________________________________________________ Leonard J. Reder Jet Propulsion Laboratory Interferometry Systems and Technology Section 383 Email: reder at huey.jpl.nasa.gov Phone (Voice): 818-354-3639 Phone (FAX): 818-354-4357 Mail Address: Mail Stop: 171-113 4800 Oak Grove Dr. Pasadena, CA. 91109 --------------------------------------------------- From mwarden at gmail.com Wed Jun 8 15:04:44 2005 From: mwarden at gmail.com (Matt Warden) Date: Wed, 8 Jun 2005 15:04:44 -0400 Subject: Annoying behaviour of the != operator In-Reply-To: <1118256283.485202.19780@o13g2000cwo.googlegroups.com> References: <1118250172.559202.209150@g47g2000cwa.googlegroups.com> <1118256283.485202.19780@o13g2000cwo.googlegroups.com> Message-ID: Jordan, On 8 Jun 2005 11:44:43 -0700, Jordan Rastrick wrote: > But I explicitly provided a method to test equality. And look at the > plain english meaning of the term "Not equals" I think its pretty > reasonable Indeed. Furthermore, it seems quite silly that these would be different: a != b not (a == b) To be fair, though, other languages have peculiarities with equation. Consider this Java code: String s1 = "a"; String s2 = "a"; String s3 = new String("a"); String s4 = new String("a"); s1 == s2; // true s1.equals(s2); // true s1 == s3; // false s1.equals(s3); // true s3 == s4; // false s3.equals(s4); // true Doesn't make it any less silly, though. -- Matt Warden Miami University Oxford, OH, USA http://mattwarden.com This email proudly and graciously contributes to entropy. From kbilsted at hotmail.com Sun Jun 12 19:36:22 2005 From: kbilsted at hotmail.com (newseater) Date: 12 Jun 2005 16:36:22 -0700 Subject: changing how instances are "created" In-Reply-To: References: <1118617483.215438.318980@o13g2000cwo.googlegroups.com> Message-ID: <1118619382.878977.185960@g44g2000cwa.googlegroups.com> Robert Kern wrote: > newseater wrote: > > Hello. I need to be able to control how objects are created. Sometimes > > when creating an object, i want to reuse another object instead. I've > > searched for factory method implementations and singleton > > implementations. They were too much of a hack! > > > > My first attempt of doing this was to play around with the __new__() > > method. But i didn't quite succed. Then i came up with making a static > > method which can create my instances or re-use other instances. > > However, the below code I cannot get to work :( > > > > class Creator > > def createInstance(cls, *args, **kwargs): > > anewinstance = cls.__new__(cls, *args, **kwargs) > > anewinstance.__init__(*args, **kwargs) > > > > return anewinstance > > createInstance = staticmethod(createInstance) > > You want a classmethod, not a staticmethod. why do i want that? how should the code look like? currently the objects fail to get initialized etc... From __peter__ at web.de Thu Jun 2 05:25:09 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 02 Jun 2005 11:25:09 +0200 Subject: How to restrict lenght of entry widget to certain number of character References: <1117396149.334908.238580@g14g2000cwa.googlegroups.com> <1117700375.764690.305820@g44g2000cwa.googlegroups.com> Message-ID: Michael Onfrek wrote: > import Tkinter as tk > > Hi! Can you explain what line above mean? > > I also found : http://effbot.org/zone/tkinter-entry-validate.htm > > It works for me, but I not really understand how? :) >> import Tkinter as tk Make objects defined in Tkinter available under the tk prefix. E. g. to access an Entry you can do 'tk.Entry'. Had you imported it 'import Tkinter' you would have to do 'Tkinter.Entry' instead. So you are saving a few keystrokes. Doing 'from Tkinter import *' saves you still more keystrokes but is considered bad style except for demonstration purposes. >> var = tk.StringVar() >> entry = tk.Entry(root, textvariable=var) Create a StringVar and connect it to the Entry widget. Any changes the user makes in the Entry are reflected in the StringVar's value which can be accessed with its get() method. >> max_len = 5 >> def on_write(*args): >> ????s?=?var.get() >> ????if?len(s)?>?max_len: >> ????????var.set(s[:max_len]) Define a function that doesn't care about the arguments passed to it. It reads?the current value of the StringVar 'var' and, if necessary, trims it to 'max_len_' characters. >> var.trace_variable("w", on_write) Tell the StringVar to call the function on_write() every time its value is changed. So every time the user edits the data in the Entry, in turn the Entry changes the data of the StringVar, which calls the on_write() function which may or may not change the StringVar -- and that change is reflected in what the Entry displays. This smells like an endless loop, but so far we seem to be lucky... If you look again at Fredrik Lundh's ValidatingEntry, you will find all the elements explained above packed nicely into one class, with the extra refinement that he keeps another copy of the value which is used to restore the old state when the new value is found to be invalid. Peter From cantabile.03 at wanadoo.fr Sun Jun 12 20:12:22 2005 From: cantabile.03 at wanadoo.fr (cantabile) Date: Mon, 13 Jun 2005 02:12:22 +0200 Subject: Get drives and partitions list (Linux) Message-ID: <42accf62$0$11720$8fcfb975@news.wanadoo.fr> Hi, I'd like to get drives and partitions (and their size too) with python under Linux. So far, I thought of reading /proc/partitions but maybe i could use fdsik also ? How would I do that in python ? Thanks for your help (newbie here :) ) From davecook at nowhere.net Sun Jun 19 12:37:29 2005 From: davecook at nowhere.net (Dave Cook) Date: Sun, 19 Jun 2005 16:37:29 GMT Subject: extreme newbie References: <1119055296.405442.91560@f14g2000cwb.googlegroups.com> <11b6vdcnqdnsm4a@corp.supernews.com> <1119068711.730364.215290@g47g2000cwa.googlegroups.com> <42B3AC76.2060504@lexicon.net> <1119080561.407266.319960@o13g2000cwo.googlegroups.com> <1119097400.061145.247190@z14g2000cwz.googlegroups.com> Message-ID: On 2005-06-18, cpunerd4 wrote: > thanks all for the advice. The reason I was thinking about using java > (or C or something) was that it is a little more secure than > distributing the source code isn't it? 14 and he already wants to horde his source code. Dave Cook From benji at benjiyork.com Tue Jun 21 08:36:15 2005 From: benji at benjiyork.com (Benji York) Date: Tue, 21 Jun 2005 08:36:15 -0400 Subject: eval() in python In-Reply-To: References: <1119353539.441005.108180@g47g2000cwa.googlegroups.com> Message-ID: <42B809BF.10809@benjiyork.com> harold fellermann wrote: > >>> s="print 'hello Xah Lee :-)'" > >>> exec(s) > hello Xah Lee :-) Note that because "exec" is a statement, the parentheses above are superfluous. -- Benji York From fperez.net at gmail.com Thu Jun 2 14:24:45 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 02 Jun 2005 12:24:45 -0600 Subject: PYSH? (was:Re: calling ksh script from python) References: <1117722690.144752.82250@g14g2000cwa.googlegroups.com> <429F3FDA.3080402@ulmcnett.com> Message-ID: Paul McNett wrote: > Cameron Laird wrote: >> Infidel. While I sure feel that way about csh(1), it >> surprises me you'd criticize ksh(1) so. 'Fact, 'mong >> all the *sh-s, I *recommend* ksh for programming. May- >> be the two of us see things differently. > > I keep wondering how difficult it would be to make a Python shell that > exposes all of Python but also includes some builtin commands such as > cd, mkdir, etc., that are just names bound to os.chdir, os.mkdir..., and > is smart enough to take a given command from the user and try to do a > os.system() on it based on the path. IOW, I'd love to have all of Python > available as my unix shell, while still doing shell-type stuff such as > traversing directories, launching applications, etc. > > There's likely a project that does this already that I'm just unaware of. yes, there is: planck[~]> ipython -p pysh Welcome to pysh, a set of extensions to IPython for shell usage. help(pysh) -> help on the installed shell extensions and syntax. Python 2.3.4 (#1, Feb 2 2005, 12:11:53) Type "copyright", "credits" or "license" for more information. IPython 0.6.15 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. IPython profile: pysh fperez at planck[~]|1> cd test fperez at planck[~/test]|2> ls argv.py* cf.py div.py exit.py* lcomp.py sanner.py* times.sh* ast.tcl* data error.py* foo.old pplot2.py* scopes.py* t.py avg.py* die.py err.py foo.py pplot.py* splot.py vars.py bar.py div.c err.pyc inspectbug.py pylabug.py strings.py visex.py bar.pyc div.f exit2.py* inter.py ramptest.py* tgp.py xplot.py* fperez at planck[~/test]|3> $$a=ls e*py fperez at planck[~/test]|4> a <4> ['error.py', 'err.py', 'exit2.py', 'exit.py'] fperez at planck[~/test]|5> for f in a: |.> if len(f)>6: |.> wc -l $f |.> 64 error.py 2 exit2.py 10 exit.py fperez at planck[~/test]|6> Exit Cheers, f